def test_compute_scalar_potential_fk(self): m1 = df.Constant([1, 0, 0]) m2 = df.Expression(["x[0]*x[1]+3", "x[2]+5", "x[1]+7"], degree=1) expressions = [m1, m2] for exp in expressions: for k in xrange(1, 5 + 1): self.run_demag_computation_test( df.UnitCubeMesh(k, k, k), exp, compute_scalar_potential_native_fk, "native, FK", k=k) self.run_demag_computation_test( sphere(1., 1. / k), exp, compute_scalar_potential_native_fk, "native, FK", k=k) self.run_demag_computation_test(MagSphereBase(0.25, 1).mesh, exp, compute_scalar_potential_native_fk, "native, FK", k=k)
def forms(): mesh = dolfin.UnitCubeMesh(MPI.comm_world, MESH_SIZE, MESH_SIZE, MESH_SIZE) cell = mesh.ufl_cell() el_p1 = ufl.FiniteElement("Lagrange", cell, 1) el_p2 = ufl.FiniteElement("Lagrange", cell, 2) vec_el_p1 = ufl.VectorElement("Lagrange", cell, 1) laplace = ("Laplace P1", mesh, raw_forms.laplace_forms(mesh, el_p1)) laplace_p2p1 = ("Laplace P2, P1 coeff", mesh, raw_forms.laplace_coeff_forms(mesh, el_p2, el_p1)) laplace_p2p1_action = ("Laplace P2, P1 coeff, action", mesh, raw_forms.laplace_coeff_action_forms( mesh, el_p2, el_p1)) hyperelasticity = ("Hyperelasticity", mesh, raw_forms.hyperelasticity_forms(mesh, vec_el_p1)) hyperelasticity_action = ("Hyperelasticity, action", mesh, raw_forms.hyperelasticity_action_forms( mesh, vec_el_p1)) return [ # laplace, laplace_p2p1, hyperelasticity, laplace_p2p1_action, hyperelasticity_action ]
def test_3d(self): prm = c.Parameters(c.Constraint.FULL) mesh = df.UnitCubeMesh(5, 5, 5) u_bc = 42.0 problem = c.MechanicsProblem(mesh, prm, law(prm)) bcs = [] bcs.append(df.DirichletBC(problem.Vd.sub(0), 0, boundary.plane_at(0))) bcs.append( df.DirichletBC(problem.Vd.sub(0), u_bc, boundary.plane_at(1))) bcs.append( df.DirichletBC(problem.Vd.sub(1), 0, boundary.plane_at(0, "y"))) bcs.append( df.DirichletBC(problem.Vd.sub(2), 0, boundary.plane_at(0, "z"))) problem.set_bcs(bcs) u = problem.solve() xs = np.linspace(0, 1, 5) for x in xs: for y in xs: for z in xs: u_fem = u((x, y, z)) # print(u_fem) u_correct = (x * u_bc, -y * u_bc * prm.nu, -z * u_bc * prm.nu) self.assertAlmostEqual(u_fem[0], u_correct[0]) self.assertAlmostEqual(u_fem[1], u_correct[1]) self.assertAlmostEqual(u_fem[2], u_correct[2])
def test_to_DG0(self): subdomains = (df.CompiledSubDomain('near(x[0], 0.5)'), df.DomainBoundary()) for subd in subdomains: mesh = df.UnitCubeMesh(4, 4, 4) facet_f = df.MeshFunction('size_t', mesh, 2, 0) subd.mark(facet_f, 1) submesh = EmbeddedMesh(facet_f, 1) transfer = SubMeshTransfer(mesh, submesh) V = df.FunctionSpace(mesh, 'Discontinuous Lagrange Trace', 0) Vsub = df.FunctionSpace(submesh, 'DG', 0) to_Vsub = transfer.compute_map(Vsub, V, strict=False) # Set degree 0 to get the quad order right f = df.Expression('x[0] + 2*x[1] - x[2]', degree=0) fV = df.interpolate(f, V) fsub = df.Function(Vsub) to_Vsub(fsub, fV) error = df.inner(fsub - f, fsub - f)*df.dx(domain=submesh) error = df.sqrt(abs(df.assemble(error))) self.assertTrue(error < 1E-13)
def test_compute_scalar_potential_gcr(self): m1 = df.Constant([1, 0, 0]) m2 = df.Expression(["x[0]*x[1]+3", "x[2]+5", "x[1]+7"], degree=1) tol = 1e-1 expressions = [m1, m2] self.run_demag_computation_test(MagSphereBase(0.1, 1.).mesh, m1, compute_scalar_potential_native_gcr, "native, GCR", ref=compute_scalar_potential_native_fk, tol=tol) for exp in expressions: for k in xrange(3, 10 + 1, 2): self.run_demag_computation_test( df.UnitCubeMesh(k, k, k), exp, compute_scalar_potential_native_gcr, "native, GCR, cube", tol=tol, ref=compute_scalar_potential_native_fk) self.run_demag_computation_test( MagSphereBase(1. / k, 1.).mesh, exp, compute_scalar_potential_native_gcr, "native, GCR, sphere", tol=tol, ref=compute_scalar_potential_native_fk, k=k)
def disk_test(n, subd=I_curve): '''Averaging over indep coords of f''' shape = Disk(radius=lambda x0: 0.1 + 0.0 * x0[2] / 2, degree=10) foo = df.Expression('x[2]*((x[0]-0.5)*(x[0]-0.5) + (x[1]-0.5)*(x[1]-0.5))', degree=3) mesh = df.UnitCubeMesh(n, n, n) V = df.FunctionSpace(mesh, 'CG', 3) v = df.interpolate(foo, V) f = df.MeshFunction('size_t', mesh, 1, 0) subd.mark(f, 1) true = df.Expression('x[2]*(0.1+0.0*x[2]/2)*(0.1+0.0*x[2]/2)/2', degree=4) line_mesh = EmbeddedMesh(f, 1) Q = average_space(V, line_mesh) q = df.Function(Q) Pi = avg_mat(V, Q, line_mesh, {'shape': shape}) Pi.mult(v.vector(), q.vector()) q0 = true # Error L = df.inner(q0 - q, q0 - q) * df.dx e = q.vector().copy() e.axpy(-1, df.interpolate(q0, Q).vector()) return df.sqrt(abs(df.assemble(L)))
def test_p1_trace(has_dolfin): """Test the trace of a P1 Dolfin function.""" if has_dolfin: import dolfin else: try: import dolfin except ImportError: pytest.skip("DOLFIN must be installed to run this test") import bempp.api from bempp.api.external.fenics import fenics_to_bempp_trace_data fenics_mesh = dolfin.UnitCubeMesh(2, 2, 2) fenics_space = dolfin.FunctionSpace(fenics_mesh, "CG", 1) bempp_space, trace_matrix = fenics_to_bempp_trace_data(fenics_space) fenics_coeffs = np.random.rand(fenics_space.dim()) bempp_coeffs = trace_matrix @ fenics_coeffs fenics_fun = dolfin.Function(fenics_space) fenics_fun.vector()[:] = fenics_coeffs bempp_fun = bempp.api.GridFunction(bempp_space, coefficients=bempp_coeffs) for cell in bempp_space.grid.entity_iterator(0): mid = cell.geometry.centroid bempp_val = bempp_fun.evaluate(cell.index, np.array([[1 / 3], [1 / 3]])) fenics_val = np.zeros(1) fenics_fun.eval(fenics_val, mid) assert np.allclose(bempp_val.T[0], fenics_val)
def test_taylor_values(dim, degree): """ Check that the Lagrange -> Taylor projection gives the correct Taylor values """ if dim == 2: mesh = dolfin.UnitSquareMesh(4, 4) else: mesh = dolfin.UnitCubeMesh(2, 2, 2) # Setup Lagrange function with given derivatives and constants V = dolfin.FunctionSpace(mesh, 'DG', degree) u = dolfin.Function(V) if dim == 2: coeffs = [1, 2, -3.0] if degree == 1 else [1, 2, -3.0, -2.5, 4.2, -1.0] else: coeffs = ([1, 2, -3.0, 2.5] if degree == 1 else [1, 2, -3.0, 2.5, -1.3, 4.2, -1.0, -4.2, 2.66, 3.14]) make_taylor_func(u, coeffs) # Convert to Taylor t = dolfin.Function(V) lagrange_to_taylor(u, t) # Check that the target values are obtained dm = V.dofmap() vals = t.vector().get_local() for cell in dolfin.cells(mesh): cell_dofs = dm.cell_dofs(cell.index()) cell_vals = vals[cell_dofs] assert all(abs(cell_vals - coeffs) < 1e-13)
def test_nc1_trace(): """Test the trace of a (N1curl, 1) Dolfin function.""" import dolfin import bempp.api from bempp.api.external.fenics import fenics_to_bempp_trace_data fenics_mesh = dolfin.UnitCubeMesh(2, 2, 2) fenics_space = dolfin.FunctionSpace(fenics_mesh, "N1curl", 1) bempp_space, trace_matrix = fenics_to_bempp_trace_data(fenics_space) fenics_coeffs = np.random.rand(fenics_space.dim()) bempp_coeffs = trace_matrix @ fenics_coeffs fenics_fun = dolfin.Function(fenics_space) fenics_fun.vector()[:] = fenics_coeffs bempp_fun = bempp.api.GridFunction(bempp_space, coefficients=bempp_coeffs) for cell in bempp_space.grid.entity_iterator(0): mid = cell.geometry.centroid normal = cell.geometry.normal bempp_val = bempp_fun.evaluate(cell.index, np.array([[1 / 3], [1 / 3]])) fenics_val = np.zeros(3) fenics_fun.eval(fenics_val, mid) crossed = np.cross(fenics_val, normal) assert np.allclose(bempp_val.T[0], crossed)
def test_bdm_identity_transform(gdim): N = 5 k = 2 # Create mesh and define a divergence free field if gdim == 2: mesh = dolfin.UnitSquareMesh(N, N) field = ['-sin(pi*x[1])*cos(pi*x[0])', 'sin(pi*x[0])*cos(pi*x[1])'] elif gdim == 3: mesh = dolfin.UnitCubeMesh(N, N, N) field = [ '-sin(pi*x[0])*cos(pi*x[1])*sin(pi*x[2])', 'sin(pi*x[0])*cos(pi*x[1])*sin(pi*x[2])', '-cos(pi*x[2])*cos(pi*(x[0]-x[1]))', ] V = dolfin.FunctionSpace(mesh, 'DG', k) u = dolfin.as_vector([dolfin.Function(V) for _ in range(gdim)]) a = dolfin.as_vector([dolfin.Function(V) for _ in range(gdim)]) # Make a divergence free field for i, cpp in enumerate(field): ei = dolfin.Expression(cpp, degree=k) u[i].interpolate(ei) a[i].assign(u[i]) # Run the projection into BDM and then assign this to u bdm = VelocityBDMProjection(simulation=Simulation(), w=u, use_bcs=False) bdm.run() # Check the changes made for ui, ai in zip(u, a): error = dolfin.errornorm(ai, ui, degree_rise=0) assert error < 1e-15
def unitcube_geometry(): N = 3 mesh = dolfin.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) fixed_marker_ = Marker(name='fixed', value=fixed_marker, dimension=2) free_marker_ = Marker(name='free', value=free_marker, dimension=2) markers = (fixed_marker_, free_marker_) # Fibers V_f = QuadratureSpace(mesh, 4) f0 = dolfin.interpolate(dolfin.Expression(("1.0", "0.0", "0.0"), degree=1), V_f) s0 = dolfin.interpolate(dolfin.Expression(("0.0", "1.0", "0.0"), degree=1), V_f) n0 = dolfin.interpolate(dolfin.Expression(("0.0", "0.0", "1.0"), degree=1), V_f) microstructure = Microstructure(f0=f0, s0=s0, n0=n0) geometry = Geometry(mesh=mesh, markers=markers, marker_functions=marker_functions, microstructure=microstructure) return geometry
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 square_test(n, subd=I_curve): '''Averaging over indep coords of f''' size = 0.1 shape = Square(P=lambda x0: x0 - np.array( [size + size * x0[2], size + size * x0[2], 0]), degree=10) foo = df.Expression('x[2]*((x[0]-0.5)*(x[0]-0.5) + (x[1]-0.5)*(x[1]-0.5))', degree=3) mesh = df.UnitCubeMesh(n, n, n) V = df.FunctionSpace(mesh, 'CG', 3) v = df.interpolate(foo, V) f = df.MeshFunction('size_t', mesh, 1, 0) subd.mark(f, 1) true = df.Expression('x[2]*2./3*(size+size*x[2])*(size+size*x[2])', degree=4, size=size) line_mesh = EmbeddedMesh(f, 1) Q = average_space(V, line_mesh) q = df.Function(Q) Pi = avg_mat(V, Q, line_mesh, {'shape': shape}) Pi.mult(v.vector(), q.vector()) q0 = true # Error L = df.inner(q0 - q, q0 - q) * df.dx e = q.vector().copy() e.axpy(-1, df.interpolate(q0, Q).vector()) return df.sqrt(abs(df.assemble(L)))
def test_vector_field(): sim = Simulation() sim.input.read_yaml(yaml_string=INP) mesh = dolfin.UnitCubeMesh(2, 2, 2) sim.set_mesh(mesh) field_inp = sim.input.get_value('fields/0', required_type='Input') field = VectorField(sim, field_inp) def verify(f, t, A): print(t, A) check_vector_value_histogram(f[0].vector(), {t + A: 125}) check_vector_value_histogram(f[1].vector(), {t * A: 125}) check_vector_value_histogram(f[2].vector(), {t * A + A: 125}) # t = 0 t, A = 0, 1 f = field.get_variable('u') verify(f, t, A) # t = 1 t, A = 1, 1 sim.time = t sim.input.set_value('user_code/constants/A', A) field.update(1, t, 1.0) verify(f, t, A) # t = 2 t, A = 2, 10 sim.time = t sim.input.set_value('user_code/constants/A', A) field.update(2, t, 1.0) verify(f, t, A)
def test_sharp_field_dg0(): sim = Simulation() sim.input.read_yaml(yaml_string=INP) mesh = dolfin.UnitCubeMesh(2, 2, 2) sim.set_mesh(mesh) # Sharp jump at the cell boundaries field_inp = sim.input.get_value('fields/0', required_type='Input') f = SharpField(sim, field_inp).get_variable('rho') check_vector_value_histogram(f.vector(), {1: 24, 1000: 24}, round_digits=6) # Sharp jump in the middle of the cells field_inp['z'] = 0.25 f = SharpField(sim, field_inp).get_variable('rho') hist = get_vector_value_histogram(f.vector()) assert len(hist) == 4 for k, v in hist.items(): if round(k, 6) != 1: assert v == 8 else: assert v == 24 # Non-projected sharp jump between cells field_inp['local_projection'] = False field_inp['z'] = 0.50 f = SharpField(sim, field_inp).get_variable('rho') check_vector_value_histogram(f.vector(), {1: 24, 1000: 24}, round_digits=6) # Non-projected sharp jump the middle of the cells field_inp['z'] = 0.25 f = SharpField(sim, field_inp).get_variable('rho') hist = get_vector_value_histogram(f.vector()) check_vector_value_histogram(f.vector(), {1: 40, 1000: 8}, round_digits=6)
def main(n, chi, measure, restrict): mesh = df.UnitCubeMesh(2, n, n) facet_f = df.MeshFunction('size_t', mesh, 2, 0) chi.mark(facet_f, 1) submesh = EmbeddedMesh(facet_f, 1) transfer = SubMeshTransfer(mesh, submesh) V = df.FunctionSpace(mesh, 'Discontinuous Lagrange Trace', 0) Vsub = df.FunctionSpace(submesh, 'DG', 0) to_V = transfer.compute_map(V, Vsub, strict=False) # Set degree 0 to get the quad order right f = df.Expression('x[0] + 2*x[1] - x[2]', degree=0) fsub = df.interpolate(f, Vsub) fV = df.Function(V) to_V(fV, fsub) y = V.tabulate_dof_coordinates().reshape((V.dim(), -1)) x = Vsub.tabulate_dof_coordinates().reshape((Vsub.dim(), -1)) # Correspondence of coordinates self.assertTrue(np.linalg.norm(y[transfer.cache] - x) < 1E-13) # These are all the coordinates idx = list(set(range(V.dim())) - set(transfer.cache)) self.assertTrue(not any(chi.inside(xi, True) for xi in y[idx])) dS_ = df.Measure(measure, domain=mesh, subdomain_data=facet_f) # Stange that this is not exact error = df.inner(restrict(fV - f), restrict(fV - f))*dS_(1) error = df.sqrt(abs(df.assemble(error, form_compiler_parameters={'quadrature_degree': 0}))) return error
def test3D(self): nx = 10 ny = 15 nz = 20 mesh = dl.UnitCubeMesh(nx, ny, nz) true_sub = dl.CompiledSubDomain("x[0] <= .5") true_marker = dl.MeshFunction('size_t', mesh, 3, value=0) true_sub.mark(true_marker, 1) np_sub_x = np.ones(nx, dtype=np.uint) np_sub_x[nx // 2:] = 0 np_sub_y = np.ones(ny, dtype=np.uint) np_sub_z = np.ones(nz, dtype=np.uint) np_sub_xx, np_sub_yy, np_sub_zz = np.meshgrid(np_sub_x, np_sub_y, np_sub_z, indexing='ij') np_sub = np_sub_xx * np_sub_yy * np_sub_zz h = np.array([1. / nx, 1. / ny, 1. / nz]) marker = dl.MeshFunction('size_t', mesh, 3) numpy2MeshFunction(mesh, h, np_sub, marker) assert_allclose(marker.array(), true_marker.array(), rtol=1e-7, atol=1e-9)
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_plot_dolfin_function(tmpdir): os.chdir(str(tmpdir)) interval_mesh = df.UnitIntervalMesh(2) square_mesh = df.UnitSquareMesh(2, 2) cube_mesh = df.UnitCubeMesh(2, 2, 2) S = df.FunctionSpace(cube_mesh, 'CG', 1) V2 = df.VectorFunctionSpace(square_mesh, 'CG', 1, dim=3) V3 = df.VectorFunctionSpace(cube_mesh, 'CG', 1, dim=3) s = df.Function(S) v2 = df.Function(V2) v3 = df.Function(V3) v3.vector()[:] = 1.0 # Wrong function space dimension with pytest.raises(TypeError): plot_dolfin_function(s, outfile='buggy.png') # Plotting a 3D function on a 3D mesh should work plot_dolfin_function(v3, outfile='plot.png') assert (os.path.exists('plot.png')) # Try 2-dimensional mesh as well plot_dolfin_function(v2, outfile='plot_2d_mesh.png') assert (os.path.exists('plot_2d_mesh.png'))
def test_dolfin_p1_identity_equals_bempp_p1_identity(self): """Dolfin P1 boundary identity is equal to BEM++ P1 identity.""" #pylint: disable=import-error import dolfin from bempp.api.fenics_interface import fenics_to_bempp_trace_data from bempp.api.fenics_interface import FenicsOperator mesh = dolfin.UnitCubeMesh(5, 5, 5) V = dolfin.FunctionSpace(mesh, "CG", 1) space, trace_matrix = fenics_to_bempp_trace_data(V) u = dolfin.TestFunction(V) v = dolfin.TrialFunction(V) a = dolfin.inner(u, v) * dolfin.ds fenics_mass = FenicsOperator(a).weak_form().sparse_operator #pylint: disable=no-member actual = trace_matrix * fenics_mass * trace_matrix.transpose() from bempp.api.operators.boundary import sparse expected = sparse.identity(space, space, space).weak_form().sparse_operator diff = actual - expected self.assertAlmostEqual(np.max(np.abs(diff.data)), 0)
def test_scalar_valued_dg_function(): mesh = df.UnitCubeMesh(2, 2, 2) def init_f(coord): x, y, z = coord if z <= 0.5: return 1 else: return 10 f = scalar_valued_dg_function(init_f, mesh) assert f(0, 0, 0.51) == 10.0 assert f(0.5, 0.7, 0.51) == 10.0 assert f(0.4, 0.3, 0.96) == 10.0 assert f(0, 0, 0.49) == 1.0 fa = f.vector().array().reshape(2, -1) assert np.min(fa[0]) == np.max(fa[0]) == 1 assert np.min(fa[1]) == np.max(fa[1]) == 10 dg = df.FunctionSpace(mesh, "DG", 0) dgf = df.Function(dg) dgf.vector()[0] = 9.9 f = scalar_valued_dg_function(dgf, mesh) assert f.vector().array()[0] == 9.9
def test_cell_midpoints(D): from ocellaris.solver_parts.slope_limiter.limiter_cpp_utils import SlopeLimiterInput if D == 2: mesh = dolfin.UnitSquareMesh(4, 4) else: mesh = dolfin.UnitCubeMesh(2, 2, 2) Vx = dolfin.FunctionSpace(mesh, 'DG', 2) V0 = dolfin.FunctionSpace(mesh, 'DG', 0) py_inp = SlopeLimiterInput(mesh, Vx, V0) cpp_inp = py_inp.cpp_obj all_ok = True for cell in dolfin.cells(mesh): cid = cell.index() mp = cell.midpoint() cpp_mp = cpp_inp.cell_midpoints[cid] for d in range(D): ok = dolfin.near(mp[d], cpp_mp[d]) if not ok: print( '%3d %d - %10.3e %10.3e' % (cid, d, mp[d], cpp_mp[d]), '<--- ERROR' if not ok else '', ) all_ok = False assert all_ok
def identity_test(n, shape, subd=I_curve): '''Averaging over indep coords of f''' true = df.Expression('x[2]*x[2]', degree=2) mesh = df.UnitCubeMesh(n, n, n) V = df.FunctionSpace(mesh, 'CG', 2) v = df.interpolate(true, V) f = df.MeshFunction('size_t', mesh, 1, 0) subd.mark(f, 1) line_mesh = EmbeddedMesh(f, 1) Q = average_space(V, line_mesh) q = df.Function(Q) Pi = avg_mat(V, Q, line_mesh, {'shape': shape}) Pi.mult(v.vector(), q.vector()) q0 = true # Error L = df.inner(q0 - q, q0 - q) * df.dx e = q.vector().copy() e.axpy(-1, df.interpolate(q0, Q).vector()) return df.sqrt(abs(df.assemble(L)))
def test_scalar_field(): sim = Simulation() sim.input.read_yaml(yaml_string=INP) mesh = dolfin.UnitCubeMesh(2, 2, 2) sim.set_mesh(mesh) field_inp = sim.input.get_value('fields/1', required_type='Input') field = ScalarField(sim, field_inp) # t = 0 t, A = 0, 1 f = field.get_variable('rho') check_vector_value_histogram(f.vector(), {t * A + A: 125}) # t = 1 t, A = 1, 1 sim.time = t field.update(1, t, 1.0) check_vector_value_histogram(f.vector(), {t * A + A: 125}) # t = 2 t, A = 2, 10 sim.time = t sim.input.set_value('user_code/constants/A', A) field.update(2, t, 1.0) check_vector_value_histogram(f.vector(), {t * A + A: 125})
def setup(self) -> None: self.mesh = df.UnitCubeMesh(5, 5, 5) # Create time self.time = df.Constant(0.0) # Create stimulus self.stimulus = df.Expression("2.0*t", t=self.time, degree=1) # Create ac self.applied_current = df.Expression("sin(2*pi*x[0])*t", t=self.time, degree=3) # Create conductivity "tensors" self.M_i = 1.0 self.M_e = 2.0 self.cell_model = FitzHughNagumoManual() self.cardiac_model = Model(self.mesh, self.time, self.M_i, self.M_e, self.cell_model, self.stimulus, self.applied_current) dt = 0.05 self.t0 = 0.0 self.dt = dt self.T = self.t0 + 5 * dt self.ics = self.cell_model.initial_conditions()
def test3D(self): nx = 10 ny = 15 nz = 20 mesh = dl.UnitCubeMesh(nx, ny, nz) Vh = dl.FunctionSpace(mesh, "CG", 2) nx_np = 2 * nx ny_np = 2 * ny nz_np = 2 * nz hx = 1. / float(nx_np) hy = 1. / float(ny_np) hz = 1. / float(nz_np) x_np = np.linspace(0., 1., nx_np + 1) y_np = np.linspace(0., 1., ny_np + 1) z_np = np.linspace(0., 1., nz_np + 1) xx, yy, zz = np.meshgrid(x_np, y_np, z_np, indexing='ij') f_np = xx + 2. * yy - 3. * zz f_exp = NumpyScalarExpression3D() f_exp.setData(f_np, hx, hy, hz) f_exp2 = dl.Expression("x[0] + 2.*x[1] - 3.*x[2]", degree=2) fh_1 = dl.interpolate(f_exp, Vh).vector() fh_2 = dl.interpolate(f_exp2, Vh).vector() fh_1.axpy(-1., fh_2) error = fh_1.norm("l2") assert_allclose([error], [0.], rtol=1e-7, atol=1e-9)
def setup(self): # Create a 3d mesh. self.mesh3d = df.UnitCubeMesh(11, 10, 10) # Create a DG scalar function space. self.functionspace = df.FunctionSpace(self.mesh3d, "DG", 1)
def test_surface_normal(self): mesh = df.UnitCubeMesh(5, 5, 5) bdries = df.MeshFunction('size_t', mesh, 2, 0) df.CompiledSubDomain('near(x[0], 0)').mark(bdries, 1) n = surface_normal(1, bdries, [0.5, 0.5, 0.5]) n = np.array([-1, 0, 0]) self.assertTrue(np.linalg.norm(n - np.array([-1, 0, 0])) < 1E-13)
def test_facet_normal_direction(self): mesh = df.UnitCubeMesh(1, 1, 1) field = df.Expression(["x[0]", "x[1]", "x[2]"], degree=1) n = df.FacetNormal(mesh) # Divergence of R is 3, the volume of the unit cube is 1 so we divide # by 3 print "Normal: +1=outward, -1=inward:", df.assemble( df.dot(field, n) * df.ds) / 3.
def discretize(dim, n, order): # ### problem definition import dolfin as df if dim == 2: mesh = df.UnitSquareMesh(n, n) elif dim == 3: mesh = df.UnitCubeMesh(n, n, n) else: raise NotImplementedError V = df.FunctionSpace(mesh, "CG", order) g = df.Constant(1.0) c = df.Constant(1.) class DirichletBoundary(df.SubDomain): def inside(self, x, on_boundary): return abs(x[0] - 1.0) < df.DOLFIN_EPS and on_boundary db = DirichletBoundary() bc = df.DirichletBC(V, g, db) u = df.Function(V) v = df.TestFunction(V) f = df.Expression("x[0]*sin(x[1])", degree=2) F = df.inner( (1 + c * u**2) * df.grad(u), df.grad(v)) * df.dx - f * v * df.dx df.solve(F == 0, u, bc, solver_parameters={"newton_solver": { "relative_tolerance": 1e-6 }}) # ### pyMOR wrapping from pymor.bindings.fenics import FenicsVectorSpace, FenicsOperator, FenicsVisualizer from pymor.models.basic import StationaryModel from pymor.operators.constructions import VectorOperator space = FenicsVectorSpace(V) op = FenicsOperator( F, space, space, u, (bc, ), parameter_setter=lambda mu: c.assign(mu['c'].item()), parameters={'c': 1}, solver_options={'inverse': { 'type': 'newton', 'rtol': 1e-6 }}) rhs = VectorOperator(op.range.zeros()) fom = StationaryModel(op, rhs, visualizer=FenicsVisualizer(space)) return fom