def get_centred_cube(domain_size, max_edge_len, centred_element_coordinate=None): """ Generate a cube mesh centred arount [0,0,0] optionally translates mesh slightly such that centred_element_coordinate is at the centre of an element. """ domain_subdivisions = N.array( N.ceil(N.sqrt(2) * domain_size / max_edge_len), N.uint) mesh = dolfin.UnitCube(*domain_subdivisions) # Transform mesh to correct dimensions mesh.coordinates()[:] *= domain_size mesh.coordinates()[:] -= domain_size / 2 if centred_element_coordinate is not None: ## Translate mesh slightly so that source coordinate lies at ## centroid of an element centred_element_point = dolfin.Point(*centred_element_coordinate) # source_elnos = mesh.all_intersected_entities(centred_element_point) source_elnos = mesh.intersected_cells(centred_element_point) closest_elno = source_elnos[(N.argmin([ centred_element_point.distance(dolfin.Cell(mesh, i).midpoint()) for i in source_elnos ]))] centre_pt = dolfin.Cell(mesh, closest_elno).midpoint() centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()]) # The mesh intersect operator caches certain data # structures. We need to clear them if the mesh coordinates # are changed after calling any mesh intersection methods. mesh.intersection_operator().clear() mesh.coordinates()[:] -= centre_coord return mesh
def setUp(self): self.mesh = dolfin.UnitCube(1,1,1) self.V = dolfin.FunctionSpace(self.mesh, "Nedelec 1st kind H(curl)", 1) self.DUT = FillamentSource(self.V) self.fillament_current = 2 self.fillament_endpoints = np.array([[0,0,0.7], [0,0,0.2]]) self.source_parameters = dict( I=self.fillament_current, endpoints=self.fillament_endpoints)
def setUp(self): self.mesh = dolfin.UnitCube(3, 3, 3) self.V = dolfin.FunctionSpace(self.mesh, "Nedelec 1st kind H(curl)", 3) self.u_r = dolfin.interpolate(dolfin.Expression(('0', '0', '2*x[2]')), self.V) self.u_i = dolfin.interpolate( dolfin.Expression(('0', '0', '-x[2]*x[2]')), self.V) self.x = self.u_r.vector().array() + 1j * self.u_i.vector().array() self.DUT = ComplexVoltageAlongLine(self.V) self.DUT.set_dofs(self.x)
def setUp(self): self.mesh = dolfin.UnitCube(2, 2, 2) self.function_space = dolfin.FunctionSpace(self.mesh, "Nedelec 1st kind H(curl)", 1) nodofs = self.function_space.dofmap().global_dimension() self.E_dofs = np.random.random(nodofs) + 1j * np.random.random(nodofs) self.g_dofs = np.random.random(nodofs) + 1j * np.random.random(nodofs) self.k0 = np.random.rand() * 10 self.DUT = CalcEMFunctional(self.function_space)
# Authors: # Evan Lezar <*****@*****.**> import sys import numpy as N import os import dolfin as dol sys.path.insert(0, '../../') from sucemfem.ProblemConfigurations.EMVectorWaveEigenproblem import EigenProblem, DefaultEigenSolver from sucemfem.BoundaryConditions import PECWallsBoundaryCondition from sucemfem.Consts import c0 del sys.path[0] script_path = os.path.dirname(__file__) # Load the mesh and the material region markers mesh = dol.UnitCube(4, 4, 4) a = 1.0 b = 1.0 d = 1.0 mesh.coordinates()[:, 0] = a * mesh.coordinates()[:, 0] mesh.coordinates()[:, 1] = b * mesh.coordinates()[:, 1] mesh.coordinates()[:, 2] = d * mesh.coordinates()[:, 2] # init the PEC walls boundary condition pec_walls = PECWallsBoundaryCondition() pec_walls.init_with_mesh(mesh) # Use 3rd order basis functions order = 3 # Set up the eigen problem ep = EigenProblem()
exit() if not dol.has_slepc(): print "DOLFIN has not been configured with SLEPc. Exiting." exit() class CavityDims(object): pass cdims = CavityDims() cdims.a, cdims.b, cdims.c = 29, 23, 19 # Define mesh, function space mesh = dol.UnitCube(1, 1, 1) mesh.coordinates()[:] *= [cdims.a, cdims.b, cdims.c] V = dol.FunctionSpace(mesh, "Nedelec 1st kind H(curl)", 4) # Define basis and bilinear form u = dol.TrialFunction(V) v = dol.TestFunction(V) m = inner(v, u) * dx # Mass form s = dot(curl(v), curl(u)) * dx # Stiffness form # Assemble smass form M = dol.PETScMatrix() S = dol.PETScMatrix() dol.assemble(m, tensor=M, mesh=mesh) dol.assemble(s, tensor=S, mesh=mesh)
# Authors: # Neilen Marais <*****@*****.**> from __future__ import division import numpy as np import dolfin def as_dolfin_vector(a): """Convert array to a dolfin Vector() instance""" assert len(a.shape) == 1 # 1D vectors please v = dolfin.Vector(len(a)) v.set_local(np.require(a, requirements=['C',])) return v mesh = dolfin.UnitCube(1,1,1) V = dolfin.FunctionSpace(mesh, "Nedelec 1st kind H(curl)", 2) no = V.dofmap().global_dimension() x = np.ones(no) u = dolfin.Function(V, as_dolfin_vector(x)) vec = as_dolfin_vector(x) uu = dolfin.Function(V, vec)
def main(): # Define mesh domain_subdivisions = N.array( N.ceil(N.sqrt(2) * domain_size / max_edge_len), N.uint) print 'Numer of domain subdomain_subdivisions: ', domain_subdivisions mesh = dolfin.UnitCube(*domain_subdivisions) # Transform mesh to correct dimensions mesh.coordinates()[:] *= domain_size # Centred around [0,0,0] mesh.coordinates()[:] -= domain_size / 2 ## Translate mesh slightly so that source coordinate lies at ## centroid of an element io = mesh.intersection_operator() source_elnos = io.all_intersected_entities(source_point) closest_elno = source_elnos[(N.argmin([ source_point.distance(dolfin.Cell(mesh, i).midpoint()) for i in source_elnos ]))] centre_pt = dolfin.Cell(mesh, closest_elno).midpoint() centre_coord = N.array([centre_pt.x(), centre_pt.y(), centre_pt.z()]) # There seems to be an issue with the intersect operator if the # mesh coordinates are changed after calling it for the first # time. Since we called it to find the centroid, we should init a # new mesh mesh_coords = mesh.coordinates().copy() mesh = dolfin.UnitCube(*domain_subdivisions) mesh.coordinates()[:] = mesh_coords mesh.coordinates()[:] -= centre_coord ## # Define function space V = dolfin.FunctionSpace(mesh, "Nedelec 1st kind H(curl)", order) k_0 = 2 * N.pi * freq / c0 # Freespace wave number # Definite test- and trial functions u = dolfin.TrialFunction(V) v = dolfin.TestFunction(V) # Define the bilinear forms m = eps_r * inner(v, u) * dx # Mass form s = (1 / mu_r) * dot(curl(v), curl(u)) * dx # Stiffness form n = V.cell().n # Get the surface normal s_0 = inner(cross(n, v), cross(n, u)) * ds # ABC boundary condition form # Assemble forms using uBLASS matrices so that we can easily export to scipy print 'Assembling forms' M = dolfin.uBLASSparseMatrix() S = dolfin.uBLASSparseMatrix() S_0 = dolfin.uBLASSparseMatrix() dolfin.assemble(m, tensor=M, mesh=mesh) dolfin.assemble(s, tensor=S, mesh=mesh) dolfin.assemble(s_0, tensor=S_0, mesh=mesh) print 'Number of degrees of freedom: ', M.size(0) # Set up RHS b = N.zeros(M.size(0), dtype=N.complex128) dofnos, rhs_contrib = calc_pointsource_contrib(V, source_coord, source_value) rhs_contrib = 1j * k_0 * Z0 * rhs_contrib b[dofnos] += rhs_contrib Msp = dolfin_ublassparse_to_scipy_csr(M) Ssp = dolfin_ublassparse_to_scipy_csr(S) S_0sp = dolfin_ublassparse_to_scipy_csr(S_0) # A is the system matrix that must be solved A = Ssp - k_0**2 * Msp + 1j * k_0 * S_0sp solved = False if solver == 'iterative': # solve using scipy bicgstab print 'solve using scipy bicgstab' x = solve_sparse_system(A, b) elif solver == 'direct': import scipy.sparse.linalg A_lu = scipy.sparse.linalg.factorized(A.T) x = A_lu(b) else: raise ValueError("solver must have value 'iterative' or 'direct'") dolfin.set_log_active(False) # evaluation seems to make a lot of noise u_re = dolfin.Function(V) u_im = dolfin.Function(V) # N.require is important, since dolfin seems to expect a contiguous array u_re.vector()[:] = N.require(N.real(x), requirements='C') u_im.vector()[:] = N.require(N.imag(x), requirements='C') E_field = N.zeros((len(field_pts), 3), dtype=N.complex128) for i, fp in enumerate(field_pts): try: E_field[i, :] = u_re(fp) + 1j * u_im(fp) except (RuntimeError, StandardError): E_field[i, :] = N.nan + 1j * N.nan import pylab as P r1 = field_pts[:] / lam x1 = r1[:, 0] E_ana = N.abs(analytical_result) E_num = E_field P.figure() P.plot(x1, N.abs(E_num[:, 0]), '-g', label='x_num') P.plot(x1, N.abs(E_num[:, 1]), '-b', label='y_num') P.plot(x1, N.abs(E_num[:, 2]), '-r', label='z_num') P.plot(analytical_pts, E_ana, '--r', label='z_ana') P.ylabel('E-field Magnitude') P.xlabel('Distance (wavelengths)') P.legend(loc='best') P.grid(True) P.show()
def setUp(self): self.mesh = dolfin.UnitCube(3, 3, 3) self.V = dolfin.FunctionSpace(self.mesh, "Nedelec 1st kind H(curl)", 2) self.u = dolfin.interpolate(dolfin.Expression(('0', '0', '2*x[2]')), self.V) self.DUT = VoltageAlongLine(self.u)
def setUp(self): self.mesh = dolfin.UnitCube(1, 1, 1) self.no_boundary_edges = 18 # for 1x1x1 UnitCube meshed with 2 # tris on each face self.DUT = Geometry.BoundaryEdges(self.mesh)