def read(self, t, field_name=None): with open(self.jsonfilename) as jsonfile: fieldsDict = json.load(jsonfile, object_pairs_hook=OrderedDict) jsonfile.close() self.mesh = self.load_mesh() if self.field_name is None: self.field_name = field_name self.fs_type = fieldsDict[self.field_name]['metadata']['type'] self.family = fieldsDict[self.field_name]['metadata']['family'] self.degree = fieldsDict[self.field_name]['metadata']['degree'] if self.fs_type == 'vector': self.dim = fieldsDict[self.field_name]['metadata']['dim'] self.functionspace = df.VectorFunctionSpace( self.mesh, self.family, self.degree, self.dim) elif self.fs_type == 'scalar': self.functionspace = df.FunctionSpace(self.mesh, str(self.family), self.degree) name = str([ item[0] for item in fieldsDict[self.field_name]['data'].items() if abs(item[1] - t) < 1e-10 ][0]) f_loaded = df.Function(self.functionspace) self.h5file.read(f_loaded, name) return f_loaded
def setUp(self): np.random.seed(1) #self.dim = np.random.randint(1, high=5) self.dim = 1 self.means = np.random.uniform(-10, high=10., size=self.dim) self.chol = np.tril( np.random.uniform(1, high=10, size=(self.dim, self.dim))) self.cov = np.dot(self.chol, self.chol.T) self.precision = np.linalg.inv(self.cov) mesh = dl.RectangleMesh(dl.mpi_comm_world(), dl.Point(0.0, 0.0), dl.Point(3, 2), 6, 4) if self.dim > 1: self.Rn = dl.VectorFunctionSpace(mesh, "R", 0, dim=self.dim) else: self.Rn = dl.FunctionSpace(mesh, "R", 0) self.test_prior = GaussianRealPrior(self.Rn, self.cov) m = dl.Function(self.Rn) m.vector().zero() m.vector().set_local(self.means) self.test_prior.mean.axpy(1., m.vector())
def load_local_basis(h5file, lgroup, mesh, geo): if h5file.has_dataset(lgroup): # Get local bais functions local_basis_attrs = h5file.attributes(lgroup) lspace = local_basis_attrs["space"] family, order = lspace.split("_") namesstr = local_basis_attrs["names"] names = namesstr.split(":") if DOLFIN_VERSION_MAJOR > 1.6: elm = dolfin.VectorElement( family=family, cell=mesh.ufl_cell(), degree=int(order), quad_scheme="default", ) V = dolfin.FunctionSpace(mesh, elm) else: V = dolfin.VectorFunctionSpace(mesh, family, int(order)) for name in names: lb = Function(V, name=name) io_utils.read_h5file(h5file, lb, lgroup + "/{}".format(name)) setattr(geo, name, lb) else: setattr(geo, "circumferential", None) setattr(geo, "radial", None) setattr(geo, "longitudinal", None)
def unitcube_geometry(): N = 3 mesh = UnitCubeMesh(mpi_comm_world(), N, N, N) ffun = dolfin.MeshFunction("size_t", mesh, 2) ffun.set_all(0) fixed.mark(ffun, fixed_marker) free.mark(ffun, free_marker) marker_functions = MarkerFunctions(ffun=ffun) # Fibers V_f = dolfin.VectorFunctionSpace(mesh, "CG", 1) f0 = interpolate(Expression(("1.0", "0.0", "0.0"), degree=1), V_f) s0 = interpolate(Expression(("0.0", "1.0", "0.0"), degree=1), V_f) n0 = interpolate(Expression(("0.0", "0.0", "1.0"), degree=1), V_f) microstructure = Microstructure(f0=f0, s0=s0, n0=n0) geometry = Geometry( mesh=mesh, marker_functions=marker_functions, microstructure=microstructure, ) return geometry
def get_demagfield(self, phi=None, use_default_function_space=True): """ Returns the projection of the negative gradient of phi onto a DG0 space defined on the same mesh Note: Do not trust the viper solver to plot the DeMag field, it can give some wierd results, paraview is recommended instead use_default_function_space - If true project into self.W, if false project into a Vector DG0 space over the mesh of phi. """ if phi is None: phi = self.phi Hdemag = -df.grad(phi) if use_default_function_space == True: Hdemag = df.project(Hdemag, self.W) else: if self.D == 1: Hspace = df.FunctionSpace(phi.function_space().mesh(), "DG", 0) else: Hspace = df.VectorFunctionSpace(phi.function_space().mesh(), "DG", 0) Hdemag = df.project(Hdemag, Hspace) return Hdemag
def efield_DG0(mesh, phi): Q = df.VectorFunctionSpace(mesh, 'DG', 0) q = df.TestFunction(Q) M = (1.0 / df.CellVolume(mesh)) * df.inner(-df.grad(phi), q) * df.dx E_dg0 = df.assemble(M) return df.Function(Q, E_dg0)
def _space(mesh, rank): if rank==0: return dolfin.FunctionSpace(mesh, "CG", 1) elif rank==1: return dolfin.VectorFunctionSpace(mesh, "CG", 1) else: raise Exception("Loading Functions of rank > 1 is not supported.")
def set_spaces_functions(self, p): # p: int, polynomial order of trial/test functions nvar = self.params['nvar'] mesh = self.mesh # Define finite-element spaces U = d.FunctionSpace(mesh, "CG", p) W = d.VectorFunctionSpace(mesh, "CG", p, dim = nvar-1) # Functions for bilinear and linear form self.ut = d.TrialFunction(U) self.du = d.TestFunction(U) self.un = d.Function(U) self.u = d.Function(U) self.w = d.Function(W) # Auxiliar functions self.sig = d.Function(U) # conductivity value self.f = d.Function(U) # conductivity value # Save Spaces self.U = U self.W = W self.ndofs = U.tabulate_dof_coordinates().shape[0]
def test_anisotropy_energy_analytical(fixt): """ Compare one UniaxialAnisotropy energy with the corresponding analytical result. The magnetisation is m = (0, sqrt(1 - x^2), x) and the easy axis still a = (0, 0, 1). The squared dot product in the energy integral thus gives dot(a, m)^2 = x^2. Integrating x^2 gives (x^3)/3 and the analytical result with the constants we have chosen is 1 - 1/3 = 2/3. """ mesh = df.UnitCubeMesh(1, 1, 1) functionspace = df.VectorFunctionSpace(mesh, "Lagrange", 1) K1 = 1 Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 1) a = df.Constant((0, 0, 1)) m = Field(functionspace) m.set(df.Expression(("0", "sqrt(1 - pow(x[0], 2))", "x[0]"), degree=1)) anis = UniaxialAnisotropy(K1, a) anis.setup(m, Ms) E = anis.compute_energy() expected_E = float(2) / 3 print "With m = (0, sqrt(1-x^2), x), expecting E = {}. Got E = {}.".format( expected_E, E) #assert abs(E - expected_E) < TOLERANCE assert np.allclose(E, expected_E, atol=1e-14, rtol=TOLERANCE)
def test_field2_has_more_timesteps_than_field1(): filename = 'file_usage_diff' functionspace = df.VectorFunctionSpace(mesh, 'CG', 1, 3) f1 = df.Function(functionspace) f2 = df.Function(functionspace) h5file = openh5(filename, functionspace, mode='w') h5file.save_mesh() for t in t_array: f1.assign(df.Constant((t, 0, 0))) f2.assign(df.Constant((t, 1, 0))) h5file.write(f1, 'f1', t) h5file.write(f2, 'f2', t) f2.assign(df.Constant((50, 1, 0))) h5file.write(f2, 'f2', t) h5file = openh5(filename, mode='r') print h5file.fields() for field in h5file.fields(): for t in h5file.times(field): h5file.read(t_array[1], field) os.system('rm file_usage_diff.h5') os.system('rm file_usage_diff.json')
def get_field(self): """ compute field .. todo:: find better representation for real and imaginary part .. todo:: decide whether field should be of same order as solution """ self.logger.debug("Entering Field computation") if self.data['degree'] > 1: self.Vector = d.VectorFunctionSpace( self.mesh.mesh, self.data['properties']['project_element'], self.data['properties']['project_degree']) else: raise Exception( "Use for this computation a 2nd or higher order element") self.Efield_real = d.project(-d.grad(self.u.sub(0)), self.Vector, solver_type='mumps') self.Efield_imag = d.project(-d.grad(self.u.sub(1)), self.Vector, solver_type='mumps') self.Efield_real.rename('E-field real', 'E-field real') self.Efield_imag.rename('E-field imag', 'E-field imag') self.logger.debug("Computed E-Field")
def test_volume(volumes): geo = pulse.HeartGeometry.from_file(pulse.mesh_paths["simple_ellipsoid"]) V_cg2 = dolfin.VectorFunctionSpace(geo.mesh, "CG", 2) u = dolfin_adjoint.Function(V_cg2) volume_obs = VolumeObservation(mesh=geo.mesh, dmu=geo.ds(geo.markers["ENDO"]), description="Test LV volume") model_volume = volume_obs(u).vector().get_local()[0] target = OptimizationTarget(volumes, volume_obs, collect=True) if np.isscalar(volumes): volumes = (volumes, ) fs = [] for t, v in zip(target, volumes): fun = dolfin.project(t.assign(u), t._V) f = fun.vector().get_local()[0] fs.append(f) g = (model_volume - v)**2 assert abs(f - g) < 1e-12 # We collect the data assert np.all( np.subtract( np.squeeze([v.get_local() for v in target.collector["data"]]), volumes) < 1e-12) assert np.all( np.subtract( np.squeeze([v.get_local() for v in target.collector["model"]]), model_volume) < 1e-12) assert np.all(np.subtract(target.collector["functional"], fs) < 1e-12)
def main(): problem, control = fixtures.create_problem() geo = problem.geometry V_cg2 = dolfin.VectorFunctionSpace(geo.mesh, "CG", 2) u = dolfin.Function(V_cg2) volume_obs = VolumeObservation(mesh=geo.mesh, dmu=geo.ds(geo.markers["ENDO"]), description="Test LV volume") model_volume = volume_obs(u).vector().get_local()[0] print(model_volume) volumes = (2.7, 2.9) # volumes = (2.7,) target = OptimizationTarget(volumes, volume_obs, collect=True) lvp = [0.5, 1.0] # lvp = [0.5] bcs = BoundaryObservation(bc=problem.bcs.neumann[0], data=lvp) assimilator = Assimilator(problem, target, bcs, control) assimilator.assimilate() from IPython import embed embed() exit()
def test_crossprod(): """ Compute the cross product of two functions f and g numerically using `helpers.crossprod` and compare with the analytical expression. """ xmin = ymin = zmin = -2 xmax = ymax = zmax = 3 nx = ny = nz = 10 mesh = df.BoxMesh(df.Point(xmin, ymin, zmin), df.Point(xmax, ymax, zmax), nx, ny, nz) V = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3) u = df.interpolate(df.Expression(['x[0]', 'x[1]', '0'], degree=1), V) v = df.interpolate(df.Expression(['-x[1]', 'x[0]', 'x[2]'], degree=1), V) w = df.interpolate( df.Expression(['x[1]*x[2]', '-x[0]*x[2]', 'x[0]*x[0]+x[1]*x[1]'], degree=1), V) a = u.vector().array() b = v.vector().array() c = w.vector().array() axb = crossprod(a, b) assert (np.allclose(axb, c))
def convert3D(mesh3D, *forces): "convert force from axisymmetric 2D simulation to 3D vector function" def rad(x, y): return dolfin.sqrt(x**2 + y**2) class Convert3DExpression(dolfin.Expression): def __init__(self, F, **kwargs): self.F = F def value_shape(self): return (3,) def eval(self, value, x): r = rad(x[0], x[1]) F = self.F([r, x[2]]) if r==0.: value[0] = 0. value[1] = 0. value[2] = F[1] else: value[0] = x[0]/r*F[0] value[1] = x[1]/r*F[0] value[2] = F[1] #U = dolfin.FunctionSpace(mesh3D, "CG", 1) #V = dolfin.MixedFunctionSpace([U, U, U]) V = dolfin.VectorFunctionSpace(mesh3D, "CG", 1) def to3D(F): F2 = dolfin.project(Convert3DExpression(F, degree=1), V) #F2 = dolfin.Function(V) #F2.interpolate(Convert3DExpression(F)) return F2 return tuple(map(to3D, forces))
def test_exchange_field_supported_methods(fixt): """ Check that all supported methods give the same results as the default method. """ A = 1 REL_TOLERANCE = 1e-12 mesh = df.UnitCubeMesh(10, 10, 10) Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 1) functionspace = df.VectorFunctionSpace(mesh, "CG", 1, 3) m = Field(functionspace) m.set(df.Expression(("0", "sin(x[0])", "cos(x[0])"), degree=1)) exch = Exchange(A) exch.setup(m, Ms) H_default = exch.compute_field() supported_methods = list(Exchange._supported_methods) # no need to compare default method with itself supported_methods.remove(exch.method) # the project method for the exchange is too bad supported_methods.remove("project") for method in supported_methods: exch = Exchange(A, method=method) exch.setup(m, Ms) H = exch.compute_field() print "With method '{}', expecting H =\n{}\n, got H =\n{}.".format( method, H_default.reshape((3, -1)).mean(1), H.reshape((3, -1)).mean(1)) rel_diff = np.abs((H - H_default) / H_default) assert np.nanmax(rel_diff) < REL_TOLERANCE
def diffusivity_field_simple(setup, r, ddata_bulk, boundary="poresolidb"): "interpolates diffusivity field defined on the geometry given by setup" # build 1D interpolations from data fn, ft = preprocess_Dr(ddata_bulk, r) setup.prerefine(visualize=True) dist = distance_boundary_from_geo(setup.geo, boundary) VV = dolfin.VectorFunctionSpace(setup.geo.mesh, "CG", 1) normal = dolfin.project(dolfin.grad(dist), VV) phys = setup.phys D0 = phys.kT / (6. * np.pi * phys.eta * r * 1e-9) def DBulk(x, i): r = dist(x) n = normal(x) Dn = D0 * float(fn(r)) Dt = D0 * float(ft(r)) D = transformation(n, Dn, Dt) return D[i][i] D = lambda i: dict(fluid=lambda x: DBulk(x, i), ) dim = setup.geop.dim DD = [harmonic_interpolation(setup, subdomains=D(i)) for i in range(dim)] D = dolfin.Function(VV) dolfin.assign(D, DD) return dict(dist=dist, D=D)
def test_exchange_energy_analytical_2(): """ Compare one Exchange energy with the corresponding analytical result. """ REL_TOLERANCE = 5e-5 lx = 6 ly = 3 lz = 2 nx = 300 ny = nz = 1 mesh = df.BoxMesh(df.Point(0, 0, 0), df.Point(lx, ly, lz), nx, ny, nz) unit_length = 1e-9 functionspace = df.VectorFunctionSpace(mesh, "CG", 1, 3) Ms = Ms = Field(df.FunctionSpace(mesh, 'DG', 0), 8e5) A = 13e-12 m = Field(functionspace) m.set( df.Expression(['0', 'sin(2*pi*x[0]/l_x)', 'cos(2*pi*x[0]/l_x)'], l_x=lx, degree=1)) exch = Exchange(A) exch.setup(m, Ms, unit_length=unit_length) E_expected = A * 4 * pi ** 2 * \ (ly * unit_length) * (lz * unit_length) / (lx * unit_length) E = exch.compute_energy() print "expected energy: {}".format(E) print "computed energy: {}".format(E_expected) assert abs((E - E_expected) / E_expected) < REL_TOLERANCE
def __init__(self, mesh, orientation): # Manifold assumption assert 1 <= mesh.topology().dim() < mesh.geometry().dim() gdim = mesh.geometry().dim() # Orientation from inside point if isinstance(orientation, (list, np.ndarray, tuple)): assert len(orientation) == gdim kwargs = {'x0%d' % i: val for i, val in enumerate(orientation)} orientation = ['x[%d] - x0%d' % (i, i) for i in range(gdim)] orientation = df.Expression(orientation, degree=1, **kwargs) assert orientation.ufl_shape == (gdim, ) V = df.VectorFunctionSpace(mesh, 'DG', 0, gdim) df.Function.__init__(self, V) n_values = self.vector().get_local() values = [] for cell in df.cells(mesh): n = cell.cell_normal().array()[:gdim] x = cell.midpoint().array()[:gdim] # Disagree? if np.inner(orientation(x), n) < 0: n *= -1 values.append(n / np.linalg.norm(n)) values = np.array(values) for sub in range(gdim): dofs = V.sub(sub).dofmap().dofs() n_values[dofs] = values[:, sub] self.vector().set_local(n_values) self.vector().apply('insert')
def generate_function_spaces(self, order=1, use_periodic=False): r""" Generates the finite-element function spaces used with topological dimension :math:`d` set by variable ``self.top_dim``. :param order: order :math:`k` of the shape function, currently only supported are Lagrange :math:`P_1` elements. :param use_periodic: use periodic boundaries along lateral boundary (currently not supported). :type use_periodic: bool The element shape-functions available from this method are : * ``self.Q`` -- :math:`\mathcal{H}^k(\Omega)` * ``self.Q3`` -- :math:`[\mathcal{H}^k(\Omega)]^3` * ``self.V`` -- :math:`[\mathcal{H}^k(\Omega)]^d` formed using :func:`~dolfin.functions.functionspace.VectorFunctionSpace` * ``self.T`` -- :math:`[\mathcal{H}^k(\Omega)]^{d \times d}` formed using :func:`~dolfin.functions.functionspace.TensorFunctionSpace` """ s = "::: generating fundamental function spaces of order %i :::" % order print_text(s, cls=self.this) if use_periodic: self.generate_pbc() else: self.pBC = None order = 1 space = 'CG' Qe = dl.FiniteElement("CG", self.mesh.ufl_cell(), order) self.Q3 = dl.FunctionSpace(self.mesh, dl.MixedElement([Qe] * 3)) self.Q = dl.FunctionSpace(self.mesh, space, order) self.V = dl.VectorFunctionSpace(self.mesh, space, order) self.T = dl.TensorFunctionSpace(self.mesh, space, order) s = " - fundamental function spaces created - " print_text(s, cls=self.this)
def setup(): """ Create a cuboid mesh representing a magnetic material and two dolfin.Functions defined on this mesh: m -- unit magnetisation (linearly varying across the sample) Ms_func -- constant function representing the saturation magnetisation Ms *Returns* A triple (m_space, m, Ms_func), where m_space is the VectorFunctionSpace (of type "continuous Lagrange") on which the magnetisation m is defined and m, Ms_funct are as above. """ m_space = df.VectorFunctionSpace(mesh, "CG", 1) m = Field(m_space, value=df.Expression(("1e-9", "x[0]/10", "0"), degree=1)) m.set_with_numpy_array_debug(fnormalise(m.get_numpy_array_debug())) Ms_space = df.FunctionSpace(mesh, "DG", 0) Ms_func = df.interpolate(df.Constant(Ms), Ms_space) return m_space, m, Ms_func
def load_vector_field_hdf5(hdf, name, mesh, pd): """ Load a vector-valued function from an HDF5 file. Parameters ---------- hdf : str, dolfin.HDF5File The name of the file where the cell functions are stored, or the handle to the an HDF5 file. name : str The name under which the vector-valued function is stored in the HDF5 file. mesh : dolfin.Mesh The computational mesh over which the fiber directions need to be defined. This is needed to create the corresponding mesh functions. pd : int The polynomial degree used to approximate the vector field describing the fiber directions. Returns ------- vector_field : dolfin.Function The vector-valued dolfin.Function object describing the fiber directions. """ family = "DG" if pd == 0 else "CG" V = dlf.VectorFunctionSpace(mesh, family, pd) vector_field = dlf.Function(V) hdf.read(vector_field, name) return vector_field
def convert2D(mesh2D, *forces): "convert force from axisymmetric 2D simulation to 2D vector function" dolfin.parameters['allow_extrapolation'] = False class Convert2DExpression(dolfin.Expression): def __init__(self, F, **kwargs): self.F = F def value_shape(self): return (2, ) def eval(self, value, x): r = abs(x[0]) F = self.F([r, x[1]]) if r == 0.: value[0] = 0. value[1] = F[1] else: value[0] = x[0] / r * F[0] value[1] = F[1] #U = dolfin.FunctionSpace(mesh2D, "CG", 1) #V = dolfin.MixedFunctionSpace([U, U]) V = dolfin.VectorFunctionSpace(mesh2D, "CG", 1) def to2D(F): F2 = dolfin.project(Convert2DExpression(F, degree=1), V) #F2 = dolfin.Function(V) #F2.interpolate(Convert3DExpression(F)) return F2 return tuple(map(to2D, forces))
def convert_meshfunctions_to_vectorfunction(meshfunctions, functionspace=None): """ Convert a list of mesh functions to a vector-valued dolfin.Function object. Parameters ---------- meshfunctions : list, tuple The list/tuple of mesh function objects used to create a vector-valued function. These are first converted to scalar-valued functions, and then they are assigned to the components of the vector-valued function. functionspace : dolfin.FunctionSpace (default None) The function space used to create the dolfin.Function object. A new function space with element 'p0' is created if None is provided. Returns ------- vector_func : dolfin.Function The vector-valued dolfin.Function object created to describe the fiber directions specified by the list of mesh functions. """ func_components = list() for i, mf in enumerate(meshfunctions): func_components.append(convert_meshfunction_to_function(mf)) mesh = meshfunctions[0].mesh() if functionspace is None: functionspace = dlf.VectorFunctionSpace(mesh, "DG", 0) vector_func = dlf.Function(functionspace) assign_scalars_to_vectorfunctions(func_components, vector_func) return vector_func
def __init__(self, mesh, Ms=8e5, unit_length=1.0, name='unnamed', auto_save_data=True): self.mesh = mesh self.unit_length=unit_length self.DG = df.FunctionSpace(mesh, "DG", 0) self.DG3 = df.VectorFunctionSpace(mesh, "DG", 0, dim=3) self._m = df.Function(self.DG3) self.Ms = Ms self.nxyz_cell=mesh.num_cells() self._alpha = np.zeros(self.nxyz_cell) self.m = np.zeros(3*self.nxyz_cell) self.H_eff = np.zeros(3*self.nxyz_cell) self.dm_dt = np.zeros(3*self.nxyz_cell) self.set_default_values() self.auto_save_data = auto_save_data self.sanitized_name = helpers.clean_filename(name) if self.auto_save_data: self.ndtfilename = self.sanitized_name + '.ndt' self.tablewriter = Tablewriter(self.ndtfilename, self, override=True)
def setup(self): """ Create mesh velocity and deformation functions """ sim = self.simulation assert self.active is False, 'Trying to setup mesh morphing twice in the same simulation' # Store previous cell volumes mesh = sim.data['mesh'] Vcvol = dolfin.FunctionSpace(mesh, 'DG', 0) sim.data['cvolp'] = dolfin.Function(Vcvol) # The function spaces for mesh velocities and displacements Vmesh = dolfin.FunctionSpace(mesh, 'CG', 1) Vmesh_vec = dolfin.VectorFunctionSpace(mesh, 'CG', 1) sim.data['Vmesh'] = Vmesh # Create mesh velocity functions u_mesh = [] for d in range(sim.ndim): umi = dolfin.Function(Vmesh) sim.data['u_mesh%d' % d] = umi u_mesh.append(umi) u_mesh = dolfin.as_vector(u_mesh) sim.data['u_mesh'] = u_mesh # Create mesh displacement vector function self.displacement = dolfin.Function(Vmesh_vec) self.assigners = [ dolfin.FunctionAssigner(Vmesh_vec.sub(d), Vmesh) for d in range(sim.ndim) ] self.active = True
def make_crl_basis(mesh, foc): """ Makes the crl basis for the LV mesh (prolate ellipsoidal) with prespecified focal length. """ VV = dolfin.VectorFunctionSpace(mesh, "CG", 1) V = dolfin.FunctionSpace(mesh, "CG", 1) if DOLFIN_VERSION_MAJOR > 1.6: dofs_x = V.tabulate_dof_coordinates().reshape( (-1, mesh.geometry().dim())) else: dm = V.dofmap() dofs_x = dm.tabulate_all_coordinates(mesh).reshape( (-1, mesh.geometry().dim())) e_c = make_unit_vector(V, VV, dofs_x, fill_coordinates_ec) e_l = make_unit_vector(V, VV, dofs_x, fill_coordinates_el, foc) e_r = calc_cross_products(e_c, e_l, VV) e_c.rename("c0", "local_basis_function") e_r.rename("r0", "local_basis_function") e_l.rename("l0", "local_basis_function") return e_c, e_r, e_l
def test_demag_2d(plot=False): mesh = df.UnitSquareMesh(4, 4) Ms = 1.0 S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3) m0 = df.Expression(("0", "0", "1"), degree=1) m = Field(S3, m0) h = 0.001 demag = Demag2D(thickness=h) demag.setup(m, Ms) print demag.compute_field() f0 = demag.compute_field() m.set_with_numpy_array_debug(f0) print demag.m.probe(0., 0., 0) print demag.m.probe(1., 0., 0) print demag.m.probe(0., 1., 0) print demag.m.probe(1., 1., 0) print '=' * 50 print demag.m.probe(0., 0., h) print demag.m.probe(1., 0., h) print demag.m.probe(0., 1., h) print demag.m.probe(1., 1., h) if plot: df.plot(m.f) df.interactive()
def computeVelocityField(mesh): Xh = dl.VectorFunctionSpace(mesh, 'Lagrange', 2) Wh = dl.FunctionSpace(mesh, 'Lagrange', 1) XW = dl.MixedFunctionSpace([Xh, Wh]) Re = 1e2 g = dl.Expression(('0.0', '(x[0] < 1e-14) - (x[0] > 1 - 1e-14)')) bc1 = dl.DirichletBC(XW.sub(0), g, v_boundary) bc2 = dl.DirichletBC(XW.sub(1), dl.Constant(0), q_boundary, 'pointwise') bcs = [bc1, bc2] vq = dl.Function(XW) (v, q) = dl.split(vq) (v_test, q_test) = dl.TestFunctions(XW) def strain(v): return dl.sym(dl.nabla_grad(v)) F = ((2. / Re) * dl.inner(strain(v), strain(v_test)) + dl.inner(dl.nabla_grad(v) * v, v_test) - (q * dl.div(v_test)) + (dl.div(v) * q_test)) * dl.dx dl.solve(F == 0, vq, bcs, solver_parameters={ "newton_solver": { "relative_tolerance": 1e-4, "maximum_iterations": 100 } }) return v
def __init__(self, mesh): assert 1 <= mesh.topology().dim() < mesh.geometry().dim() gdim = mesh.geometry().dim() V = df.VectorFunctionSpace(mesh, 'DG', 0, gdim) df.Function.__init__(self, V) n_values = self.vector().get_local() X = mesh.coordinates() c2v = mesh.topology()(1, 0) _, v2c = mesh.init(0, 1), mesh.topology()(0, 1) cell_f, bcolors, lcolors = color_branches(mesh) loop_flags = chain(repeat(False, len(bcolors)), repeat(True, len(lcolors))) colors = chain(bcolors, lcolors) cell_f = cell_f.array() values = np.zeros(V.dim()).reshape((-1, gdim)) for color, lf in zip(colors, loop_flags): for cell, orient in walk_cells(cell_f, tag=color, c2v=c2v, v2c=v2c, is_loop=lf): v0, v1 = X[c2v(cell) if orient else c2v(cell)[::-1]] t = (v1 - v0) / np.linalg.norm(v1 - v0) values[cell][:] = t for sub in range(gdim): dofs = V.sub(sub).dofmap().dofs() n_values[dofs] = values[:, sub] self.vector().set_local(n_values) self.vector().apply('insert')