def checktheboundarycoordinates(bcsd, femp, plot=False): g1 = dolfin.Constant((0, 0)) for bc in bcsd: bcrl = dolfin.DirichletBC(femp['V'], g1, bc()) bcdict = bcrl.get_boundary_values() print bcdict.keys() bcinds = bcdict.keys() V = femp['V'] cylmesh = femp['V'].mesh() if plot: dolfin.plot(cylmesh) dolfin.interactive(True) gdim = cylmesh.geometry().dim() dofmap = V.dofmap() # Get coordinates as len(dofs) x gdim array dofs_x = dofmap.tabulate_all_coordinates(cylmesh).reshape((-1, gdim)) # for dof, dof_x in zip(dofs, dofs_x): # print dof, ':', dof_x xcenter = 0.2 ycenter = 0.2 for bcind in bcinds: dofx = dofs_x[bcind, :] dx = dofx[0] - xcenter dy = dofx[1] - ycenter r = dolfin.sqrt(dx*dx + dy*dy) print bcind, ':', dofx, r
def _adaptive_mesh_refinement(dx, phi, mu, sigma, omega, conv, voltages): from dolfin import cells, refine eta = _error_estimator(dx, phi, mu, sigma, omega, conv, voltages) mesh = phi.function_space().mesh() level = 0 TOL = 1.0e-4 E = sum([e * e for e in eta]) E = sqrt(MPI.sum(E)) info('Level %d: E = %g (TOL = %g)' % (level, E, TOL)) # Mark cells for refinement REFINE_RATIO = 0.5 cell_markers = MeshFunction('bool', mesh, mesh.topology().dim()) eta_0 = sorted(eta, reverse=True)[int(len(eta) * REFINE_RATIO)] eta_0 = MPI.max(eta_0) for c in cells(mesh): cell_markers[c] = eta[c.index()] > eta_0 # Refine mesh mesh = refine(mesh, cell_markers) # Plot mesh plot(mesh) interactive() exit() ## Compute error indicators #K = array([c.volume() for c in cells(mesh)]) #R = array([abs(source([c.midpoint().x(), c.midpoint().y()])) for c in cells(mesh)]) #gam = h*R*sqrt(K) return
def write_fenics_file(ofile, mesh, editor): dim = mesh.geometry().dim() for i in range(1, len(cell_map)+1): if dim == 2: editor.add_cell(i-1, cell_map[i][0]-1, cell_map[i][1]-1, cell_map[i][2]-1) else: editor.add_cell(i-1, cell_map[i][0]-1, cell_map[i][1]-1, cell_map[i][2]-1, cell_map[i][3]-1) mesh.order() # Set MeshValueCollections from info in boundary_cell #mvc = mesh.domains().markers(dim-1) md = mesh.domains() for zone, cells in boundary_cells.iteritems(): for cell, nds in cells.iteritems(): dolfin_cell = Cell(mesh, cell-1) vertices_of_cell = dolfin_cell.entities(0) vertices_of_face = nds - 1 for jj, ff in enumerate(facets(dolfin_cell)): facet_vertices = ff.entities(0) if all(map(lambda x: x in vertices_of_face, facet_vertices)): local_index = jj break #mvc.set_value(cell-1, local_index, zone) md.set_marker((ff.index(), zone), dim-1) ofile << mesh from dolfin import plot plot(mesh, interactive=True) print 'Finished writing FEniCS mesh\n'
def compute_functionals(self, velocity, pressure, t): if self.args.wss: info('Computing stress tensor') I = Identity(velocity.geometric_dimension()) T = TensorFunctionSpace(self.mesh, 'Lagrange', 1) stress = project(-pressure*I + 2*sym(grad(velocity)), T) info('Generating boundary mesh') wall_mesh = BoundaryMesh(self.mesh, 'exterior') # wall_mesh = SubMesh(self.mesh, self.facet_function, 1) # QQ why does not work? # plot(wall_mesh, interactive=True) info(' Boundary mesh geometric dim: %d' % wall_mesh.geometry().dim()) info(' Boundary mesh topologic dim: %d' % wall_mesh.topology().dim()) info('Projecting stress to boundary mesh') Tb = TensorFunctionSpace(wall_mesh, 'Lagrange', 1) stress_b = interpolate(stress, Tb) self.fileDict['wss']['file'] << stress_b if False: # does not work info('Computing WSS') n = FacetNormal(wall_mesh) info(stress_b, True) # wss = stress_b*n - inner(stress_b*n, n)*n wss = dot(stress_b, n) - inner(dot(stress_b, n), n)*n # equivalent Vb = VectorFunctionSpace(wall_mesh, 'Lagrange', 1) Sb = FunctionSpace(wall_mesh, 'Lagrange', 1) # wss_func = project(wss, Vb) wss_norm = project(sqrt(inner(wss, wss)), Sb) plot(wss_norm, interactive=True)
def main(): resolution = 96 # 32 * 3 filename = 'data/mesh_res_%d_boundary.xml' % resolution mesh_3d = dolfin.Mesh(filename) mesh_3d = dolfin.mesh.refine(mesh_3d) print '=' * 60 print 'Plotting in interactive mode' print '=' * 60 dolfin.plot(mesh_3d, '3D mesh', interactive=True)
def visualize(self, U, discretization, title="", legend=None, filename=None): """Visualize the provided data. Parameters ---------- U |VectorArray| of the data to visualize (length must be 1). Alternatively, a tuple of |VectorArrays| which will be visualized in separate windows. If `filename` is specified, only one |VectorArray| may be provided which, however, is allowed to contain multipled vectors which will be interpreted as a time series. discretization Filled in :meth:`pymor.discretizations.DiscretizationBase.visualize` (ignored). title Title of the plot. legend Description of the data that is plotted. If `U` is a tuple of |VectorArrays|, `legend` has to be a tuple of the same length. filename If specified, write the data to that file. `filename` needs to have an extension supported by FEniCS (e.g. `.pvd`). """ if filename: assert not isinstance(U, tuple) assert U in self.space f = df.File(filename) function = df.Function(self.function_space) if legend: function.rename(legend, legend) for u in U._list: function.vector()[:] = u.impl f << function else: assert ( U in self.space and len(U) == 1 or (isinstance(U, tuple) and all(u in self.space for u in U) and all(len(u) == 1 for u in U)) ) if not isinstance(U, tuple): U = (U,) if isinstance(legend, str): legend = (legend,) assert legend is None or len(legend) == len(U) for i, u in enumerate(U): function = df.Function(self.function_space) function.vector()[:] = u._list[0].impl if legend: tit = title + " -- " if title else "" tit += legend[i] else: tit = title df.plot(function, interactive=False, title=tit) df.interactive()
def main(): geometry_3d = get_geometry() dolfin.info(geometry_3d, True) resolution = 32 print "=" * 60 print "Creating mesh" print "=" * 60 mesh_3d = dolfin.Mesh(geometry_3d, resolution) print "=" * 60 print "Plotting in interactive mode" print "=" * 60 dolfin.plot(mesh_3d, "3D mesh", interactive=True)
def _compute_time_errors(problem, method, mesh_sizes, Dt, plot_error=False): mesh_generator, solution, ProblemClass, cell_type = problem() # Translate data into FEniCS expressions. fenics_sol = Expression(smp.printing.ccode(solution['value']), degree=solution['degree'], t=0.0, cell=cell_type ) # Compute the problem errors = {'theta': numpy.empty((len(mesh_sizes), len(Dt)))} # Create initial state. # Deepcopy the expression into theta0. Specify the cell to allow for # more involved operations with it (e.g., grad()). theta0 = Expression(fenics_sol.cppcode, degree=solution['degree'], t=0.0, cell=cell_type ) for k, mesh_size in enumerate(mesh_sizes): mesh = mesh_generator(mesh_size) V = FunctionSpace(mesh, 'CG', 1) theta_approx = Function(V) theta0p = project(theta0, V) stepper = method(ProblemClass(V)) if plot_error: error = Function(V) for j, dt in enumerate(Dt): # TODO We are facing a little bit of a problem here, being the # fact that the time stepper only accept elements from V as u0. # In principle, though, this isn't necessary or required. We # could allow for arbitrary expressions here, but then the API # would need changing for problem.lhs(t, u). # Think about this. stepper.step(theta_approx, theta0p, 0.0, dt, tol=1.0e-12, verbose=False ) fenics_sol.t = dt # # NOTE # When using errornorm(), it is quite likely to see a good part # of the error being due to the spatial discretization. Some # analyses "get rid" of this effect by (sometimes implicitly) # projecting the exact solution onto the discrete function # space. errors['theta'][k][j] = errornorm(fenics_sol, theta_approx) if plot_error: error.assign(project(fenics_sol - theta_approx, V)) plot(error, title='error (dt=%e)' % dt) interactive() return errors, stepper.name, stepper.order
def plot(self, **kwargs): func = self._fefunc # fix a bug in the fenics plot function that appears when # the maximum difference between data values is very small # compared to the magnitude of the data values = func.vector().array() diff = max(values) - min(values) magnitude = max(abs(values)) if diff < magnitude * 1e-8: logger.warning("PLOT: function values differ only by tiny amount -> plotting as constant") func = Function(func.function_space()) func.vector()[:] = values[0] plot(func, **kwargs)
def plot_indicators(indicators, mesh, refinements=1, interactive=True): DG = FunctionSpace(mesh, 'DG', 0) for _ in range(refinements): mesh = refine(mesh) V = FunctionSpace(refine(mesh), 'CG', 1) if len(indicators) == 1 and not isinstance(indicators[0], (list, tuple)): indicators = [indicators] for eta, title in indicators: e = Function(DG, eta) f = interpolate(e, V) plot(f, title=title) if interactive: from dolfin import interactive interactive()
def testit(problem='cylinderwake', N=2, nu=None, Re=1e2, Nts=1e3+1, ParaviewOutput=False, tE=1.0, scheme=None, zerocontrol=False): nnewtsteps = 9 # n nwtn stps for vel comp vel_nwtn_tol = 1e-14 tips = dict(t0=0.0, tE=tE, Nts=Nts) femp, stokesmatsc, rhsd_vfrc, rhsd_stbc \ = dnsps.get_sysmats(problem=problem, Re=Re, meshparams=dict(refinement_level=N), bccontrol=True, nu=nu, scheme=scheme) proutdir = 'results/' ddir = 'data/' data_prfx = problem + '_N{0}_Re{1}_Nts{2}_tE{3}'.\ format(N, femp['Re'], Nts, tE) dolfin.plot(femp['mesh']) palpha = 1e-5 stokesmatsc['A'] = stokesmatsc['A'] + 1./palpha*stokesmatsc['Arob'] if zerocontrol: Brob = 0.*1./palpha*stokesmatsc['Brob'] else: Brob = 1./palpha*stokesmatsc['Brob'] def fv_tmdp(time=0, v=None, **kw): return np.sin(time)*(Brob[:, :1] - Brob[:, 1:]), None soldict = stokesmatsc # containing A, J, JT soldict.update(femp) # adding V, Q, invinds, diribcs soldict.update(tips) # adding time integration params soldict.update(fv=rhsd_stbc['fv']+rhsd_vfrc['fvc'], fp=rhsd_stbc['fp']+rhsd_vfrc['fpr'], N=N, nu=nu, vel_nwtn_stps=nnewtsteps, # comp_nonl_semexp=True, treat_nonl_explct=True, vel_nwtn_tol=vel_nwtn_tol, fv_tmdp=fv_tmdp, start_ssstokes=True, get_datastring=None, data_prfx=ddir+data_prfx, paraviewoutput=ParaviewOutput, vel_pcrd_stps=1, clearprvdata=True, vfileprfx=proutdir+'vel_{0}_'.format(scheme), pfileprfx=proutdir+'p_{0}_'.format(scheme)) snu.solve_nse(**soldict)
def plot(args): from dolfin import plot, interactive, Mesh, Function, VectorFunctionSpace # Plot the mesh mesh = Mesh(args.xml) plot(mesh, title="Mesh") interactive() # Plot velocities if args.velocity is not None: G = VectorFunctionSpace(mesh, "DG", 0) base_file = args.velocity[:-4] + "_{}.xml" for i, u in enumerate(fvcom_reader.velocity): g = Function(G, base_file.format(i)) plot(g, title="Velocity time={}".format(i)) interactive()
def testit(problem='drivencavity', N=None, nu=1e-2, Re=None, nonltrt=None, t0=0.0, tE=1.0, Nts=1e2+1, ParaviewOutput=False, scheme='TH'): femp, stokesmatsc, rhsd = \ dnsps.get_sysmats(problem=problem, Re=Re, nu=nu, scheme=scheme, meshparams=dict(refinement_level=N), mergerhs=True) proutdir = 'results/' ddir = 'data/' data_prfx = problem + '{4}_N{0}_Re{1}_Nts{2}_tE{3}'.\ format(N, femp['Re'], Nts, tE, scheme) dolfin.plot(femp['V'].mesh()) # setting some parameters if Re is not None: nu = femp['charlen']/Re tips = dict(t0=t0, tE=tE, Nts=Nts) try: os.chdir(ddir) except OSError: raise Warning('need "' + ddir + '" subdir for storing the data') os.chdir('..') soldict = stokesmatsc # containing A, J, JT soldict.update(femp) # adding V, Q, invinds, diribcs soldict.update(tips) # adding time integration params soldict.update(fv=rhsd['fv'], fp=rhsd['fp'], N=N, nu=nu, start_ssstokes=True, get_datastring=None, treat_nonl_explct=nonltrt, data_prfx=ddir+data_prfx, paraviewoutput=ParaviewOutput, vfileprfx=proutdir+'vel_expnl_', pfileprfx=proutdir+'p_expnl') soldict.update(krylovdict) # if we wanna use an iterative solver # # compute the uncontrolled steady state Navier-Stokes solution # # v_ss_nse, list_norm_nwtnupd = snu.solve_steadystate_nse(**soldict) snu.solve_nse(**soldict)
def relax_system(mesh=mesh): Ms = 8.6e5 sim = Simulation(mesh, Ms, pbc='1d', unit_length=1e-9, name='relax') sim.set_m(m_init_skyrmion) A = 1.3e-11 D = 4e-3 sim.add(Exchange(A)) sim.add(DMI(D)) sim.add(Zeeman((0, 0, 0.4 * Ms))) #sim.run_until(1e-9) #sim.schedule('save_vtk', at_end=True) #sim.schedule(plot_m, every=1e-10, at_end=True) sim.relax() df.plot(sim.llg._m) np.save('relaxed.npy', sim.m)
def plot_domains(self, color='viridis'): """Plot labeled domains with color corresponding to their label. :parameter color: Name of the colormap to use """ if self.domains is None: raise ValueError("models Not Compiled") p = df.plot(self.domains) p.set_cmap(color)
def problem_whirl_cylindrical(): '''Pistol Pete's example from Teodora I. Mitkova's text "Finite-Elemente-Methoden fur die Stokes-Gleichungen", adapted for cylindrical Navier-Stokes. ''' alpha = 1.0 def mesh_generator(n): #return UnitSquareMesh(n, n, 'left/right') return RectangleMesh(alpha, 0.0, 1.0 + alpha, 1.0, n, n, 'left/right') cell_type = triangle x = smp.DeferredVector('x') # Note that the exact solution is indeed div-free. x0 = x[0] - alpha x1 = x[1] u = (x0 ** 2 * (1 - x0) ** 2 * 2 * x1 * (1 - x1) * (2 * x1 - 1) / x[0], x1 ** 2 * (1 - x1) ** 2 * 2 * x0 * (1 - x0) * (1 - 2 * x0) / x[0], 0 ) p = x0 * (1 - x0) * x1 * (1 - x1) solution = {'u': {'value': u, 'degree': numpy.infty}, 'p': {'value': p, 'degree': 4} } plot_solution = False if plot_solution: sol_u = Expression((smp.printing.ccode(u[0]), smp.printing.ccode(u[1])), degree=numpy.infty, t=0.0, cell=cell_type, ) plot(sol_u, mesh=mesh_generator(20) ) interactive() f = {'value': _get_navier_stokes_rhs_cylindrical(u, p), 'degree': numpy.infty } mu = 1.0 rho = 1.0 return mesh_generator, solution, f, mu, rho, cell_type
def plot_functions(functions, nrows=1): import matplotlib.pyplot as plt nfunctions = len(functions) if nrows == 1: ncols = nfunctions ncols = int(np.ceil(nfunctions/nrows)) for ii in range(nfunctions): ax = plt.subplot(nrows, ncols, ii+1) pp = dl.plot(functions[ii]) plt.colorbar(pp)
def figureHandling(self, Init=False, Update=False): """ Input: Init - Initialize plots/savefiles. Update - Updates the initialized plots/savefiles. """ if Init: if self.parameters['output']['plot']: if self.plotcomponents == []: self.file = d.File('%s/plot/u_0.pvd' % self.savepath) self.file << (self.u, float(self.t)) else: self.file = [ d.File('%s/plot/u%s_0.pvd' % (self.savepath, i)) for i in range(self.n) ] for i in self.plotcomponents: self.file[i] << (self.u.split()[i], float(self.t)) if self.parameters['drawplot']: self.plots = [plt.figure() for i in range(self.n)] if Update: if self.parameters['output']['plot']: if self.plotcomponents == []: self.file << (self.u, float(self.t)) else: for i in self.plotcomponents: self.file[i] << (self.u.split()[i], float(self.t)) if self.parameters['drawplot']: if self.plotcomponents == []: plt.figure(1) plt.cla() d.plot(self.u) plt.ion() plt.pause(0.001) else: for figureCounter in range(0, self.n): plt.figure(figureCounter + 1) # Must start with figure 1, not figure 0 plt.cla() d.plot(self.u.split()[figureCounter]) plt.ion() plt.pause(0.001)
def main(): filename = 'data/surfmesh.xml' mesh_3d = dolfin.Mesh(filename) # Plot in either case. print('Plotting in interactive mode') fh = dolfin.plot(mesh_3d, '3D mesh', interactive=True, window_width=900, window_height=700)
def _error_estimator(dx, phi, mu, sigma, omega, conv, voltages): '''Simple error estimator from A posteriori error estimation and adaptive mesh-refinement techniques; R. Verfürth; Journal of Computational and Applied Mathematics; Volume 50, Issues 1-3, 20 May 1994, Pages 67-83; <https://www.sciencedirect.com/science/article/pii/0377042794902909>. The strong PDE is - div(1/(mu r) grad(rphi)) + <u, 1/r grad(rphi)> + i sigma omega phi = sigma v_k / (2 pi r). ''' from dolfin import cells mesh = phi.function_space().mesh() # Assemble the cell-wise residual in DG space DG = FunctionSpace(mesh, 'DG', 0) # get residual in DG v = TestFunction(DG) R = _residual_strong(dx, v, phi, mu, sigma, omega, conv, voltages) r_r = assemble(R[0]) r_i = assemble(R[1]) r = r_r * r_r + r_i * r_i visualize = True if visualize: # Plot the cell-wise residual u = TrialFunction(DG) a = zero() * dx(0) subdomain_indices = mu.keys() for i in subdomain_indices: a += u * v * dx(i) A = assemble(a) R2 = Function(DG) solve(A, R2.vector(), r) plot(R2, title='||R||^2') interactive() K = r.array() info('%r' % K) h = numpy.array([c.diameter() for c in cells(mesh)]) eta = h * numpy.sqrt(K) return eta
def test_cut_mesh(): mesh = dolfin.UnitCubeMesh(2, 2, 2) mesh.init(3, 0) pt = (0.1, 0.1, 0.1) n = (0, 0, 1) mesh2d, cell_origins = make_cut_plane_mesh(pt, n, mesh) import pprint pprint.pprint(cell_origins) if False and mesh2d is not None: import matplotlib matplotlib.use('Agg') from matplotlib import pyplot fig = pyplot.figure() dolfin.plot(mesh2d) fig.savefig('test_cut_mesh.png')
def generate_H1_deformation(self): self.deformation = [] for i in range(1, self.N): S_i = VectorFunctionSpace(self.multimesh.part(i), "CG", 1) u_i, v_i = TrialFunction(S_i), TestFunction(S_i) d_free = Measure("ds", domain=self.multimesh.part(i), subdomain_data=self.mfs[i], subdomain_id=self.move_dict[i]["Deform"]) plot(-self.integrand_list[i - 1]) plt.show() a_i = inner(u_i, v_i) * dx + 0.01 * inner(grad(u_i), grad(v_i)) * dx n_i = FacetNormal(self.multimesh.part(i)) l_i = inner(v_i, -self.integrand_list[i - 1]) * d_free s_i = Function(S_i) solve(a_i == l_i, s_i) plot(s_i) plt.show() self.deformation.append(s_i)
def relax(mesh): Ms = 8.6e5 sim = Simulation(mesh, Ms, pbc='2d',unit_length=1e-9) sim.set_m(m_init_fun) sim.add(Exchange(1.3e-11)) sim.add(DMI(D = 4e-3)) sim.add(Zeeman((0,0,0.45*Ms))) sim.alpha = 0.5 ts = np.linspace(0, 1e-9, 101) for t in ts: sim.run_until(t) p = df.plot(sim.llg._m) sim.save_vtk() df.plot(sim.llg._m).write_png("vortex") df.interactive()
def solve2D_hybrid_PB(geo, phys, **params): globals().update(params) pb = solve_pde(SimplePBProblem, geo, phys, cyl=True, iterative=False, tolnewton=1e-2) pnps = PNPSHybrid(geo, phys, v0=pb.solution, cyl=True, inewton=1, ipicard=imax, tolnewton=tol, verbose=True, iterative=False) for i in pnps.fixedpoint(): dolfin.plot(pnps.functions["pnp"].sub(0), key="uhpb") return pnps.converged
def delta_cg(mesh, expr): V = df.FunctionSpace(mesh, "CG", 1) Vv = df.VectorFunctionSpace(mesh, "CG", 1) u = df.interpolate(expr, Vv) u1 = df.TrialFunction(Vv) v1 = df.TestFunction(Vv) K = df.assemble(df.inner(df.grad(u1), df.grad(v1)) * df.dx).array() L = df.assemble(df.dot(v1, df.Constant([1, 1, 1])) * df.dx).array() h = -np.dot(K, u.vector().array()) / L fun = df.Function(Vv) fun.vector().set_local(h) res = [] for x in xs: res.append(fun(x, 5, 0.5)[0]) df.plot(fun) return res
def problem_whirl_cylindrical(): """Example from Teodora I. Mitkova's text "Finite-Elemente-Methoden fur die Stokes-Gleichungen", adapted for cylindrical Navier-Stokes. """ alpha = 1.0 def mesh_generator(n): # return UnitSquareMesh(n, n, 'left/right') return RectangleMesh( Point(alpha, 0.0), Point(1.0 + alpha, 1.0), n, n, "left/right" ) cell_type = triangle x = sympy.DeferredVector("x") # Note that the exact solution is indeed div-free. x0 = x[0] - alpha x1 = x[1] u = ( x0 ** 2 * (1 - x0) ** 2 * 2 * x1 * (1 - x1) * (2 * x1 - 1) / x[0], x1 ** 2 * (1 - x1) ** 2 * 2 * x0 * (1 - x0) * (1 - 2 * x0) / x[0], 0, ) p = x0 * (1 - x0) * x1 * (1 - x1) solution = { "u": {"value": u, "degree": numpy.infty}, "p": {"value": p, "degree": 4}, } plot_solution = False if plot_solution: sol_u = Expression( (helpers.ccode(u[0]), helpers.ccode(u[1])), degree=numpy.infty, t=0.0, cell=cell_type, ) plot(sol_u, mesh=mesh_generator(20)) f = {"value": _get_navier_stokes_rhs_cylindrical(u, p), "degree": numpy.infty} mu = 1.0 rho = 1.0 return mesh_generator, solution, f, mu, rho, cell_type
def method(L=3., H=1., R=0.3, n_segments=40, res=60, show=False, **kwargs): """ Generates mesh of Snausen/Snoevsen. """ info("Generating mesh of Snoevsen.") # Define points: pt_A = df.Point(0., 0.) pt_B = df.Point(L, H) pt_C = df.Point(L / 2 - 2 * R, 0.) pt_D = df.Point(L / 2 + 2 * R, 0.) pt_E = df.Point(L / 2 - 2 * R, -R) pt_F = df.Point(L / 2 + 2 * R, -R) pt_G = df.Point(L / 2, -R) tube = mshr.Rectangle(pt_A, pt_B) add_rect = mshr.Rectangle(pt_E, pt_D) neg_circ_L = mshr.Circle(pt_E, R, segments=n_segments) neg_circ_R = mshr.Circle(pt_F, R, segments=n_segments) pos_circ = mshr.Circle(pt_G, R, segments=n_segments) domain = tube + add_rect - neg_circ_L - neg_circ_R + pos_circ mesh = mshr.generate_mesh(domain, res) # check that mesh is periodic along x boun = df.BoundaryMesh(mesh, "exterior") y = boun.coordinates()[:, 1] y = y[y < 1.] y = y[y > 0.] n_y = len(y) n_y_unique = len(np.unique(y)) assert (n_y == 2 * n_y_unique) mesh_path = os.path.join(MESHES_DIR, "snoevsen_res" + str(res)) store_mesh_HDF5(mesh, mesh_path) if show: df.plot(mesh, "Mesh") plt.show()
def write_fenics_file(dim, ofilename): ofile = File(ofilename + '.xml') mesh = Mesh() editor = MeshEditor() editor.open(mesh, dim, dim) editor.init_vertices(nodes.shape[1]) editor.init_cells(len(cell_map)) for i in range(nodes.shape[1]): if dim == 2: editor.add_vertex(i, nodes[0, i], nodes[1, i]) else: editor.add_vertex(i, nodes[0, i], nodes[1, i], nodes[2, i]) for i in range(1, len(cell_map)+1): if dim == 2: editor.add_cell(i-1, cell_map[i][0]-1, cell_map[i][1]-1, cell_map[i][2]-1) else: editor.add_cell(i-1, cell_map[i][0]-1, cell_map[i][1]-1, cell_map[i][2]-1, cell_map[i][3]-1) mesh.order() mvc = mesh.domains().markers(dim-1) for zone, cells in boundary_cells.iteritems(): for cell, nds in cells.iteritems(): dolfin_cell = Cell(mesh, cell-1) nodes_of_cell = dolfin_cell.entities(0) #print cell #print nodes_of_cell nodes_of_face = nds - 1 #print nodes_of_face for jj, ff in enumerate(facets(dolfin_cell)): facet_nodes = ff.entities(0) #print facet_nodes if all(map(lambda x: x in nodes_of_face, facet_nodes)): local_index = jj break mvc.set_value(cell-1, local_index, zone) ofile << mesh from dolfin import plot plot(mesh, interactive=True) print 'Finished writing FEniCS mesh\n'
def _plot_mesh(self): if self.mesh.dimension < 3: self.logger.info("Plotting mesh") d.plot(self.mesh.mesh, title='mesh') plt.show() p = d.plot(self.mesh.cells, title="subdomains ") loc = plticker.MultipleLocator(base=1.0) # some hacks from the internet plt.colorbar(p, format='%d', ticks=loc, fraction=0.03, pad=0.04) plt.show() self.logger.debug( "Mesh was plotted, subdomains and facets also match the mesh") else: self.logger.info( "Plotting mesh does not make sense in 3D. Output is written to paraview readable files." ) self.mesh_dir = "mesh/" if not os.path.exists(self.mesh_dir): try: os.makedirs(self.mesh_dir) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise tmp = d.XDMFFile( self.mesh.mesh.mpi_comm(), self.mesh_dir + self.mesh.meshname + str('_plot.xdmf')) tmp.write(self.mesh.mesh) tmp.close() tmp = d.XDMFFile( self.mesh.mesh.mpi_comm(), self.mesh_dir + self.mesh.meshname + str('_subdomains') + str('.xdmf')) tmp.write(self.mesh.cells) tmp.close() tmp = d.XDMFFile( self.mesh.mesh.mpi_comm(), self.mesh_dir + self.mesh.meshname + str('_facets') + str('.xdmf')) tmp.write(self.mesh.facets) tmp.close() self.logger.debug("Mesh was written out.")
def method(res=10, height=1, length=5, use_mshr=False, show=False, **kwargs): ''' Function that generates a mesh for a straight capillary, default meshing method is Dolfin's RectangleMesh, but there is an option for mshr. Note: The generated mesh is stored in "BERNAISE/meshes/". ''' if use_mshr: # use mshr for the generation info("Generating mesh using the mshr tool") # Define coners of Rectangle a = df.Point(0, 0) b = df.Point(height, length) domain = mshr.Rectangle(a, b) mesh = mshr.generate_mesh(domain, res) meshpath = os.path.join( MESHES_DIR, "straight_capillary_mshr_h{}_l{}_res{}".format( height, length, res)) info("Done.") else: # use the Dolfin built-in function info("Generating mesh using the Dolfin built-in function.") # Define coners of rectangle/capilar a = df.Point(0, 0) b = df.Point(height, length) # Setting the reselution if height <= length: num_points_height = res num_points_length = res * int(length / height) else: num_points_height = res * int(height / length) num_points_length = res mesh = df.RectangleMesh(a, b, num_points_height, num_points_length) meshpath = os.path.join( MESHES_DIR, "straight_capillary_dolfin_h{}_l{}_res{}".format( height, length, res)) store_mesh_HDF5(mesh, meshpath) if show: df.plot(mesh) plt.show()
def generate_mesh_with_cicular_subdomain(resolution, radius, plot_mesh=False): cx1, cy1 = 0.5, 0.5 lx, ly = 1.0, 1.0 # Define 2D geometry domain = mshr.Rectangle(dl.Point(0.0, 0.0), dl.Point(lx, ly)) domain.set_subdomain(1, mshr.Circle(dl.Point(cx1, cy1), radius)) cx2, cy2 = cx1 - radius / np.sqrt(8), cy1 - radius / np.sqrt(8) domain.set_subdomain(2, mshr.Circle(dl.Point(cx2, cy2), radius / 2)) # Generate and plot mesh mesh2d = mshr.generate_mesh(domain, resolution) if plot_mesh: dl.plot(mesh2d, "2D mesh") class Circle1(dl.SubDomain): def inside(self, x, on_boundary): return pow(x[0] - cx1, 2) + pow(x[1] - cy1, 2) <= pow( radius, 2) class Circle2(dl.SubDomain): def inside(self, x, on_boundary): return pow(x[0] - cx2, 2) + pow(x[1] - cy2, 2) <= pow( radius / 2, 2) # Convert subdomains to mesh function for plotting mf = dl.MeshFunction("size_t", mesh2d, 2) mf.set_all(0) circle1 = Circle1() circle2 = Circle2() for c in dl.cells(mesh2d): if circle1.inside(c.midpoint(), True): mf[c.index()] = 1 if circle2.inside(c.midpoint(), True): mf[c.index()] = 2 dl.plot(mf, "Subdomains") # show must be called here or plot gets messed up # plt.show() return mesh2d
def generate_polygonal_mesh(resolution, ampothem, nedges, radius, plot_mesh=False): """ Sometimes segault is thrown when mshr.generate_mesh() is called. This is because resolution is to low to resolve smaller inner-most circle. """ import mshr vertices = get_vertices_of_polygon(ampothem, nedges) domain_vertices = [] for vertex in vertices.T: domain_vertices.append(dl.Point(vertex[0], vertex[1])) domain = mshr.Polygon(domain_vertices) cx1, cy1 = 0.0, 0.0 circle1 = mshr.Circle(dl.Point(cx1, cy1), radius) domain.set_subdomain(1, circle1) cx2, cy2 = cx1 - radius / np.sqrt(8), cy1 - radius / np.sqrt(8) circle2 = mshr.Circle(dl.Point(cx2, cy2), radius / 2) domain.set_subdomain(2, circle2) mesh = mshr.generate_mesh(domain, resolution) if plot_mesh: subdomains = dl.MeshFunction('size_t', mesh, mesh.topology().dim(), 2) subdomains.set_all(0) subdomain1 = dl.AutoSubDomain(lambda x: np.sqrt( (x[0] - cx1)**2 + (x[1] - cy1)**2) < radius + 1e-8) subdomain1.mark(subdomains, 1) subdomain2 = dl.AutoSubDomain(lambda x: np.sqrt( (x[0] - cx2)**2 + (x[1] - cy2)**2) < radius / 2 + 1e-8) subdomain2.mark(subdomains, 2) dl.plot(mesh) dl.plot(subdomains) plt.show() return mesh
def solve(geo, dops): tic() t = dolfin.Timer("phys") phys = nanopores.Physics("finfet", geo, dopants=dops, vD=None, vG=None, vS=None) phys.add_dopants t.stop() dolfin.plot(geo.submesh("source"), key="dop", title="dopants in source") t = dolfin.Timer("init") pde = nanopores.NonstandardPB(geo, phys) pde.tolnewton = 1e-8 pde.newtondamp = 1. t.stop() t = dolfin.Timer("solve") pde.solve() t.stop() u = pde.solution print "Loop time: %s s" %(toc(),) return u
def move_skyrmion(mesh): Ms = 8.6e5 sim = Simulation(mesh, Ms, pbc='2d', unit_length=1e-9) sim.set_m(np.load('m0.npy')) sim.add(Exchange(1.3e-11)) sim.add(DMI(D=4e-3)) sim.add(Zeeman((0, 0, 0.45 * Ms))) sim.alpha = 0.01 sim.set_zhangli(init_J, 1.0, 0.01) ts = np.linspace(0, 10e-9, 101) for t in ts: sim.run_until(t) print t #p = df.plot(sim.llg._m) sim.save_vtk(filename='vtks/v1e7_.pvd') df.plot(sim.llg._m).write_png("vortex")
def prerefine(setup, visualize=False): geo, phys, p = setup.geo, setup.phys, setup.solverp dolfin.tic() if setup.geop.x0 is None: goal = phys.CurrentPB else: goal = lambda v: phys.CurrentPB(v) + phys.Fbare(v, phys.dim-1) pb = simplepnps.SimpleLinearPBGO(geo, phys, goal=goal, cheapest=p.cheapest) for i in pb.adaptive_loop(p.Nmax, p.frac, verbose=True): if visualize: if phys.dim==3: nano.plot_sliced_mesh(geo, title="adapted mesh", key="b", elevate=-90. if i==1 else 0.) #dolfin.plot(geo.submesh("solid"), key="b", # title="adapted solid mesh") if phys.dim==2: dolfin.plot(geo.boundaries, key="b", title="adapted mesh", scalarbar=False) print "CPU time (PB): %.3g s" %(dolfin.toc(),) return pb
def criterion_h(self): est_1, est_2, est_3, Est_1, Est_2, Est_3 = \ self.estimate_errors_overall() u = self._w.sub(0) N = self._w.function_space().dim() dolfin.plot(u, title='solution at N = %d' % N) dofs.append(N) est.append([est_1, est_2, est_3]) u.rename("velocity", "") Est_1.rename("residual_1 estimate", "") Est_2.rename("residual_2 estimate", "") Est_3.rename("residual_3 estimate", "") f_u.write(u, N) f_Est_1.write(Est_1, N) f_Est_2.write(Est_2, N) f_Est_3.write(Est_3, N) return GeneralizedStokesProblem.criterion_h(self)
def create_mesh(self, parameters): from dolfin import Point, XDMFFile import hashlib d = { 'rad': parameters['geometry']['rad'], 'h': parameters['geometry']['meshsize'] } # fname = 'coinforall' # fname = 'coin' fname = 'coinforall_small' meshfile = "meshes/%s-%s.xml" % (fname, self.signature) if os.path.isfile(meshfile): print("Meshfile %s exists" % meshfile) else: print("Create meshfile, meshsize {}".format( parameters['geometry']['meshsize'])) nel = int(parameters['geometry']['rad'] / parameters['geometry']['meshsize']) # geom = mshr.Circle(Point(0., 0.), parameters['geometry']['rad']) # mesh = mshr.generate_mesh(geom, nel) mesh_template = open('scripts/coin_template.geo') src = Template(mesh_template.read()) geofile = src.substitute(d) if MPI.rank(MPI.comm_world) == 0: with open("scripts/coin-%s" % self.signature + ".geo", 'w') as f: f.write(geofile) form_compiler_parameters = { "representation": "uflacs", "quadrature_degree": 2, "optimize": True, "cpp_optimize": True, } mesh = Mesh("meshes/{}.xml".format(fname)) self.domains = MeshFunction( 'size_t', mesh, 'meshes/{}_physical_region.xml'.format(fname)) self.ds = Measure("exterior_facet", domain=mesh) self.dS = Measure("interior_facet", domain=mesh) self.dx = Measure("dx", metadata=form_compiler_parameters, subdomain_data=self.domains) # self.dx = Measure("dx", subdomain_data=self.domains) plt.colorbar(plot(self.domains)) plt.savefig('domains.pdf') return mesh
def move_skyrmion(mesh): Ms = 8.6e5 sim = Simulation(mesh, Ms, pbc='2d',unit_length=1e-9, kernel='llg_stt') sim.set_m(np.load('m0.npy')) sim.add(Exchange(1.3e-11)) sim.add(DMI(D = 4e-3)) sim.add(Zeeman((0,0,0.45*Ms))) sim.alpha=0.01 sim.llg.set_parameters(J_profile=init_J, speedup=50) ts = np.linspace(0, 5e-9, 101) for t in ts: sim.run_until(t) print t #p = df.plot(sim.llg._m) sim.save_vtk(filename='nonlocal/v1e7_.pvd') df.plot(sim.llg._m).write_png("vortex")
def plot_sliced(geo, **params): tol = 1e-5 class Back(dolfin.SubDomain): def inside(self, x, on_boundary): return x[1] >= -tol back = dolfin.CellFunction("size_t", geo.mesh, 0) Back().mark(back, 1) submesh = dolfin.SubMesh(geo.mesh, back, 1) #plot(submesh) bb = geo.mesh.bounding_box_tree() subsub = dolfin.CellFunction("size_t", submesh, 0) sub = geo.subdomains for cell in dolfin.cells(submesh): iparent = bb.compute_first_entity_collision(cell.midpoint()) subsub[cell] = sub[int(iparent)] plot_params = dict(title="sliced geometry with subdomains", elevate=-90., **params) dolfin.plot(subsub, **plot_params)
def compute_noweb(pool): # Load pool into DOLFIN's parameters data structure from parampool.utils import set_dolfin_prm import dolfin pool.traverse(set_dolfin_prm, user_data=dolfin.parameters) # Load user's parameters Nx = pool.get_value('Nx') Ny = pool.get_value('Ny') degree = pool.get_value('element degree') f_str = pool.get_value('f') u0_str = pool.get_value('u0') f = dolfin.Expression(f_str) u0 = dolfin.Expression(u0_str) from poisson_solver import solver u = solver(f, u0, Nx, Ny, degree) #dolfin.plot(u, title='Solution', interactive=True) from poisson_iterative import gradient grad_u = gradient(u) grad_u_x, grad_u_y = grad_u.split(deepcopy=True) # Make VTK file, offer for download vtkfile = dolfin.File('poisson2D.pvd') vtkfile << u vtkfile << grad_u dolfin.plot(u) dolfin.plot(u.function_space().mesh()) dolfin.plot(grad_u) dolfin.interactive()
def plot_scalar_field(function, figname=None, title=None): if not isinstance(function, dolfin.Function): raise TypeError( 'Parameter `function` must be of type `dolfin.Function.`.') fh = plt.figure(figname) fh.clear() ah = fh.add_subplot(111) dolfin.plot(function) dim = len(function.ufl_shape) vec = function.vector().get_local() if dim > 0: delta_max = math.sqrt((vec**2).reshape((-1, dim)).sum(1).max()) else: delta_max = np.abs(vec).max() # annotation = '$\delta_{max}$ = ' + f'{delta_max:.3g}' # plt.annotate(annotation, # xy=(1, 0), xycoords='axes fraction', # xytext=(-12, 12), textcoords='offset points', # horizontalalignment='right',verticalalignment='bottom', # bbox=dict(boxstyle="round", fc="w", ec="k", pad=0.3, alpha=0.75)) ah.set_ylabel('y (mm)') ah.set_xlabel('x (mm)') if title is not None: ah.set_title(title) plt.axis('equal') plt.axis('image') plt.tight_layout() return fh, simplify_figure_name(figname)
def onclick(event): if print_point: print('(', event.xdata, ',', event.ydata, ')') delta_p = dl.PointSource(function_space_V, dl.Point(event.xdata, event.ydata), 1.0) if event.button == 3: point_source_dual_vector[:] = 0. delta_p.apply(point_source_dual_vector) Adelta.vector()[:] = apply_A(point_source_dual_vector) plt.clf() c = dl.plot(Adelta) plt.colorbar(c) plt.title('left click adds points, right click resets') plt.draw()
def solve_cycle(state): print('Solving state:', state['name']) # u1.assign(state['u_prev']) u0.assign(state['u_last']) p0.assign(state['pressure']) rhs.assign( project(dt * (-u0.dx(0) * u0 - nu * u0.dx(0).dx(0) / 2.0 - p0.dx(0)), Q)) plot(rhs, title='RHS') # rhs_nonlinear.assign(project(dt*(- u0.dx(0)*u0), Q)) # rhs_visc.assign(project(dt*(-nu*u0.dx(0).dx(0)/2.0), Q)) # rhs_pressure.assign(project(dt*(-p0.dx(0)), Q)) # plot(rhs_nonlinear, title='RHS nonlin') # plot(rhs_visc, title='RHS visc') # plot(rhs_pressure, title='RHS pressure') solve(a_tent == L_tent, u_tent_computed, bcu) if state['rot']: if state['null']: b = assemble(L_p_rot) null_space.orthogonalize(b) solve(A_p_rot, p_computed.vector(), b, 'cg') else: solve(a_p_rot == L_p_rot, p_computed, bcp) solve(a_cor_rot == L_cor_rot, u_cor_computed) div_u_tent.assign(project(-nu * u_tent_computed.dx(0), Vplot)) plot(div_u_tent, title=state['name'] + '_div u_tent (pressure correction), t = ' + str(t)) # div_u_tent.assign(project(p0+p_computed-nu*state['p_tent'].dx(0), Q)) # plot(div_u_tent, title=state['name']+'_RHS (pressure correction), t = ' +str(t)) solve(a_rot == L_rot, p_cor_computed) p_correction.assign(p_cor_computed - p_computed - p0) plot(p_correction, title=state['name'] + '_(computed pressure correction), t = ' + str(t)) print(' updating state') state['u_prev'].assign(state['u_last']) state['u_tent'].assign(u_tent_computed) state['u_last'].assign(u_cor_computed) state['pressure'].assign(p_cor_computed) state['p_tent'].assign(p_computed + p0) else: if state['null']: b = assemble(L_p) null_space.orthogonalize(b) print('new:', assemble((v_in_expr - u_tent_computed) * ds(2))) # plot(interpolate((v_in_expr-u_tent_computed)*ds(2), Q), title='new') # print(A_p.array()) # print(b.array()) solve(A_p, p_computed.vector(), b, 'gmres') else: solve(a_p == L_p, p_computed, bcp) solve(a_cor == L_cor, u_cor_computed) print(' updating state') # state['u_prev'].assign(state['u_last']) state['u_tent'].assign(u_tent_computed) state['u_last'].assign(u_cor_computed) state['pressure'].assign(p_computed)
def example1_sundials(Ms): x0 = y0 = z0 = 0 x1 = y1 = z1 = 10 nx = ny = nz = 1 mesh = df.Box(x0, x1, y0, y1, z0, z1, nx, ny, nz) S1 = df.FunctionSpace(mesh, "Lagrange", 1) S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1, dim=3) vis = df.Function(S3) llb = LLB(S1, S3) llb.alpha = 0.00 llb.set_m((1, 1, 1)) llb.Ms = Ms H_app = Zeeman((0, 0, 1e5)) H_app.setup(S3, llb._m, Ms=Ms) llb.interactions.append(H_app) exchange = BaryakhtarExchange(13.0e-12, 1e-2) exchange.setup(S3, llb._m, llb._Ms) llb.interactions.append(exchange) integrator = llg_integrator(llb, llb.M, abstol=1e-10, reltol=1e-6) max_time = 2 * np.pi / (llb.gamma * 1e5) ts = np.linspace(0, max_time, num=50) mlist = [] Ms_average = [] for t in ts: integrator.advance_time(t) mlist.append(integrator.m.copy()) llb.M = mlist[-1] vis.vector()[:] = mlist[-1] Ms_average.append(llb.M_average) df.plot(vis) time.sleep(0.0) print llb.count save_plot(ts, Ms_average, 'Ms_%g-time-sundials.png' % Ms) df.interactive()
def __init__(self, n=16, divide=1, threshold=12.3, left_side_num=3, left_side_denom=4): """ Store parameters, initialize data exports (latex, txt). """ # left_side_num/denom are either height, assuming base is 1, # or left and bottom side lengths self.n = n self.threshold = threshold / left_side_denom ** 2 self.left_side = [0] * (n + 1) self.bottom_side = [0] * (n + 1) self.left_side_len = left_side_num * 1.0 / left_side_denom self.left_side_num = left_side_num self.left_side_denom = left_side_denom self.folder = "results" self.name = "domains_{}_{}_{}".format(n, divide, threshold) self.filename = self.folder + "/" + self.name + ".tex" self.matrixZname = self.folder + "/matrices_Z/" + self.name self.matrixQname = self.folder + "/matrices_Q/" + self.name self.genericname = self.folder + "/" + self.name self.textname = self.folder + "/" + self.name + ".txt" f = open(self.textname, 'w') f.close() self.latex = "cd " + self.folder + "; pdflatex --interaction=batchmode" \ + " {0}.tex; rm {0}.aux {0}.log".format(self.name) self.shift = 0 # common mesh, ready to cut/apply Dirichlet BC self.mesh = Triangle(self.left_side_num, left_side_denom) while self.mesh.size(2) < self.n * self.n: self.mesh = refine(self.mesh) for i in range(divide): self.mesh = refine(self.mesh) boundary = MeshFunction("size_t", self.mesh, 1) boundary.set_all(0) self.plotted = plot( boundary, prefix='animation/animation', scalarbar=False, window_width=1024, window_height=1024) print 'Grid size: ', self.n ** 2 print 'Mesh size: ', self.mesh.size(2) # setup solver self.solver = Solver(self.mesh, left_side_num, left_side_denom) self.mass = self.solver.B self.stiff = self.solver.A print np.unique(self.stiff.data) self.save_matrices(0) # save dofs f = open(self.genericname+'_dofmap.txt', 'w') for vec in self.solver.dofs: print >>f, vec f.close()
def plot(self, sub=False): geo = self.create_geometry() if not hasattr(self, "geo") else self.geo if hasattr(geo, "subdomains"): dolfin.plot(geo.subdomains) dolfin.plot(geo.boundaries) else: dolfin.plot(geo.mesh) dolfin.interactive()
def test_dirichlet_solver(): Lx = 1.0 Ly = 1.0 Nx = 100 Ny = 100 mesh = df.RectangleMesh(df.Point(0, 0), df.Point(Lx, Ly), Nx, Ny) df.plot(mesh, interactive=True) V = df.FunctionSpace(mesh, "CG", 1) d = mesh.geometry().dim() L = np.empty(2 * d) for i in range(d): l_min = mesh.coordinates()[:, i].min() l_max = mesh.coordinates()[:, i].max() L[i] = l_min L[d + i] = l_max u_D = df.Expression('1 + x[0]*x[0] + 2*x[1]*x[1]', degree=2) f = df.Constant(-6.0) bc = DirichletBC(V, u_D, NonPeriodicBoundary(Ld)) poisson = PoissonSolver(V, bc) phi = poisson.solve(f) error_l2 = df.errornorm(u_D, phi, "L2") print("l2 norm: ", error_l2) vertex_values_u_D = u_D.compute_vertex_values(mesh) vertex_values_phi = phi.compute_vertex_values(mesh) error_max = np.max(vertex_values_u_D - \ vertex_values_phi) tol = 1E-10 msg = 'error_max = %g' % error_max assert error_max < tol, msg df.plot(phi, interactive=True)
def mk_limiter(degree, dim, use_cpp, comm_self=False): dolfin.parameters['ghost_mode'] = 'shared_vertex' sim = Simulation() sim.input.read_yaml(yaml_string=BASE_INPUT) if dim == 2: sim.input.set_value('mesh/type', 'Rectangle') sim.input.set_value('mesh/Nx', 10) sim.input.set_value('mesh/Ny', 10) cpp = 'A + A*sin(B*pi*x[0])*sin(B*pi*x[1])' else: sim.input.set_value('mesh/type', 'Box') sim.input.set_value('mesh/Nx', 5) sim.input.set_value('mesh/Ny', 5) sim.input.set_value('mesh/Nz', 5) cpp = 'A + A*sin(B*pi*x[0])*sin(B*pi*x[1])*sin(B*pi*x[2])' # Create simulation with mesh and the phi function sim.input.set_value('mesh/mpi_comm', 'SELF' if comm_self else 'WORLD') sim.input.set_value('solver/polynomial_degree', degree) sim.input.set_value('output/stdout_enabled', False) setup_simulation(sim) phi = sim.data['phi'] V = phi.function_space() # Create a phi field with some jumps e = dolfin.Expression(cpp, element=V.ufl_element(), A=0.5, B=2.0) phi.interpolate(e) arr = phi.vector().get_local() arr[arr > 0.8] = 2 * 0.8 - arr[arr > 0.8] arr[arr < 0.2] = 0.5 phi.vector().set_local(arr) phi.vector().apply('insert') # Create slope limiter sim.input.set_value('slope_limiter/phi/method', 'HierarchicalTaylor') sim.input.set_value('slope_limiter/phi/use_cpp', use_cpp) sim.input.set_value('slope_limiter/phi/skip_boundaries', []) lim = SlopeLimiter(sim, 'phi', phi) if True: from matplotlib import pyplot pyplot.figure() patches = dolfin.plot(phi) pyplot.colorbar(patches) pyplot.savefig('ht_lim_phi.png') return phi, lim
def main(): resolution = 96 # 32 * 3 filename = 'data/mesh_res_%d_boundary.xml' % resolution if os.path.exists(filename): print '=' * 60 print 'Mesh file exists, loading from file' print '=' * 60 mesh_3d = dolfin.Mesh(filename) else: geometry_3d = get_geometry() dolfin.info(geometry_3d, True) print '=' * 60 print 'Creating mesh' print '=' * 60 mesh_3d = dolfin.Mesh(geometry_3d, resolution) print '=' * 60 print 'Converting to a boundary mesh' print '=' * 60 mesh_3d = dolfin.BoundaryMesh(mesh_3d, 'exterior') # Since much smaller, it's much easier to refine the boundary mesh # as well. It may be worth doing this via: # mesh_3d = dolfin.mesh.refine(mesh_3d) print '=' * 60 print 'Saving to file:', filename print '=' * 60 data_file = dolfin.File(filename) data_file << mesh_3d # Plot in either case. print '=' * 60 print 'Plotting in interactive mode' print '=' * 60 dolfin.plot(mesh_3d, '3D mesh', interactive=True)
def check_input_opa(NU, femp=None): if femp is None: # from dolfin_navier_scipy.problem_setups import cyl_fems # femp = cyl_fems(2) from dolfin_navier_scipy.problem_setups import drivcav_fems femp = drivcav_fems(20) V = femp["V"] Q = femp["Q"] cdcoo = femp["cdcoo"] # get the system matrices stokesmats = dts.get_stokessysmats(V, Q) # check the B B1, Mu = cou.get_inp_opa(cdcoo=cdcoo, V=V, NU=NU, xcomp=0) B2, Mu = cou.get_inp_opa(cdcoo=cdcoo, V=V, NU=NU, xcomp=1) # get the rhs expression of Bu Bu1 = spsla.spsolve( stokesmats["M"], B1 * np.vstack([np.linspace(0, 1, NU).reshape((NU, 1)), np.linspace(0, 1, NU).reshape((NU, 1))]), ) Bu2 = spsla.spsolve( stokesmats["M"], B2 * np.vstack([np.linspace(0, 1, NU).reshape((NU, 1)), np.linspace(0, 1, NU).reshape((NU, 1))]), ) Bu3 = spsla.spsolve(stokesmats["M"], B1 * np.vstack([1 * np.ones((NU, 1)), 0.2 * np.ones((NU, 1))])) bu1 = dolfin.Function(V) bu1.vector().set_local(Bu1) bu1.vector()[2] = 1 # for scaling and illustration purposes bu2 = dolfin.Function(V) bu2.vector().set_local(Bu2) bu2.vector()[2] = 1 # for scaling and illustration purposes bu3 = dolfin.Function(V) bu3.vector().set_local(Bu3) bu3.vector()[2] = 1 # for scaling and illustration purposes plt.figure(11) dolfin.plot(bu1, title="plot of Bu - extending in x") plt.figure(12) dolfin.plot(bu2, title="plot of Bu - extending in y") plt.figure(13) dolfin.plot(bu3, title="plot of Bu - extending in y") # dolfin.plot(V.mesh()) dolfin.interactive() plt.show(block=False)
def solve_cycle(state): print('Solving state:', state['name']) # u1.assign(state['u_prev']) u0.assign(state['u_last']) p0.assign(state['pressure']) rhs.assign(project(dt*(- u0.dx(0)*u0 - nu*u0.dx(0).dx(0)/2.0 - p0.dx(0)), Q)) plot(rhs, title='RHS') # rhs_nonlinear.assign(project(dt*(- u0.dx(0)*u0), Q)) # rhs_visc.assign(project(dt*(-nu*u0.dx(0).dx(0)/2.0), Q)) # rhs_pressure.assign(project(dt*(-p0.dx(0)), Q)) # plot(rhs_nonlinear, title='RHS nonlin') # plot(rhs_visc, title='RHS visc') # plot(rhs_pressure, title='RHS pressure') solve(a_tent == L_tent, u_tent_computed, bcu) if state['rot']: if state['null']: b = assemble(L_p_rot) null_space.orthogonalize(b) solve(A_p_rot, p_computed.vector(), b, 'cg') else: solve(a_p_rot == L_p_rot, p_computed, bcp) solve(a_cor_rot == L_cor_rot, u_cor_computed) div_u_tent.assign(project(-nu*u_tent_computed.dx(0), Vplot)) plot(div_u_tent, title=state['name']+'_div u_tent (pressure correction), t = ' +str(t)) # div_u_tent.assign(project(p0+p_computed-nu*state['p_tent'].dx(0), Q)) # plot(div_u_tent, title=state['name']+'_RHS (pressure correction), t = ' +str(t)) solve(a_rot == L_rot, p_cor_computed) p_correction.assign(p_cor_computed-p_computed-p0) plot(p_correction, title=state['name']+'_(computed pressure correction), t = ' +str(t)) print(' updating state') state['u_prev'].assign(state['u_last']) state['u_tent'].assign(u_tent_computed) state['u_last'].assign(u_cor_computed) state['pressure'].assign(p_cor_computed) state['p_tent'].assign(p_computed+p0) else: if state['null']: b = assemble(L_p) null_space.orthogonalize(b) print('new:', assemble((v_in_expr-u_tent_computed)*ds(2))) # plot(interpolate((v_in_expr-u_tent_computed)*ds(2), Q), title='new') # print(A_p.array()) # print(b.array()) solve(A_p, p_computed.vector(), b, 'gmres') else: solve(a_p == L_p, p_computed, bcp) solve(a_cor == L_cor, u_cor_computed) print(' updating state') # state['u_prev'].assign(state['u_last']) state['u_tent'].assign(u_tent_computed) state['u_last'].assign(u_cor_computed) state['pressure'].assign(p_computed)
def test_stationary_solve(show=False): problem = problems.Crucible() boundaries = problem.wp_boundaries average_temp = 1551.0 material = problem.subdomain_materials[problem.wpi] rho = material.density(average_temp) cp = material.specific_heat_capacity kappa = material.thermal_conductivity my_ds = Measure("ds")(subdomain_data=boundaries) convection = None heat = maelstrom.heat.Heat( problem.Q, kappa, rho, cp, convection, source=Constant(0.0), dirichlet_bcs=problem.theta_bcs_d, neumann_bcs=problem.theta_bcs_n, robin_bcs=problem.theta_bcs_r, my_dx=dx, my_ds=my_ds, ) theta_reference = heat.solve_stationary() theta_reference.rename("theta", "temperature") if show: # with XDMFFile('temperature.xdmf') as f: # f.parameters['flush_output'] = True # f.parameters['rewrite_function_mesh'] = False # f.write(theta_reference) tri = plot(theta_reference) plt.colorbar(tri) plt.show() assert abs(maelstrom.helpers.average(theta_reference) - 1551.0) < 1.0e-1 return theta_reference
def main(mesh_filename='meshfile', resolution=32): filename = '%s.%s' % (mesh_filename, 'xml') if os.path.exists(filename): print('Mesh file exists, loading from file') mesh_3d = dolfin.Mesh(filename) else: geometry_3d = get_geometry() dolfin.info(geometry_3d, True) print('Creating mesh') mesh_3d = dolfin.Mesh(geometry_3d, resolution) print('Saving to file:'); print(filename) data_file = dolfin.File(filename) data_file << mesh_3d # Plot in either case. print('Plotting in interactive mode') fh = dolfin.plot(mesh_3d, '3D mesh', interactive=True, window_width=900, window_height=700)
def main(): resolution = 32 # 32 * 3 # filename = 'data/mesh_res_%d_boundary.xml' % resolution filename = "data/mesh_res_%d_boundary.xml" % resolution if os.path.exists(filename): print "=" * 60 print "Mesh file exists, loading from file" print "=" * 60 mesh_3d = dolfin.Mesh(filename) else: geometry_3d = get_geometry() dolfin.info(geometry_3d, True) print "=" * 60 print "Creating mesh" print "=" * 60 mesh_3d = dolfin.Mesh(geometry_3d, resolution) print "=" * 60 print "Converting to a boundary mesh" print "=" * 60 mesh_3d = dolfin.BoundaryMesh(mesh_3d, "exterior") # Since much smaller, it's much easier to refine the boundary mesh # as well. It may be worth doing this via: # mesh_3d = dolfin.mesh.refine(mesh_3d) print "=" * 60 print "Saving to file:", filename print "=" * 60 data_file = dolfin.File(filename) data_file << mesh_3d # Plot in either case. print "=" * 60 print "Plotting in interactive mode" print "=" * 60 fh = dolfin.plot(mesh_3d, "3D mesh", interactive=True, window_width=900, window_height=700)
def main(): def round_trip_connect(start, end): result = [] for i in range(start, end): result.append((i, i+1)) result.append((end, start)) return result corners, mesh1, mesh2 = generate_meshes(2, 1, 0.3) points = get_vertices(corners, mesh1, mesh2) print "points", np.array(points) info = triangle.MeshInfo() info.set_points(points) info.set_facets(round_trip_connect(0, len(corners)-1)) mesh = triangle.build(info, allow_volume_steiner=False, allow_boundary_steiner=False, min_angle=60) if False: print "vertices:" for i, p in enumerate(mesh.points): print i, p print "point numbers in triangles:" for i, t in enumerate(mesh.elements): print i, t finemesh = Mesh() ME = MeshEditor() ME.open(finemesh,2,2) ME.init_vertices(len(mesh.points)) ME.init_cells(len(mesh.elements)) for i,v in enumerate(mesh.points): ME.add_vertex(i,v[0],v[1]) for i,c in enumerate(mesh.elements): ME.add_cell(i,c[0],c[1],c[2]) ME.close() triangle.write_gnuplot_mesh("triangles.dat", mesh) plot(mesh1) plot(mesh2) plot(finemesh) interactive()
def plot_state(state, t): print('Plotting state:', state['name']) # plot(state['u_tent'], title=state['name']+'_u_tent') # interactive() # exit() # state['u_tent'].set_allow_extrapolation(True) state['u_tent_plot'].assign(interpolate(state['u_tent'], Vplot)) state['u_last_plot'].assign(interpolate(state['u_last'], Vplot)) if doSavePlot: utp = plot(state['u_tent_plot'], title=state['name']+'_u_tent, t = ' +str(t), range_min=0., range_max=2*v_in, window_width= width, window_height= height) utp.write_png('%s/%d_u_tent' % (dir, step)) else: plot(state['u_tent_plot'], title=state['name']+'_u_tent, t = ' +str(t), range_min=-v_in, range_max=3*v_in) if doSavePlot: ucp = plot(state['u_last_plot'], title=state['name']+'_u_corrected, t = ' +str(t), range_min=0., range_max=2*v_in, window_width= width, window_height= height) ucp.write_png('%s/%d_u_cor' % (dir, step)) else: plot(state['u_last_plot'], title=state['name']+'_u_corrected, t = ' +str(t), range_min=-v_in, range_max=3*v_in) if state['rot']: if doSavePlot: # prp = plot(state['p_tent'], title=state['name']+'_pressure, t = ' +str(t), range_min=-1000., range_max=1100., window_width= width, window_height= height) prp = plot(state['p_tent'], title=state['name']+'_pressure, t = ' +str(t), range_min=0., range_max=2100., window_width= width, window_height= height) prp.write_png('%s/%d_u_pres' % (dir, step)) else: plot(state['p_tent'], title=state['name']+'_tentative pressure, t = ' +str(t)) if doSavePlot: # prp = plot(state['pressure'], title=state['name']+'_corrected pressure, t = ' +str(t), range_min=-1000., range_max=1100., window_width= width, window_height= height) prp = plot(state['pressure'], title=state['name']+'_corrected pressure, t = ' +str(t), range_min=0., range_max=2100., window_width= width, window_height= height) prp.write_png('%s/%d_pres_cor' % (dir, step)) else: plot(state['pressure'], title=state['name']+'_corrected pressure, t = ' +str(t)) else: if doSavePlot: # prp = plot(state['pressure'], title=state['name']+'_pressure, t = ' +str(t), range_min=-1000., range_max=1100., window_width= width, window_height= height) prp = plot(state['pressure'], title=state['name']+'_pressure, t = ' +str(t), range_min=0., range_max=2100., window_width= width, window_height= height) prp.write_png('%s/%d_pres' % (dir, step)) else: plot(state['pressure'], title=state['name']+'_pressure, t = ' +str(t))
mesh_plot = IntervalMesh(8*mesh_size, 0.0, length) boundary_parts = FacetFunction('size_t', mesh) right = AutoSubDomain(lambda x: near(x[0], length)) left = AutoSubDomain(lambda x: near(x[0], 0.0)) right.mark(boundary_parts, 2) left.mark(boundary_parts, 1) # Create function spaces V = FunctionSpace(mesh, 'Lagrange', 2) # Vplot = FunctionSpace(mesh_plot, 'Lagrange', 1) Vplot = V Q = FunctionSpace(mesh, 'Lagrange', 1) # BC conditions, nullspace v_in_expr = Constant(v_in) plt = plot(interpolate(v_in_expr, V), range_min=0., range_max=2*v_in, window_width= width, window_height= height) plt.write_png('%s/correct' % dir) # v_in_expr = Expression('(t<1.0)?t*v:v', v=Constant(v_in), t=0.0) # v_in_expr = Expression('(t<1.0)?(1-cos(pi*t))*v*0.5:v', v=Constant(v_in), t=0.0) bcp = DirichletBC(Q, Constant(0.0), boundary_parts, 2) bcu = DirichletBC(V, v_in_expr, boundary_parts, 1) foo = Function(Q) null_vec = Vector(foo.vector()) Q.dofmap().set(null_vec, 1.0) null_vec *= 1.0/null_vec.norm('l2') # print(null_vec.array()) null_space = VectorSpaceBasis([null_vec]) ds = Measure("ds", subdomain_data=boundary_parts) # Define forms (dont redefine functions used here)