How to create a Matrix (dolfin.cpp.la.Matrix) from Vectors (dolfin.cpp.la.Vector)?

Hi all:

I have several vectors (<dolfin.cpp.la.Vector at…) and I need to create a matrix<dolfin.cpp.la.Matrix at…) from them like this (every column of the matrix will be a vector):

A = [vector1, vector2, vector3, …]

I would like to know how to do that with these dolfin object types.

Thank you so much and regards

Maybe it is a non-sense question. I am in a python environment with those dolfin objects. I tried “as_matrix” but did not work :frowning:
I would appreciate a hint about that.

As always, you should second-guess any procedure that results in a dense matrix, but, if it’s really necessary, one approach could be the following:

from dolfin import *
from petsc4py import PETSc
from numpy import array

# Get some dolfin.cpp.la.Vector objects:
mesh = UnitIntervalMesh(10)
V = FunctionSpace(mesh,"DG",0)
v = TestFunction(V)
v1 = assemble(Constant(1.0)*v*dx)
v2 = assemble(Constant(2.0)*v*dx)
v3 = assemble(Constant(3.0)*v*dx)

# Put them all into a NumPy matrix:
npMat = array([v1.get_local(),
               v2.get_local(),
               v3.get_local()]).transpose()
print(npMat)

# Create a PETSc dense matrix, with the
# petsc4py API, then wrap that as a
# dolfin.cpp.la.PETScMatrix object:
petMat = PETSc.Mat()
petMat.createDense(npMat.shape,array=npMat)
petMat.setUp()
mat = PETScMatrix(petMat)

print(mat.array())

Thank you so much kamensky, that does the trick!!! :clap:

Hi Kamensky,

Thank you for the answer and it is very helpful. I am trying to do something like this to add some forces to the system manually:

add forces

F0 = assemble(RHS)
F0.add_local(forces)
F = as_backend_type(F0)
bc.apply(F)

assemble matrix

K = PETScMatrix()
assemble(LHS, tensor=K)
bc.apply(K)
K_array = K.array()
petMat = PETSc.Mat()
petMat.createDense(K_array.shape,array=K_array)
mat = PETScMatrix(petMat)

solve my matrix and FEniCS matrix:

solve(mat, u.vector(), F, “bicgstab”, “amg”)
solve(K, u.vector(), F, “bicgstab”, “amg”)

These two are solving in very different time, when FEniCS matrix K is solved in a second but the assembled mat needs minutes. Could you let me know where I am doing wrong?

Many thanks!

Does anyone know how to convert a numpy array to a dolfin.cpp.la.PETScVector?

You may want to have a look at PETScVector.set_local.