def mesh2d(inner, outer, *meshres, stefan=True): origin = dolfin.Point(0., 0.) if stefan: geometry = mshr.Circle(origin, outer, 2 * meshres[0]) - mshr.Circle( origin, inner, int(0.5 * meshres[0])) mesh = mshr.generate_mesh(geometry, meshres[0]) mesh.init() # Construct of the facet markers: boundary = (dolfin.MeshFunction("size_t", mesh, mesh.topology().dim() - 1, 0), {}) for f in dolfin.facets(mesh): if f.midpoint().distance(origin) <= inner and f.exterior(): boundary[0][f] = 1 # inner radius boundary[1]['inner'] = 1 elif f.midpoint().distance(origin) >= (inner + outer) / 2 and f.exterior(): boundary[0][f] = 2 # outer radius boundary[1]['outer'] = 2 # Definition of measures and normal vector: n = dolfin.FacetNormal(mesh) dx = dolfin.Measure("dx", mesh) ds = dolfin.Measure("ds", domain=mesh, subdomain_data=boundary[0]) else: width = inner height = outer mesh = dolfin.RectangleMesh(origin, Point(width, height), meshres[0], meshres[1]) mesh.init() boundary = (dolfin.MeshFunction("size_t", mesh, mesh.topology().dim() - 1, 0), {}) for f in dolfin.facets(mesh): if dolfin.near(f.midpoint()[1], 0.): boundary[0][f] = 1 # bottom boundary[1]['bottom'] = 1 elif dolfin.near(f.midpoint()[1], height): boundary[0][f] = 2 # top boundary[1]['top'] = 2 elif dolfin.near(f.midpoint()[0], 0.): boundary[0][f] = 3 # left boundary[1]['left'] = 3 elif dolfin.near(f.midpoint()[0], width): boundary[0][f] = 4 # right boundary[1]['right'] = 4 # Definition of measures and normal vector: n = dolfin.FacetNormal(mesh) dx = dolfin.Measure("dx", mesh) ds = dolfin.Measure("ds", subdomain_data=boundary[0]) return (mesh, boundary, n, dx, ds)
def compute_velocity(mesh, Vh, a, u): #export the velocity field v = - exp( a ) \grad u: then we solve ( exp(-a) v, w) = ( u, div w) Vv = dl.FunctionSpace(mesh, 'RT', 1) v = dl.Function(Vv, name="velocity") vtrial = dl.TrialFunction(Vv) vtest = dl.TestFunction(Vv) afun = dl.Function(Vh[PARAMETER], a) ufun = dl.Function(Vh[STATE], u) Mv = dl.exp(-afun) * dl.inner(vtrial, vtest) * dl.dx n = dl.FacetNormal(mesh) class TopBoundary(dl.SubDomain): def inside(self, x, on_boundary): return on_boundary and x[1] > 1 - dl.DOLFIN_EPS Gamma_M = TopBoundary() boundaries = dl.FacetFunction("size_t", mesh) boundaries.set_all(0) Gamma_M.mark(boundaries, 1) dss = dl.Measure("ds")[boundaries] rhs = ufun * dl.div(vtest) * dl.dx - dl.dot(vtest, n) * dss(1) bcv = dl.DirichletBC(Vv, dl.Expression(("0.0", "0.0")), v_boundary) dl.solve(Mv == rhs, v, bcv) return v
def __init__(self, u, alpha): self._u = u self._alpha = alpha self._normal = df.FacetNormal(u.function_space().mesh()) self._form = None self._side = '+'
def init_variables(self): mesh = self.mesh DG0 = self.DG0 self.n = n = dolfin.FacetNormal(mesh) self.u = u = dolfin.Function(DG0) self.v = v = dolfin.TestFunction(DG0)
def get_volume(geometry, u=None, chamber="lv"): if "ENDO" in geometry.markers: lv_endo_marker = geometry.markers["ENDO"] rv_endo_marker = None else: lv_endo_marker = geometry.markers["ENDO_LV"] rv_endo_marker = geometry.markers["ENDO_RV"] marker = lv_endo_marker if chamber == "lv" else rv_endo_marker if marker is None: return None if hasattr(marker, "__len__"): marker = marker[0] ds = df.Measure( "exterior_facet", subdomain_data=geometry.ffun, domain=geometry.mesh )(marker) X = df.SpatialCoordinate(geometry.mesh) N = df.FacetNormal(geometry.mesh) if u is None: vol = df.assemble((-1.0 / 3.0) * df.dot(X, N) * ds) else: F = df.grad(u) + df.Identity(3) J = df.det(F) vol = df.assemble((-1.0 / 3.0) * df.dot(X + u, J * df.inv(F).T * N) * ds) return vol
def mesh3d(width, depth, height, nx, ny, nz): mesh = dolfin.BoxMesh(Point(0., 0., 0.), Point(width, depth, height), nx, ny, nz) boundary = (dolfin.MeshFunction("size_t", mesh, mesh.topology().dim() - 1, 0), {}) for f in dolfin.facets(mesh): if dolfin.near(f.midpoint()[2], 0.): boundary[0][f] = 1 # bottom boundary[1]['bottom'] = 1 elif dolfin.near(f.midpoint()[2], height): boundary[0][f] = 2 # top boundary[1]['top'] = 2 elif dolfin.near(f.midpoint()[0], 0.): boundary[0][f] = 3 # left boundary[1]['left'] = 3 elif dolfin.near(f.midpoint()[0], width): boundary[0][f] = 4 # right boundary[1]['right'] = 4 elif dolfin.near(f.midpoint()[1], 0): boundary[0][f] = 5 # front boundary[1]['front'] = 5 elif dolfin.near(f.midpoint()[1], depth): boundary[0][f] = 6 # back boundary[1]['back'] = 6 # Definition of measures and normal vector: n = dolfin.FacetNormal(mesh) dx = dolfin.Measure("dx", mesh) ds = dolfin.Measure("ds", subdomain_data=boundary[0]) mesh_xdmf = dolfin.XDMFFile(mpi_comm_world(), "data/mesh_3D.xdmf") mesh_xdmf.write(boundaries[0]) return (mesh, boundary, n, dx, ds)
def __init__(self, Vh, nu, ds_ff, u_ff, inletMomentun, inletWidth): """ Contructor INPUTS: - Vh: the mixed finite element space for the state variable - nu: the kinetic viscosity - ds_ff: the integrator on the farfield boundary (where we impose the swithcing Dir/Neu conditions - u_ff: the farfield Dirichlet condition for the normal component of the velocity field u (when backflow is detected) - inletMomentun, inletWidth: the standard parameters in the algebraic closure model """ self.Vh = Vh self.mesh = Vh.mesh() self.nu = nu self.ds_ff = ds_ff self.u_ff = u_ff self.inletMomentun = inletMomentun self.inletWidth = inletWidth self.metric = mesh_metric(self.mesh) self.n = dl.FacetNormal(self.mesh) self.tg = dl.perp(self.n) self.reg_norm = dl.Constant(1e-1) self.Cd = dl.Constant(1e5) #self.xfun = dl.Expression("x[0]", element = self.Vh.sub(1).ufl_element()) self.xfun, self.yfun = dl.SpatialCoordinate(self.mesh)
def delta_dg(mesh, expr): V = df.FunctionSpace(mesh, "DG", 0) m = df.interpolate(expr, V) n = df.FacetNormal(mesh) h = df.CellSize(mesh) h_avg = (h('+') + h('-')) / 2 alpha = 1.0 gamma = 0.0 u = df.TrialFunction(V) v = df.TestFunction(V) # for DG 0 case, only term contain alpha is nonzero a = df.dot(df.grad(v), df.grad(u))*df.dx \ - df.dot(df.avg(df.grad(v)), df.jump(u, n))*df.dS \ - df.dot(df.jump(v, n), df.avg(df.grad(u)))*df.dS \ + alpha/h_avg*df.dot(df.jump(v, n), df.jump(u, n))*df.dS \ - df.dot(df.grad(v), u*n)*df.ds \ - df.dot(v*n, df.grad(u))*df.ds \ + gamma/h*v*u*df.ds K = df.assemble(a).array() L = df.assemble(v * df.dx).array() h = -np.dot(K, m.vector().array()) / (L) xs = [] for cell in df.cells(mesh): xs.append(cell.midpoint().x()) print len(xs), len(h) return xs, h
def __init__(self, model, boundary, marker=6174, direction=None): """ Postprocessing class to track the tractions at `boundary` (actually tractions . direction) and the displacements at the boundary. Each update to the plot can visualized using fenics_helpers.plotting.AdaptivePlot """ mesh = model.mesh self.model = model boundary_markers = df.MeshFunction("size_t", mesh, mesh.topology().dim() - 1) boundary.mark(boundary_markers, marker) ds = df.Measure("ds", domain=mesh, subdomain_data=boundary_markers) n = df.FacetNormal(mesh) if direction is None: direction = n self.boundary_load = df.dot(model.traction(n), direction) * ds(marker) self.boundary_disp = df.dot(model.d, direction) * ds(marker) self.area = df.assemble(1.0 * ds(marker)) self.load = [] self.disp = [] self.plot = None
def main(): fsr = FunctionSubspaceRegistry() deg = 2 mesh = dolfin.UnitSquareMesh(100, 3) muc = mesh.ufl_cell() el_w = dolfin.FiniteElement('DG', muc, deg - 1) el_j = dolfin.FiniteElement('BDM', muc, deg) el_DG0 = dolfin.FiniteElement('DG', muc, 0) el = dolfin.MixedElement([el_w, el_j]) space = dolfin.FunctionSpace(mesh, el) DG0 = dolfin.FunctionSpace(mesh, el_DG0) fsr.register(space) facet_normal = dolfin.FacetNormal(mesh) xyz = dolfin.SpatialCoordinate(mesh) trial = dolfin.Function(space) test = dolfin.TestFunction(space) w, c = dolfin.split(trial) v, phi = dolfin.split(test) sympy_exprs = derive_exprs() exprs = { k: sympy_dolfin_printer.to_ufl(sympy_exprs['R'], mesh, v) for k, v in sympy_exprs['quantities'].items() } f = exprs['f'] w0 = dolfin.project(dolfin.conditional(dolfin.gt(xyz[0], 0.5), 1.0, 0.3), DG0) w_BC = exprs['w'] dx = dolfin.dx() form = (+v * dolfin.div(c) * dx - v * f * dx + dolfin.exp(w + w0) * dolfin.dot(phi, c) * dx + dolfin.div(phi) * w * dx - (w_BC - w0) * dolfin.dot(phi, facet_normal) * dolfin.ds() - (w0('-') - w0('+')) * dolfin.dot(phi('+'), facet_normal('+')) * dolfin.dS()) solver = NewtonSolver(form, trial, [], parameters=dict(relaxation_parameter=1.0, maximum_iterations=15, extra_iterations=10, relative_tolerance=1e-6, absolute_tolerance=1e-7)) solver.solve() with closing(XdmfPlot("out/qflop_test.xdmf", fsr)) as X: CG1 = dolfin.FunctionSpace(mesh, dolfin.FiniteElement('CG', muc, 1)) X.add('w0', 1, w0, CG1) X.add('w_c', 1, w + w0, CG1) X.add('w_e', 1, exprs['w'], CG1) X.add('f', 1, f, CG1) X.add('cx_c', 1, c[0], CG1) X.add('cx_e', 1, exprs['c'][0], CG1)
def get_contact_currents(solution, contact_name): '''Integrate current flux across the area of a contact. Returns the electron and hole currents as Pint quantities.''' sl = solution # components of electron and hole currents normal to mesh facets jvn = sl['/pde/dot'](sl['/CB/j'], dolfin.FacetNormal(sl['/mesh'])) jvp = sl['/pde/dot'](sl['/VB/j'], dolfin.FacetNormal(sl['/mesh'])) int_over_surf = sl['/pde/integrate_over_surface'] hole_current = int_over_surf( jvp, sl['/geometry/facet_regions/' + contact_name + '/ds']) elec_current = int_over_surf( jvn, sl['/geometry/facet_regions/' + contact_name + '/ds']) return elec_current, hole_current
def normal_stresses(self): k = self.bc_dict["obstacle"] n = df.FacetNormal(self.mesh) tau = (self.mu * (df.grad(self.u_) + df.grad(self.u_).T) - self.p_ * df.Identity(2)) normal_stresses_x = -df.assemble(df.dot(tau, n)[0] * self.ds_(k)) normal_stresses_y = df.assemble(df.dot(tau, n)[1] * self.ds_(k)) return np.array([normal_stresses_x, normal_stresses_y])
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 Fbaresurf(v, i): dS = geo.dS("moleculeb") n = dolfin.FacetNormal(geo.mesh) #def tang(x): # return x - dolfin.inner(x,n)*n #def gradT(v): # tangential gradient # return tang(dolfin.grad(v)) #return dolfin.Constant(Moleculeqs)*(-r*gradT(v)[i])('-')*dS return dolfin.Constant(Moleculeqs) * (-r2pi * grad(v)[i])('-') * dS
def __init__(self, V, bnd, objects, vsources=None, isources=None, dt=None, int_bnd_ids=None, eps0=1): num_objects = len(objects) if int_bnd_ids == None: int_bnd_ids = [ objects[i].domain_args[1] for i in range(num_objects) ] if vsources == None: vsources = [] if isources == None: isources = [] self.dt = 1 else: assert dt != None self.dt = dt self.int_bnd_ids = int_bnd_ids self.vsources = vsources self.isources = isources self.objects = objects self.eps0 = eps0 self.groups = get_charge_sharing_sets(vsources, num_objects) self.V = V mesh = V.mesh() R = df.FunctionSpace(mesh, "Real", 0) self.mu = df.TestFunction(R) self.phi = df.TrialFunction(V) self.dss = df.Measure("ds", domain=mesh, subdomain_data=bnd) self.n = df.FacetNormal(mesh) thisdir = os.path.dirname(__file__) path = os.path.join(thisdir, 'addrow.cpp') code = open(path, 'r').read() self.compiled = df.compile_extension_module(code=code) # Rows in which to store charge and potential constraints rows_charge = [g[0] for g in self.groups] rows_potential = list(set(range(num_objects)) - set(rows_charge)) self.rows_charge = [objects[i].get_free_row() for i in rows_charge] self.rows_potential = [ objects[i].get_free_row() for i in rows_potential ]
def __init__(self, V, bnd, bnd_id): ConstantBC.__init__(self, V, bnd, bnd_id) self.charge = 0. self.collected_current = 0. self.potential = 0. self.id = bnd_id mesh = self.function_space().mesh() self.n = df.FacetNormal(mesh) self.dss = df.Measure("ds", domain=mesh, subdomain_data=bnd)
def compute_current(self, facet): if not hasattr(self, "normal"): self.normal = d.FacetNormal(self.mesh.mesh) if facet not in self.mesh.facetinfo: raise Exception( 'The facet {} is not in this geometry. Choose one of the following facets {}' .format(facet, self.mesh.facetinfo.keys)) index = self.boundaries.facet_dict[facet] current = d.dot(-self.conductivity * d.grad(self.u), self.normal) * self.ds(index) return d.assemble(current)
def _define_incompressibility_constraint(self): """ THIS SHOULD BE SUPPLIED BY THE CONSTITUTIVE EQUATION CLASS. """ q = self.test_scalar n = dlf.FacetNormal(self.mesh) G2 = q*dlf.dot(self.ufl_velocity, n)*dlf.ds \ - dlf.dot(dlf.grad(q), self.ufl_velocity)*dlf.dx return G2
def setUp(self): self.mesh = mesh = dolfin.UnitSquareMesh(20, 2, "left") self.DG0_element = DG0e = dolfin.FiniteElement("DG", mesh.ufl_cell(), 0) self.DG0v_element = DG0ve = dolfin.VectorElement( "DG", mesh.ufl_cell(), 0) self.DG0 = DG0 = dolfin.FunctionSpace(mesh, DG0e) self.DG0v = DG0v = dolfin.FunctionSpace(mesh, DG0ve) self.fsr = fsr = FunctionSubspaceRegistry() fsr.register(DG0) fsr.register(DG0v) self.cellmid = cm = CellMidpointExpression(mesh, element=DG0ve) self.n = n = dolfin.FacetNormal(mesh) self.u = u = dolfin.Function(DG0) self.v = v = dolfin.TestFunction(DG0) u_bc = dolfin.Expression('x[0]', degree=2) x = dolfin.SpatialCoordinate(mesh) self.rho = rho = dolfin.conditional( dolfin.lt((x[0] - 0.5)**2 + (x[1] - 0.5)**2, 0.2**2), 0.0, 0.0) dot = dolfin.dot cellsize = dolfin.CellSize(mesh) self.h = h = cm('+') - cm('-') self.h_boundary = h_boundary = 2 * n * dot(x - cm, n) self.E = E = h / dot(h, h) * (u('-') - u('+')) self.E_boundary = E_boundary = h_boundary / dot( h_boundary, h_boundary) * (u - u_bc) dS = dolfin.dS eps = 1e-8 class BL(dolfin.SubDomain): def inside(self, x, on_boundary): return abs(x[0]) < eps class BR(dolfin.SubDomain): def inside(self, x, on_boundary): return abs(x[0] - 1) < eps ff = dolfin.FacetFunction('size_t', mesh, 0) BL().mark(ff, 1) BR().mark(ff, 1) ds = dolfin.Measure('ds', domain=mesh, subdomain_data=ff) self.F = (dot(E, n('+')) * v('+') * dS + dot(E, n('-')) * v('-') * dS - v * rho * dolfin.dx + dot(E_boundary, n) * v * ds(1))
def steady_state_res(vel, pres, phi=None): if phi is None: phi = dolfin.TestFunction(V) cnvfrm = inner(dolfin.dot(vel, nabla_grad(vel)), phi) * dx diffrm = nu * inner(grad(vel) + grad(vel).T, grad(phi)) * dx if gradvsymmtrc: nvec = dolfin.FacetNormal(V.mesh()) diffrm = diffrm - (nu * inner(grad(vel).T * nvec, phi)) * outflowds pfrm = inner(pres, div(phi)) * dx res = dolfin.assemble(diffrm + cnvfrm - pfrm) return res
def __init__(self, u, boundary_is_streamline=False, degree=1): """ Heavily based on https://github.com/mikaem/fenicstools/blob/master/fenicstools/Streamfunctions.py Stream function for a given general 2D velocity field. The boundary conditions are weakly imposed through the term inner(q, grad(psi)*n)*ds, where grad(psi) = [-v, u] is set on all boundaries. This should work for any collection of boundaries: walls, inlets, outlets etc. """ Vu = u[0].function_space() mesh = Vu.mesh() # Check dimension if not mesh.geometry().dim() == 2: df.error("Stream-function can only be computed in 2D.") # Define the weak form V = df.FunctionSpace(mesh, 'CG', degree) q = df.TestFunction(V) psi = df.TrialFunction(V) n = df.FacetNormal(mesh) a = df.dot(df.grad(q), df.grad(psi)) * df.dx L = df.dot(q, df.curl(u)) * df.dx if boundary_is_streamline: # Strongly set psi = 0 on entire domain boundary self.bcs = [df.DirichletBC(V, df.Constant(0), df.DomainBoundary())] self.normalize = False else: self.bcs = [] self.normalize = True L = L + q * (n[1] * u[0] - n[0] * u[1]) * df.ds # Create preconditioned iterative solver solver = df.PETScKrylovSolver('gmres', 'hypre_amg') solver.parameters['nonzero_initial_guess'] = True solver.parameters['relative_tolerance'] = 1e-10 solver.parameters['absolute_tolerance'] = 1e-10 # Store for later computation self.psi = df.Function(V) self.A = df.assemble(a) self.L = L self.mesh = mesh self.solver = solver self._triangulation = None
def get_current(self): self.currents = {} self.logger.debug( 'Computing the electric currents through certain surfaces.') self.normal = d.FacetNormal(self.mesh.mesh) if not isinstance(self.data['properties']['Current'], list): self.data['properties']['Current'] = [ self.data['properties']['Current'] ] for facet in self.data['properties']['Current']: current = self.compute_current(facet) self.currents[facet] = current self.logger.info('The currents are:') self.logger.info(self.currents)
def __init__(self, Vh, nu, ds_ff, u_ff, k_ff, e_ff, C_mu=dl.Constant(0.09), sigma_k=dl.Constant(1.00), sigma_e=dl.Constant(1.30), C_e1=dl.Constant(1.44), C_e2=dl.Constant(1.92)): """ Contructor INPUTS: - Vh: the mixed finite element space for the state variable - nu: the kinetic viscosity - ds_ff: the integrator on the farfield boundary (where we impose the swithcing Dir/Neu conditions - u_ff: the farfield Dirichlet condition for the normal component of the velocity field u (when backflow is detected) - k_ff: the farfield Dirichlet condition for the normal component of the turbulent kinetic energy field k (when backflow is detected) - e_ff: the farfield Dirichlet condition for the normal component of the turbulent energy dissipation field e (when backflow is detected) - C_mu, sigma_k, sigma_e, C_e1, C_e1: the standard parameters in the KE closure model """ self.Vh = Vh self.mesh = Vh.mesh() self.nu = nu self.ds_ff = ds_ff self.u_ff = u_ff self.k_ff = k_ff self.e_ff = e_ff self.C_mu = C_mu self.sigma_k = sigma_k self.sigma_e = sigma_e self.C_e1 = C_e1 self.C_e2 = C_e2 self.metric = mesh_metric(self.mesh) self.n = dl.FacetNormal(self.mesh) self.tg = dl.perp(self.n) self.reg_k = dl.Constant(1e-8) self.reg_e = dl.Constant(1e-8) self.reg_norm = dl.Constant(1e-1) self.beta_chi_inflow = dl.Constant(1.) / dl.sqrt(self.nu) self.shift_chi_inflow = dl.Constant(0.) self.Cd = dl.Constant(1e5)
def assemble_1d(mesh): DG = df.FunctionSpace(mesh, "DG", 0) n = df.FacetNormal(mesh) h = df.CellSize(mesh) h_avg = (h('+') + h('-')) / 2 u = df.TrialFunction(DG) v = df.TestFunction(DG) a = 1.0 / h_avg * df.dot(df.jump(v, n), df.jump(u, n)) * df.dS K = df.assemble(a) L = df.assemble(v * df.dx).array() return copy_petsc_to_csr(K), L
def meshxml(name): # reads mesh from .xml file, cf. Notes # IN: str of name of the .xml file (do that in serial): mesh = dolfin.Mesh(name + '.xml') mesh.init() hdf = dolfin.HDF5File(mesh.mpi_comm(), name + "_hdf.h5", "w") hdf.write(mesh, "/mesh") xdmf = dolfin.XDMFFile(mesh.mpi_comm(), name + "_xdmf.xdmf") xdmf.write(mesh) xdmf.close() domains = mesh.domains() if os.path.isfile(name + "_physical_region.xml"): domains.init(mesh.topology().dim() - 1) if os.path.isfile(name + "_facet_region.xml"): boundary = (dolfin.MeshFunction("size_t", mesh, name + "_facet_region.xml"), { 'inner': 1, 'outer': 2 }) #mesh.init() hdf.write(boundary[0], "/boundary") ds = dolfin.Measure("ds", subdomain_data=boundary[0]) else: boundary = (dolfin.MeshFunction("size_t", mesh, mesh.topology().dim() - 1, 0), {}) width = mesh.coordinates()[:, 0].max() height = mesh.coordinates()[:, 1].max() for f in dolfin.facets(mesh): if dolfin.near(f.midpoint()[1], 0.): boundary[0][f] = 1 # bottom boundary[1]['bottom'] = 1 elif dolfin.near(f.midpoint()[1], height): boundary[0][f] = 2 # top boundary[1]['top'] = 2 elif dolfin.near(f.midpoint()[0], 0.): boundary[0][f] = 3 # left boundary[1]['left'] = 3 elif dolfin.near(f.midpoint()[0], width): boundary[0][f] = 4 # right boundary[1]['right'] = 4 ds = dolfin.Measure("ds", subdomain_data=boundary[0]) # mesh = Mesh() # hdf.read(mesh,"/mesh", False) hdf.close() # Definition of measures and normal vector: n = dolfin.FacetNormal(mesh) dx = dolfin.Measure("dx", mesh) return (mesh, boundary, n, dx, ds)
def delta_dg(mesh, expr): CG = df.FunctionSpace(mesh, "CG", 1) DG = df.FunctionSpace(mesh, "DG", 0) CG3 = df.VectorFunctionSpace(mesh, "CG", 1) DG3 = df.VectorFunctionSpace(mesh, "DG", 0) m = df.interpolate(expr, DG3) n = df.FacetNormal(mesh) u_dg = df.TrialFunction(DG) v_dg = df.TestFunction(DG) u3 = df.TrialFunction(CG3) v3 = df.TestFunction(CG3) a = u_dg * df.inner(v3, n) * df.ds - u_dg * df.div(v3) * df.dx mm = m.vector().array() mm.shape = (3, -1) K = df.assemble(a).array() L3 = df.assemble(df.dot(v3, df.Constant([1, 1, 1])) * df.dx).array() f = np.dot(K, mm[0]) / L3 fun1 = df.Function(CG3) fun1.vector().set_local(f) df.plot(fun1) a = df.div(u3) * v_dg * df.dx A = df.assemble(a).array() L = df.assemble(v_dg * df.dx).array() h = np.dot(A, f) / L fun = df.Function(DG) fun.vector().set_local(h) df.plot(fun) res = [] for x in xs: res.append(fun(x, 5, 0.5)) """ fun2 =df.interpolate(fun, df.VectorFunctionSpace(mesh, "CG", 1)) file = df.File('field2.pvd') file << fun2 """ return res
def blocks(self): aa, ff = super(FormulationMinimallyConstrained, self).blocks() n = df.FacetNormal(self.mesh) ds = df.Measure('ds', self.mesh) u, P = self.uu_[0], self.uu_[2] v, Q = self.vv_[0], self.vv_[2] aa[0].append(- df.inner(P, df.outer(v, n))*ds) aa[1].append(0) aa.append([- df.inner(Q, df.outer(u, n))*ds, 0, 0]) ff.append(0) return [aa, ff]
def get_cavity_volume_form(mesh, u=None, xshift=0.0): from . import kinematics shift = Constant((xshift, 0.0, 0.0)) X = dolfin.SpatialCoordinate(mesh) - shift N = dolfin.FacetNormal(mesh) if u is None: vol_form = (-1.0 / 3.0) * dolfin.dot(X, N) else: F = kinematics.DeformationGradient(u) J = kinematics.Jacobian(F) vol_form = (-1.0 / 3.0) * dolfin.dot(X + u, J * dolfin.inv(F).T * N) return vol_form
def calcCaps(self, u): x0, x1, x2 = dolfin.MeshCoordinates(self.mesh) eps = dolfin.conditional(x2 <= 0.0, self.eps_si, self.eps_di) cap_list = [0.0] * len(self.net_list) for electrode in self.elec_list: curr_net = electrode.net dS = dolfin.Measure("dS")[self.boundaries] n = dolfin.FacetNormal(self.mesh) m = dolfin.avg( dolfin.dot(eps * dolfin.grad(u), n)) * dS(7 + self.elec_list.index(electrode)) # average is used since +/- sides of facet are arbitrary v = dolfin.assemble(m) cap_list[self.net_list.index( curr_net)] = cap_list[self.net_list.index(curr_net)] + v self.cap_matrix.append(cap_list)
def __init__(self, simulation, var_name, inp_dict, subdomains, subdomain_id): """ Wall pressure boundary condition """ mesh = simulation.data['mesh'] n = dolfin.FacetNormal(mesh) g = simulation.data['g'] rho = simulation.data['rho'] bc_val = rho * dolfin.inner(n, g) # Store the boundary condition for use in the solver bc = OcellarisNeumannBC(simulation, bc_val, subdomain_id) bcs = simulation.data['neumann_bcs'] bcs.setdefault(var_name, []).append(bc) simulation.log.info(' WallPressure for %s' % var_name)