Hi, I have a very simple question. How to assign a certain value to certain nodes? Following is my minimum working code trying to assign values of mesh nodes in u to that in h:
from dolfin import *
import numpy as np
mesh = UnitSquareMesh(10,10)
V = FunctionSpace(mesh, "CG", 1)
x = V.tabulate_dof_coordinates()
point = [0.2,0.9]
# Locate which row of
index = np.where((x == point).all(axis=1))[0][0]
u = Function(V)
u.vector().vec().setValueLocal(index, 2)
print(u.vector().get_local())
@dokken Hi, dokken. I’m using the method you provided above to solve my PDE problems. This method works perfectly when the FunctionSpace is in first order. But when it comes to second order, the method seems can’t work properly. Following is a simple example showing this problem:
from dolfin import *
import numpy as np
mesh=UnitSquareMesh(2,2)
V=FunctionSpace(mesh,'CG',2)
u=TrialFunction(V)
v=TestFunction(V)
#define u0 by dirictly interpolate and then solve
u0=interpolate(Constant(2),V)
a=u*v*dx+inner(grad(u),grad(v))*dx
L=u0*v*dx+1*v*ds
ux=Function(V)
solve(a==L,ux)
print(ux.vector().get_local())
#define u0 by assign values to each nodes and then solve
u02=Function(V)
x = V.tabulate_dof_coordinates()
for point in mesh.coordinates():
index = np.where((x == point).all(axis=1))[0][0]
u02.vector().vec().setValueLocal(index, 2)
L=u02*v*dx+1*v*ds
solve(a==L,ux)
print(ux.vector().get_local())
Here I used two ways to define the u0 for the simple Poisson equation: 1.by directly interpolate a constant value; 2. by assign the value to each nodes of a Function(V). Then the u0 was used to solve the Poisson problem and the solutions for the two definition methods were compared. When the FunctionSpace’s degree is 1, the two solution were exactly the same:
It seems the above assigning method cannot be directly used in second order space. What can I do to improve this method to make it also workable in higher order space? Many thanks.
When you interpolate a constant over the whole space, every degree of freedom is set to 2.
When you assign to nodes, you assign to the vertices of your mesh (this means that not every dof is assigned the value 2, as a second order space has degrees of freedom on the facets).
Hi @dokken, I have a similar problem, in which I need to assign the value 0 to all DOFs of a vector at a single point (say, the origin of my domain). I have tried to implement it similarly to your answer, but it doesn’t work when running in parallel. Basically, I’ve tried
for dof in origin_dofs: # origin_dofs is a np array that contains the DOF id at the origin
z.vector().vec().setValueLocal(dof, 0.)
z_old.vector().vec().setValueLocal(dof, 0.)
z.vector().apply('insert')
z_old.vector().apply('insert')
The program stops running when it gets to the apply() method.