Problem with assigning vectors to nodes in a mesh

In the below MWE, I have unit square mesh with two elements. The four nodes of the mesh have the coordinates

[[0. 0.]
 [1. 0.]
 [0. 1.]
 [1. 1.]]

I want to define a function that assigns vectors to each of the nodes. For example, if

B = [
  [1.0, 5.0],
  [7.0, 1.0],
  [9.0, 10.0],
  [13.0, 5.0]
]

then I want u(0,0)=[1.0,5.0], u(1,0)=[7,1], u(0,1)=[9,10], and u(1,1)=[13,5]

So I tried the following MWE:

mesh = UnitSquareMesh(1, 1)
mesh_coords = mesh.coordinates()

V = VectorFunctionSpace(mesh, 'P', 1)

B = as_matrix([[1.0,5.0],[7.0,1.0],[9.0,10.0],[13.0,5.0]])

u = Function(V)

for i in range(0,len(mesh_coords)):

  u(mesh_coords[:,:][i]) = B[:,:][i]

This produces the error

SyntaxError: cannot assign to function call

What is wrong with the way I am assigning the vectors to the function? Any suggestion would be greatly appreciated.

See: Mapping from mesh.coordinates() to u.vector() - #2 by dokken

Hi @dokken ,

I went through the post that you suggested but couldn’t exactly figure out what you were suggesting. My apologies if it were a trivial thing that I couldn’t figure out. So I tried the following:

mesh = UnitSquareMesh(1, 1)  
mesh_coords = mesh.coordinates() 
V = VectorFunctionSpace(mesh, 'CG', 1) 

u = Function(V) # Introducing a function u on the vector function space

v2d = np.array(vertex_to_dof_map(V), dtype = int)
B = as_matrix([[1.0,5.0],[7.0,1.0],[9.0,10.0],[13.0,5.0]]) 

for i in range(0,len(v2d)):
  u.vector()[v2d[i]] = B.vector()[i]

This returns the error

SyntaxError: cannot assign to function call

Consider the following MWE:

from dolfin import *
import numpy as np
mesh = UnitSquareMesh(1, 1)  
mesh_coords = mesh.coordinates() 
V = VectorFunctionSpace(mesh, 'CG', 1) 

u = Function(V) # Introducing a function u on the vector function space

v2d = np.array(vertex_to_dof_map(V), dtype = int)
B = np.array([[1.0,5.0],[7.0,1.0],[9.0,10.0],[13.0,5.0]])
for i in range(0,len(v2d)):
  u.vector()[v2d[i]] = B[int(i/2), i%2]

dof_coords = V.tabulate_dof_coordinates()
for i, vertex in enumerate(mesh_coords):
    print(f"Vertex {i} Coordinate {vertex} value {B[i]}")

for i in range(mesh_coords.shape[0]):
    for j in range(2):
        print(f"Component: {j}, Dof coord {dof_coords[2*i+j]}, value {u.vector()[2*i+j]}")

For 3D problems the 2 hardcoded in this problem has to be replaced with 3

1 Like

Thanks @dokken , that worked.