Hello,
I would like to access a Function vector and perform numpy operations on values assembled from all MPI processes. Specifically, I'd like to be able to store data (interpolating the vector data onto a line) into a text/pickle file that I can load
import numpy as np
newX = np.asarray(x.vector()[:])
print newX*1.
Is there a recommended way to do this? I've attached a minimal(ish) example that fails for more than 1 processor? Thanks in advance
Pete
from dolfin import *
dolf=1
# Define Dirichlet boundary (x = 0 or x = 1)
class leftBoundary(SubDomain):
def inside(self,x,on_boundary):
outer = x[0] < DOLFIN_EPS
return outer and on_boundary
# Define Dirichlet boundary (x = 0 or x = 1)
class elseBoundary(SubDomain):
def inside(self,x,on_boundary):
outer = x[0] >=DOLFIN_EPS
return outer and on_boundary
class rightBoundary(SubDomain):
def inside(self,x,on_boundary):
outer = x[0] >=(1-DOLFIN_EPS)
return outer and on_boundary
# Create mesh and define function space
def doit(filename="none"):
# Create mesh and define function space
if(filename=="none"):
#mesh = UnitCube(8,8,8)
mesh = UnitCubeMesh(16,16,16)
V = FunctionSpace(mesh, "Lagrange", 1)
dims = mesh.ufl_cell().geometric_dimension()
# Define boundary condition
subdomains = MeshFunction("size_t",mesh,dims)
subsurfaces = MeshFunction("size_t",mesh,dims-1)
boundary = leftBoundary()
leftmarker = 2
boundary.mark(subsurfaces,leftmarker)
boundary = rightBoundary()
elsemarker = 3
boundary.mark(subsurfaces,elsemarker)
ds = Measure("ds")[subsurfaces]
dx = Measure('dx')[subdomains]
# save
bcs = []
u0 = Constant(1.0)
bcs.append(DirichletBC(V, u0, subsurfaces,leftmarker))
u0 = Constant(0.0)
bcs.append(DirichletBC(V, u0, subsurfaces,elsemarker))
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
# Solve
pv = Constant(1.)
if(dolf==1):
form = pv * inner(grad(u), grad(v))*dx(domain=mesh)
g = Constant(0.)
form += g*v*dx
# Compute solution
a = lhs(form)
L = rhs(form)
x = Function(V)
solve(a == L, x, bcs)
tot = assemble(x*dx)
vol = assemble(Constant(1.)*dx(domain=mesh))
conc = tot/vol
print "Tot/Vol/Conc %f %f %f" %(tot,vol,conc)
# NOT MPI SAFE
#print x([0.5,0.5,0.5])
if MPI.rank(mpi_comm_world())==0:
# still unsafe
#print x([0.5,0.5,0.5])
1
import numpy as np
newX = np.asarray(x.vector()[:])
print newX*1.
return x
doit()