Hi, I am using legacy fenics and trying to initialize the vector field with unit vectors of random directions.
from dolfin import *
import numpy as np
mesh = Mesh()
mesh = BoxMesh(Point(0,0,0), Point(1,1,1), 1, 1, 1)
x = SpatialCoordinate(mesh)
vector1 = VectorElement("Lagrange", mesh.ufl_cell(), 1)
scalar1 = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
scalarspace = FunctionSpace(mesh, scalar1)
vectorspace = FunctionSpace(mesh, vector1)
v0 = Function(vectorspace)
num_dofs = vectorspace.dim()
dim = mesh.geometry().dim()
num_nodes = num_dofs // dim
rand_vec = np.random.rand(num_nodes, dim)
norms = np.linalg.norm(rand_vec, axis=1, keepdims=True)
rand_vecs = rand_vec / norms
dofx = vectorspace.sub(0).dofmap().dofs()
dofy = vectorspace.sub(1).dofmap().dofs()
dofz = vectorspace.sub(2).dofmap().dofs()
for i in range(num_nodes):
v0.vector()[dofx[i]] = rand_vecs[i][0]
v0.vector()[dofy[i]] = rand_vecs[i][1]
v0.vector()[dofz[i]] = rand_vecs[i][2]
normv0 = project(dot(v0,v0),scalarspace)
print(normv0.vector()[:])
output_file = XDMFFile("test.xdmf")
output_file.parameters["flush_output"] = True
output_file.parameters["functions_share_mesh"] = True
v0.rename("v0", "v0")
normv0.rename("testscal", "testscal")
output_file.write(v0, float(0.0))
output_file.write(normv0, float(0.0))
In paraview, when I open the âtest.xdmfâ file, the magnitudes of v0 are 1 everywhere in the mesh. But normv0, the norm of v0, is not one. âinnerâ instead of âdotâ also does not work. I cannot figure it outâŚ