def _generateMesh(self, *args): from netgen.csg import CSGeometry, Sphere, Pnt from ngsolve import Mesh r = self.getRadius() geometry = CSGeometry() sphere = Sphere(Pnt(0, 0, 0), r).bc("sphere") geometry.Add(sphere) self.geometry = geometry self.mesh = Mesh(geometry.GenerateMesh(maxh=r / 5)) ngsolve.Draw(self.mesh)
def set_initial_conditions(self, gfu_IC: ngs.GridFunction, mesh: ngs.Mesh, model_name: str, model_components: Dict[str, int]) -> None: """ Function to load the initial conditions from their configfile into a gridfunction. Args: mesh: The model's mesh. model_name: Sometimes several models will use the same IC configfile. This identifies which model's ICs should be loaded. gfu_IC: A gridfunction to hold the initial conditions. model_components: Maps between variable names and their component in the model's finite element space. """ coef_dict = {} file_dict = {} for var, marker_dict in self.ic_dict[model_name].items(): # Determine which component of the gridfunction the initial condition is for if var == 'all': component = None else: component = model_components[var] # Check if the initial condition is specified as a file, a coefficientfunction, or a dict of material # markers and coefficientfunctions. if len(marker_dict) == 1: # One single file or coefficientfunction. assert next(iter(marker_dict.keys())) == 'all' val = next(iter(marker_dict.values())) if val is None: # No initial condition needed so just keep the zeroed out gridfunction. return if isinstance(val, str): # Check that the file exists. val = self._find_rel_path_for_file(val) file_dict[component] = val else: coef_dict[component] = val else: # Need to construct a coefficientfunction from a set of material markers. coef = ngs.CoefficientFunction([marker_dict[mat] for mat in mesh.GetMaterials()]) coef_dict[component] = coef if coef_dict: load_coefficientfunction_into_gridfunction(gfu_IC, coef_dict) if file_dict: update_gridfunction_from_files(gfu_IC, file_dict)
from netgen.csg import * from ngsolve import Mesh geo = CSGeometry() # Set the mesh size on the sphere surface to 0.1 sphere = Sphere(Pnt(0, 0, 0), 2).maxh(0.1) # meshsize of the surface of the brick will not be finer than # the volume mesh size brick = OrthoBrick(Pnt(-5, -5, -5), Pnt(5, 5, 5)) # # rodbase = Cylinder(Pnt(-3, 0, 0), Pnt(0, 0, 0), 1.0) rodplane1 = Plane(Pnt(-5, 0, 0), Vec(-1, 0, 0)) rodplane2 = Plane(Pnt(-5, 0, 0), Vec(1, 0, 0)) rod = rodbase * rodplane1 * rodplane2 brickrod = sphere + rod # in the outer region we don't give a local mesh size -> global # is used geo.Add(brick - brickrod) # in the volume of the sphere we set the meshsize to 0.2 geo.Add(brickrod, maxh=0.2) # the global mesh size is set to 0.4 ngmesh = geo.GenerateMesh(maxh=0.4) # for visualization we need a NGSolve mesh Draw(Mesh(ngmesh))
import ngsolve as ngs from ngsolve import VTKOutput, sqrt, Mesh, exp, x, GridFunction from netgen.geom2d import unit_square from wave import vec, waveA, makeforms # PARAMETERS: p = 3 # polynomial degree h0 = 1 # coarse mesh size for unit square domain markprm = 0.5 # percentage of max total error for marking # SET UP: mesh = Mesh(unit_square.GenerateMesh(maxh=h0)) q_zero = 'bottom' # Mesh boundary parts where q and mu_zero = 'bottom|right|left' # mu has essential b.c u00 = exp(-1000 * ((x - 0.5) * (x - 0.5))) # Nonzero initial condition cwave = 1. # wave speed F = ngs.CoefficientFunction((0, 0)) # Zero source a, f, X, sep = makeforms(mesh, p, F, q_zero, mu_zero, cwave, epsil=1.e-10) euz = GridFunction(X) # Contains solution at each adaptive step q = euz.components[sep[0]] # Volume (L2) components mu = euz.components[sep[0]+1] zq = euz.components[sep[1]] # Interface components zmu = euz.components[sep[1]+1] zq.Set(u00, definedon='bottom')
# solve the Poisson equation -Delta u = f # with Dirichlet boundary condition u = 0 from ngsolve import Mesh, H1, LinearForm, x, y, dx, BilinearForm, grad, GridFunction, Draw, ngsglobals, sqrt, Integrate from netgen.geom2d import unit_square ngsglobals.msg_level = 1 # generate a triangular mesh of mesh-size 0.2 mesh = Mesh(unit_square.GenerateMesh(maxh=0.2)) # H1-conforming finite element space fes = H1(mesh, order=3, dirichlet=[1,2,3,4]) # define trial- and test-functions u = fes.TrialFunction() v = fes.TestFunction() # the right hand side f = LinearForm(fes) f += 32 * (y*(1-y)+x*(1-x)) * v * dx # the bilinear-form a = BilinearForm(fes, symmetric=True) a += grad(u)*grad(v)*dx a.Assemble() f.Assemble() # the solution field gfu = GridFunction(fes)
def discretize_ngsolve(): from ngsolve import (ngsglobals, Mesh, H1, CoefficientFunction, LinearForm, SymbolicLFI, BilinearForm, SymbolicBFI, grad, TaskManager) from netgen.csg import CSGeometry, OrthoBrick, Pnt import numpy as np ngsglobals.msg_level = 1 geo = CSGeometry() obox = OrthoBrick(Pnt(-1, -1, -1), Pnt(1, 1, 1)).bc("outer") b = [] b.append( OrthoBrick(Pnt(-1, -1, -1), Pnt(0.0, 0.0, 0.0)).mat("mat1").bc("inner")) b.append( OrthoBrick(Pnt(-1, 0, -1), Pnt(0.0, 1.0, 0.0)).mat("mat2").bc("inner")) b.append( OrthoBrick(Pnt(0, -1, -1), Pnt(1.0, 0.0, 0.0)).mat("mat3").bc("inner")) b.append( OrthoBrick(Pnt(0, 0, -1), Pnt(1.0, 1.0, 0.0)).mat("mat4").bc("inner")) b.append( OrthoBrick(Pnt(-1, -1, 0), Pnt(0.0, 0.0, 1.0)).mat("mat5").bc("inner")) b.append( OrthoBrick(Pnt(-1, 0, 0), Pnt(0.0, 1.0, 1.0)).mat("mat6").bc("inner")) b.append( OrthoBrick(Pnt(0, -1, 0), Pnt(1.0, 0.0, 1.0)).mat("mat7").bc("inner")) b.append( OrthoBrick(Pnt(0, 0, 0), Pnt(1.0, 1.0, 1.0)).mat("mat8").bc("inner")) box = (obox - b[0] - b[1] - b[2] - b[3] - b[4] - b[5] - b[6] - b[7]) geo.Add(box) for bi in b: geo.Add(bi) # domain 0 is empty! mesh = Mesh(geo.GenerateMesh(maxh=0.3)) # H1-conforming finite element space V = H1(mesh, order=NGS_ORDER, dirichlet="outer") v = V.TestFunction() u = V.TrialFunction() # Coeff as array: variable coefficient function (one CoefFct. per domain): sourcefct = CoefficientFunction([1 for i in range(9)]) with TaskManager(): # the right hand side f = LinearForm(V) f += SymbolicLFI(sourcefct * v) f.Assemble() # the bilinear-form mats = [] coeffs = [[0, 1, 0, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0]] for c in coeffs: diffusion = CoefficientFunction(c) a = BilinearForm(V, symmetric=False) a += SymbolicBFI(diffusion * grad(u) * grad(v), definedon=(np.where(np.array(c) == 1)[0] + 1).tolist()) a.Assemble() mats.append(a.mat) from pymor.bindings.ngsolve import NGSolveVectorSpace, NGSolveMatrixOperator, NGSolveVisualizer space = NGSolveVectorSpace(V) op = LincombOperator( [NGSolveMatrixOperator(m, space, space) for m in mats], [ ProjectionParameterFunctional('diffusion', (len(coeffs), ), (i, )) for i in range(len(coeffs)) ]) h1_0_op = op.assemble([1] * len(coeffs)).with_(name='h1_0_semi') F = space.zeros() F._list[0].real_part.impl.vec.data = f.vec F = VectorOperator(F) return StationaryModel(op, F, visualizer=NGSolveVisualizer(mesh, V), products={'h1_0_semi': h1_0_op}, parameter_space=CubicParameterSpace( op.parameter_type, 0.1, 1.))
def Nanorod(aeff, ratio, mt_length): geo = CSGeometry() if ratio == 1: return Nanosphere(aeff, mt_length) if mt_length == 0: radius = aeff * (2 / (3 * ratio - 1))**(1 / 3) length = 2 * radius * ratio cyl_length = length / 2 - radius physical_space = length + 100 domain = physical_space + 150 #Endcaps sphere1 = Sphere(Pnt(0, -cyl_length, 0), radius) sphere2 = Sphere(Pnt(0, cyl_length, 0), radius) #Water sphere3 = Sphere(Pnt(0, 0, 0), physical_space) #PML sphere4 = Sphere(Pnt(0, 0, 0), domain).bc('outer') cyl1 = Cylinder(Pnt(0, -2 * cyl_length, 0), Pnt(0, 2 * cyl_length, 0), radius) cyl2 = Cylinder(Pnt(0, -2 * physical_space, 0), Pnt(0, 2 * physical_space, 0), radius + 100) cyl3 = Cylinder(Pnt(0, -2 * domain, 0), Pnt(0, 2 * domain, 0), radius + 200).bc('outer') plane1 = Plane(Pnt(0, -cyl_length, 0), Vec(0, -1, 0)) plane2 = Plane(Pnt(0, cyl_length, 0), Vec(0, 1, 0)) plane3 = Plane(Pnt(0, -physical_space, 0), Vec(0, -1, 0)) plane4 = Plane(Pnt(0, physical_space, 0), Vec(0, 1, 0)) plane5 = Plane(Pnt(0, -domain, 0), Vec(0, -1, 0)) plane6 = Plane(Pnt(0, domain, 0), Vec(0, 1, 0)) middle = cyl1 * plane1 * plane2 AuNP = (middle + sphere1 + sphere2).mat('gold') water = (cyl2 * plane3 * plane4 - AuNP).mat('water') pmldom = (cyl3 * plane5 * plane6 - cyl2 * plane3 * plane4).mat('pml') geo.Add(AuNP) geo.Add(water) geo.Add(pmldom) else: radius = aeff * (2 / (3 * ratio - 1))**(1 / 3) length = 2 * radius * ratio cyl_length = length / 2 - radius particle = radius + mt_length physical_space = length + mt_length + 100 domain = physical_space + 150 #Nanoparticle cyl1 = Cylinder(Pnt(0, -1, 0), Pnt(0, 1, 0), radius) #Microtubules cyl2 = Cylinder(Pnt(0, -1, 0), Pnt(0, 1, 0), particle) #Water cyl3 = Cylinder(Pnt(0, -1, 0), Pnt(0, 1, 0), particle + 100) #PML cyl4 = Cylinder(Pnt(0, -2, 0), Pnt(0, 2, 0), particle + 150).bc('outer') #Nanoparticle endcaps sphere1 = Sphere(Pnt(0, -cyl_length, 0), radius) sphere2 = Sphere(Pnt(0, cyl_length, 0), radius) #Microtubule endcaps sphere3 = Sphere(Pnt(0, -cyl_length, 0), particle) sphere4 = Sphere(Pnt(0, cyl_length, 0), particle) #Endcap cut-offs plane1 = Plane(Pnt(0, -cyl_length, 0), Vec(0, -1, 0)) plane2 = Plane(Pnt(0, cyl_length, 0), Vec(0, 1, 0)) plane3 = Plane(Pnt(0, -physical_space, 0), Vec(0, -1, 0)) plane4 = Plane(Pnt(0, physical_space, 0), Vec(0, 1, 0)) plane5 = Plane(Pnt(0, -domain, 0), Vec(0, -1, 0)) plane6 = Plane(Pnt(0, domain, 0), Vec(0, 1, 0)) middle = cyl1 * plane1 * plane2 AuNP = (middle + sphere1 + sphere2).mat('gold') mt_middle = ((cyl2 - cyl1) * plane1 * plane2).mat('mt_mid') endcap1_mt = (sphere3 - plane1) - sphere1 endcap2_mt = (sphere4 - plane2) - sphere2 mt_endcaps = (endcap1_mt + endcap2_mt).mat('mt_end') total_body = AuNP + endcap1_mt + endcap2_mt + mt_middle water = (cyl3 * plane3 * plane4 - total_body).mat('water') pmldom = ((cyl4 - cyl3) * plane5 * plane6 - (water + total_body)).mat('pml') geo.Add(AuNP) geo.Add(mt_endcaps) geo.Add(mt_middle) geo.Add(water) geo.Add(pmldom) ngmesh = geo.GenerateMesh() mesh = Mesh(ngmesh) p = pml.BrickRadial((-domain, -domain, -domain), (domain, domain, domain), alpha=1J) mesh.SetPML(p, 'pml') return mesh, radius, length
def Nanosphere(particle, mt_length, physical_space, domain, mt_model="radial"): # physical_space = particle + mt_length + 150 # domain = physical_space + 200 particle /= 100 mt_length /= 100 physical_space /= 100 domain /= 100 geo = CSGeometry() if mt_length == 0: sphere1 = Sphere(Pnt(0, 0, 0), particle) sphere2 = Sphere(Pnt(0, 0, 0), physical_space) sphere3 = Sphere(Pnt(0, 0, 0), domain).bc('outer') AuNP = sphere1.mat('gold') water = (sphere2 - sphere1).mat('water') pmldom = (sphere3 - sphere2).mat('pml') geo.Add(AuNP) geo.Add(water) geo.Add(pmldom, maxh=.7) else: if mt_model == "radial": sphere1 = Sphere(Pnt(0, 0, 0), particle) sphere2 = Sphere(Pnt(0, 0, 0), particle + mt_length) sphere3 = Sphere(Pnt(0, 0, 0), physical_space) sphere4 = Sphere(Pnt(0, 0, 0), domain).bc('outer') AuNP = sphere1.mat('gold') mt = (sphere2 - sphere1).mat('mt_sphere') water = (sphere3 - sphere2).mat('water') pmldom = (sphere4 - sphere3).mat('pml') geo.Add(AuNP) geo.Add(mt) geo.Add(water) geo.Add(pmldom) else: mt_radius = .125 # 12.5 nm sphere1 = Sphere(Pnt(0, 0, 0), particle) sphere2 = Sphere(Pnt(0, 0, 0), physical_space) sphere3 = Sphere(Pnt(0, 0, 0), domain).bc('outer') cyl1 = Cylinder(Pnt(0, 0, 0), Pnt(0, 0, 1), mt_radius) cyl2 = Cylinder(Pnt(0, 0, 0), Pnt(0, 1, 0), mt_radius) cyl3 = Cylinder(Pnt(0, 0, 0), Pnt(1, 0, 0), mt_radius) plane1 = Plane(Pnt(0, 0, mt_length + particle), Vec(0, 0, 1)) plane2 = Plane(Pnt(0, 0, -(mt_length + particle)), Vec(0, 0, -1)) plane3 = Plane(Pnt(0, mt_length + particle, 0), Vec(0, 1, 0)) plane4 = Plane(Pnt(0, -(mt_length + particle), 0), Vec(0, -1, 0)) plane5 = Plane(Pnt(mt_length + particle, 0, 0), Vec(1, 0, 0)) plane6 = Plane(Pnt(-(mt_length + particle), 0, 0), Vec(-1, 0, 0)) mt1 = ((plane2 * cyl1 * plane1) - sphere1).mat("mt_cyl") mt2 = ((plane3 * cyl2 * plane4) - sphere1).mat("mt_cyl") mt3 = ((plane5 * cyl3 * plane6) - sphere1).mat("mt_cyl") AuNP = sphere1.mat("gold") water = ((((sphere2 - mt1) - mt2) - mt3) - AuNP).mat("water") pmldom = (sphere3 - sphere2).mat("pml") geo.Add(AuNP) geo.Add(mt1) geo.Add(mt2) geo.Add(mt3) geo.Add(water) geo.Add(pmldom, maxh=1) ngmesh = geo.GenerateMesh(maxh=2) mesh = Mesh(ngmesh) p = pml.Radial(origin=(0, 0, 0), rad=domain) mesh.SetPML(p, 'pml') return mesh, particle, particle
def test_2_polyhedra(): geo = CSGeometry() first = Polyhedron([(0, 0, 0), (0, 1, 0), (3, 1, 0), (3, 0, 0), (0, 1, 1), (3, 1, 1), (3, 0, 1), (0, 0, 1)], [(0, 1, 2, 3), (1, 4, 5, 2), (2, 5, 6, 3), (3, 6, 7, 0), (0, 7, 4, 1), (7, 6, 5, 4)]) # TODO: height = 0.1 not working! height = 0.3 second = Polyhedron([(0, 0, 1), (0, 1, 1), (3, 1, 1), (3, 0, 1), (0, 1, 1 + height), (3, 1, 1 + height), (3, 0, 1 + height), (0, 0, 1 + height)], [(0, 1, 2, 3), (1, 4, 5, 2), (2, 5, 6, 3), (3, 6, 7, 0), (0, 7, 4, 1), (7, 6, 5, 4)]) geo.Add(first) geo.Add(second) mesh = geo.GenerateMesh() return mesh if __name__ == "__main__": from ngsolve import Mesh, Draw mesh = Mesh(test_2_polyhedra()) Draw(mesh)
def set_dirichlet_boundary_conditions(self, bc_dict: Dict[str, Dict[str, Dict[str, Union[ngs.CoefficientFunction, float, ngs.GridFunction]]]], mesh: ngs.Mesh, gfu: ngs.GridFunction, model_components: Dict) \ -> Dict[str, ngs.CoefficientFunction]: """ Function to load the strongly imposed Dirichlet BCs in order to apply them to the solution gridfunction. Args: bc_dict: Dict specifying the BCs and their mesh markers for each variable. The BCs are all given as floats, gridfunctions, or coefficientfunctions. mesh: The model's mesh. gfu: A gridfunction constructed on the model's finite element space. model_components: The model's model_components dict. Returns: g_D: Dict of coefficientfunctions used to set the strongly imposed Dirichlet BCs. """ # Initialize empty g_D = {} if len(bc_dict['dirichlet']) > 0: for var in bc_dict['dirichlet']: # List of values for Dirichlet BCs for each variable dirichlet_lst = [] if var == 'p': # Pressure BCs are weakly imposed, thus we skip them. pass else: for marker in mesh.GetBoundaries(): # Get the Dirichlet BC value for this marker, or default to 0.0 if there isn't one. The 0.0 # will later be overwritten when the other types of boundary conditions are imposed. component = model_components[var] # TODO: This is a hack. There should be a better way of doing this, but ngs.FESpace doesn't seem # to have a dim argument that corresponds to the dimension of the space. if component is None: if gfu.dim == 1: alternate = 0.0 else: alternate = tuple([0.0] * gfu.dim) else: if gfu.components[component].dim == 1: alternate = 0.0 else: alternate = tuple( [0.0] * gfu.components[component].dim) val = bc_dict['dirichlet'][var].get(marker, alternate) # Store the value in a list. dirichlet_lst.append(val) # Format the list of mesh markers for the Dirichlet BCs. g_D[var] = ngs.CoefficientFunction(dirichlet_lst) if len(bc_dict['pinned']) > 0: for var in bc_dict['pinned']: if var in g_D.keys(): # Check that the variable doesn't already have Dirichlet BCs specified. raise ValueError( 'Dirichlet boundary conditions have been specified for {0}. It is unnecessary to ' 'also pin the value of {0} at a point.'.format(var)) # List of values for pinned BCs for each variable pinned_lst = [] for marker in mesh.GetBoundaries(): # Get the pinned BC value for this marker, or default to 0.0 if there isn't one. The 0.0 # will later be overwritten when the other types of boundary conditions are imposed. component = model_components[var] # TODO: This is a hack. There should be a better way of doing this, but ngs.FESpace doesn't seem # to have a dim argument that corresponds to the dimension of the space. if component is None: if gfu.dim == 1: alternate = 0.0 else: alternate = tuple([0.0] * gfu.dim) else: if gfu.components[component].dim == 1: alternate = 0.0 else: alternate = tuple([0.0] * gfu.components[component].dim) val = bc_dict['pinned'][var].get(marker, alternate) # Store the value in a list. pinned_lst.append(val) # Format the list of mesh markers for the pinned BCs. g_D[var] = ngs.CoefficientFunction(pinned_lst) return g_D
def ProdMesh(ngmeshbase, t_steps, dirichletsplit=False): ngmesh = ngm.Mesh() ngmesh.dim = 3 pnums = [] for p in ngmeshbase.Points(): x, y, z = p.p ngmesh.Add(ngm.MeshPoint(ngm.Pnt(x, y, 0))) for i, p in enumerate(ngmeshbase.Points()): x, y, z = p.p pnums.append(ngmesh.Add(ngm.MeshPoint(ngm.Pnt(x, y, t_steps)))) El1d = ngmeshbase.Elements1D() El2d = ngmeshbase.Elements2D() ngmesh.SetMaterial(1, "mat") for el in El2d: ngmesh.Add( ngm.Element3D(1, [ pnums[el.points[0].nr - 1], pnums[el.points[1].nr - 1], pnums[el.points[2].nr - 1], el.points[0].nr, el.points[1].nr, el.points[2].nr ])) fde = ngm.FaceDescriptor(surfnr=1, domin=1, bc=1) fde.bcname = "bottom" fdid = ngmesh.Add(fde) for el in El2d: ngmesh.Add( ngm.Element2D(fdid, [el.points[2].nr, el.points[1].nr, el.points[0].nr])) fde = ngm.FaceDescriptor(surfnr=2, domin=1, bc=2) fde.bcname = "top" fdid = ngmesh.Add(fde) for el in El2d: ngmesh.Add( ngm.Element2D(fdid, [ pnums[el.points[0].nr - 1], pnums[el.points[1].nr - 1], pnums[el.points[2].nr - 1] ])) if dirichletsplit == False: fde = ngm.FaceDescriptor(surfnr=3, domin=1, bc=3) fde.bcname = "dirichlet" fdid = ngmesh.Add(fde) for el in El1d: ngmesh.Add( ngm.Element2D(fdid, [ el.points[0].nr, el.points[1].nr, pnums[el.points[1].nr - 1], pnums[el.points[0].nr - 1] ])) ngmesh.SetBCName(2, "dirichlet") if dirichletsplit == True: fde = ngm.FaceDescriptor(surfnr=3, domin=1, bc=3) fde.bcname = "front" fdid = ngmesh.Add(fde) for el in El1d: if ngmeshbase.Points()[el.points[0]][1] == 0: ngmesh.Add( ngm.Element2D(fdid, [ el.points[0].nr, el.points[1].nr, pnums[el.points[1].nr - 1], pnums[el.points[0].nr - 1] ])) fde = ngm.FaceDescriptor(surfnr=4, domin=1, bc=4) fde.bcname = "back" fdid = ngmesh.Add(fde) for el in El1d: if ngmeshbase.Points()[el.points[0]][1] == 1: ngmesh.Add( ngm.Element2D(fdid, [ el.points[0].nr, el.points[1].nr, pnums[el.points[1].nr - 1], pnums[el.points[0].nr - 1] ])) fde = ngm.FaceDescriptor(surfnr=5, domin=1, bc=5) fde.bcname = "left" fdid = ngmesh.Add(fde) for el in El1d: if ngmeshbase.Points()[el.points[0]][0] == 0: ngmesh.Add( ngm.Element2D(fdid, [ el.points[0].nr, el.points[1].nr, pnums[el.points[1].nr - 1], pnums[el.points[0].nr - 1] ])) fde = ngm.FaceDescriptor(surfnr=6, domin=1, bc=6) fde.bcname = "right" fdid = ngmesh.Add(fde) for el in El1d: if ngmeshbase.Points()[el.points[0]][0] == 1: ngmesh.Add( ngm.Element2D(fdid, [ el.points[0].nr, el.points[1].nr, pnums[el.points[1].nr - 1], pnums[el.points[0].nr - 1] ])) ngmesh.SetBCName(2, "front") ngmesh.SetBCName(3, "back") ngmesh.SetBCName(4, "left") ngmesh.SetBCName(5, "right") ngmesh.SetBCName(0, "bottom") ngmesh.SetBCName(1, "top") mesh = Mesh(ngmesh) return mesh
def CartSquare(N, t_steps, xscale=1, xshift=0, tscale=1): ngmesh = ngm.Mesh() ngmesh.SetGeometry(unit_square) ngmesh.dim = 2 pnums = [] for j in range(t_steps + 1): for i in range(N + 1): pnums.append( ngmesh.Add( ngm.MeshPoint( ngm.Pnt((i / N) * xscale - xshift, (j / t_steps) * tscale, 0)))) foo = ngm.FaceDescriptor(surfnr=1, domin=1, bc=1) ngmesh.Add(foo) ngmesh.SetMaterial(1, "mat") for j in range(t_steps): for i in range(N): ngmesh.Add( ngm.Element2D(1, [ pnums[i + j * (N + 1)], pnums[i + 1 + j * (N + 1)], pnums[i + 1 + (j + 1) * (N + 1)], pnums[i + (j + 1) * (N + 1)] ])) fde = ngm.FaceDescriptor(surfnr=1, domin=1, bc=1) fde.bcname = "bottom" fdid = ngmesh.Add(fde) for i in range(N): ngmesh.Add(ngm.Element1D([pnums[i], pnums[i + 1]], index=1)) fde = ngm.FaceDescriptor(surfnr=2, domin=1, bc=2) fde.bcname = "top" fdid = ngmesh.Add(fde) for i in range(N): ngmesh.Add( ngm.Element1D([ pnums[i + t_steps * (N + 1)], pnums[i + 1 + t_steps * (N + 1)] ], index=2)) fde = ngm.FaceDescriptor(surfnr=3, domin=1, bc=3) fde.bcname = "dirichlet" fdid = ngmesh.Add(fde) for i in range(t_steps): ngmesh.Add( ngm.Element1D( [pnums[N + i * (N + 1)], pnums[N + (i + 1) * (N + 1)]], index=3)) ngmesh.Add( ngm.Element1D( [pnums[0 + i * (N + 1)], pnums[0 + (i + 1) * (N + 1)]], index=3)) ngmesh.SetBCName(0, "bottom") ngmesh.SetBCName(1, "top") ngmesh.SetBCName(2, "dirichlet") mesh = Mesh(ngmesh) # print("boundaries" + str(mesh.GetBoundaries())) return mesh
def FolderMaker(Geometry, Single, Array, Omega, Pod, PlotPod, PODArray, PODTol, alpha, Order, MeshSize, mur, sig, ErrorTensors, VTK): #Find how the user wants the data saved FolderStructure = SaverSettings() if FolderStructure == "Default": #Create the file structure #Define constants for the folder name objname = Geometry[:-4] minF = Array[0] strminF = FtoS(minF) maxF = Array[-1] strmaxF = FtoS(maxF) stromega = FtoS(Omega) Points = len(Array) PODPoints = len(PODArray) strmur = DictionaryList(mur, False) strsig = DictionaryList(sig, True) strPODTol = FtoS(PODTol) #Find out the number of elements in the mesh Object = Geometry[:-4] + ".vol" #Loading the object file ngmesh = ngmeshing.Mesh(dim=3) ngmesh.Load("VolFiles/" + Object) #Creating the mesh and defining the element types mesh = Mesh("VolFiles/" + Object) #mesh.Curve(5)#This can be used to refine the mesh elements = mesh.ne #Define the main folder structure subfolder1 = "al_" + str(alpha) + "_mu_" + strmur + "_sig_" + strsig if Single == True: subfolder2 = "om_" + stromega + "_el_" + str( elements) + "_ord_" + str(Order) else: if Pod == True: subfolder2 = strminF + "-" + strmaxF + "_" + str( Points) + "_el_" + str(elements) + "_ord_" + str( Order) + "_POD_" + str(PODPoints) + "_" + strPODTol else: subfolder2 = strminF + "-" + strmaxF + "_" + str( Points) + "_el_" + str(elements) + "_ord_" + str(Order) sweepname = objname + "/" + subfolder1 + "/" + subfolder2 else: sweepname = FolderStructure if Single == True: subfolders = ["Data", "Input_files"] else: subfolders = ["Data", "Graphs", "Functions", "Input_files"] #Create the folders for folder in subfolders: try: os.makedirs("Results/" + sweepname + "/" + folder) except: pass #Create the folders for the VTK output if required if VTK == True and Single == True: try: os.makedirs("Results/vtk_output/" + objname + "/om_" + stromega) except: pass #Copy the .geo file to the folder copyfile( "GeoFiles/" + Geometry, "Results/vtk_output/" + objname + "/om_" + stromega + "/" + Geometry) #Copy the files required to be able to edit the graphs if Single != True: copyfile("Settings/PlotterSettings.py", "Results/" + sweepname + "/PlotterSettings.py") copyfile("Functions/Plotters.py", "Results/" + sweepname + "/Functions/Plotters.py") if Pod == True: if ErrorTensors == True: copyfile( "Functions/PlotEditorWithErrorBars.py", "Results/" + sweepname + "/PlotEditorWithErrorBars.py") if PlotPod == True: copyfile("Functions/PODPlotEditor.py", "Results/" + sweepname + "/PODPlotEditor.py") if ErrorTensors != False: copyfile( "Functions/PODPlotEditorWithErrorBars.py", "Results/" + sweepname + "/PODPlotEditorWithErrorBars.py") copyfile("Functions/PlotEditor.py", "Results/" + sweepname + "/PlotEditor.py") copyfile("GeoFiles/" + Geometry, "Results/" + sweepname + "/Input_files/" + Geometry) copyfile("Settings/Settings.py", "Results/" + sweepname + "/Input_files/Settings.py") copyfile("main.py", "Results/" + sweepname + "/Input_files/main.py") #Create a compressed version of the .vol file os.chdir('VolFiles') zipObj = ZipFile(objname + '.zip', 'w', ZIP_DEFLATED) zipObj.write(Object) zipObj.close() os.replace(objname + '.zip', '../Results/' + sweepname + '/Input_files/' + objname + '.zip') os.chdir('..') return
seed(4) g = CSG2d() outer = Rectangle((0, 0), (1, 1), "outer", "outer") inner = Solid2d() for i in range(30): cx = random() cy = random() r = 0.03 + 0.05 * random() print("Add Circle", i, cx, cy, r, flush=True) circle = Circle((cx, cy), r, "circle" + str(i), "circle" + str(i)) inner += circle outer -= circle g.Add(inner) g.Add(outer) geo = g.GenerateSplineGeometry() m = geo.GenerateMesh(maxh=0.1) try: from ngsolve import Draw, Mesh Draw(geo) mesh = Mesh(m) mesh.Curve(3) Draw(mesh) except: pass