def stl_import(fileName): # Imports an ASCII stl file coontaining ONE solid model. output = None # Holding variable for the output mesh object currentTris = [] # list of tris which have been created but not yet included into a solid. currentPoints = [] # list of points which have been created but not yet included in a tri # Support for arbitrary normals from file removed for now # currentNormal=None #Holding variable for one normal vector which has not yet been included in a tri. inMesh = None # Boolean flag to ensure currentTris isn't populated outside a mesh. inTri = False # Boolean flag to ensure currentPoints isn't populated outside a tri stl = open(fileName, "r") for line in stl: # Terminating a tri resets currentPoints, and stores the tri in currentTris lineList = line.split() if lineList[0] == "outer": continue # I don't understand why loops exist. if lineList[0] == "endloop": continue # I don't understand why loops exist. if lineList[0] == "endfacet": if not inTri: print "Error: endfacet found outside of tri." return currentTris.append(Basics.tri(currentPoints)) currentPoints = [] # Support for arbitrary normals from file removed for now # currentNormal=[] inTri = False continue # Initiating a new mesh if lineList[0] == "solid": if inMesh: print "Error: solid initiated inside another solid." return inMesh = True continue # Ending a mesh if lineList[0] == "endsolid": if not inMesh: print "Error: endsolid found outside of mesh." return inMesh = False output = mesh.mesh(currentTris) continue # Initiating a new triangle wipes all old points. if lineList[0] == "facet": if inTri: print "Error: facet initiated inside another facet." return inTri = True # Support for arbitrary normals from file removed for now # currentNormal=sp.array([[float(lineList[2]),float(lineList[3]),float(lineList[4])],[0,0,0]]) continue # Put vertices into currentPoints list if lineList[0] == "vertex": if len(currentPoints) > 2: print "Error, nontriangle facet in file." return currentPoints.append(sp.array([float(lineList[1]), float(lineList[2]), float(lineList[3])])) continue if output != None: return output else: print "Error: endsolid not found!" return
def test_laplacian_2d(self): sim = simulationManager() p = species() kpa = kpps_analysis() m = mesh() case = caseHandler(mesh=m, **self.case_params) sim.ndim = 2 z = m.pos[2, 0, 0, :] Lz = m.zlimits[1] y = m.pos[1, 0, :, 0] Ly = m.ylimits[1] phi = np.zeros((m.res[1:3] + 1), dtype=np.float) sol = np.zeros((m.res[1:3] + 1), dtype=np.float) for zi in range(0, m.res[2] + 1): for yi in range(0, m.res[1] + 1): phi[yi, zi] = z[zi] * (z[zi] - Lz) * y[yi] * (y[yi] - Ly) sol[yi, zi] = 2 * z[zi] * (z[zi] - Lz) + 2 * y[yi] * (y[yi] - Ly) phi = phi[np.newaxis, :, :] phi_E_vector = kpa.meshtoVector(phi) Ek = kpa.poisson_cube2nd_setup(p, m, sim).toarray() b = np.dot(Ek, phi_E_vector) b = kpa.vectortoMesh(b, phi.shape) assert np.allclose(b[0, 1:-1, 1:-1], sol[1:-1, 1:-1]) assert np.sum(b[0, 1:-1, 1:-1]) <= np.sum(sol[1:-1, 1:-1]) + 0.01 assert np.sum(b[0, 1:-1, 1:-1]) >= np.sum(sol[1:-1, 1:-1]) - 0.01 return b, phi, phi_E_vector, sol
def setup(self): species_params = {} pLoader_params = {} mLoader_params = {} sim_params = {} sim_params['xlimits'] = [-2, 2] sim_params['ylimits'] = [-2, 2] sim_params['zlimits'] = [-2, 2] self.sim = controller(**sim_params) species_params['nq'] = 8 species_params['mq'] = 1 species_params['q'] = 8 self.p = species(**species_params) pLoader_params['load_type'] = 'direct' pLoader_params['vel'] = np.zeros((8, 3), dtype=np.float) pLoader_params['pos'] = np.array([[1, 1, 1], [1, -1, 1], [1, -1, -1], [1, 1, -1], [-1, -1, -1], [-1, 1, -1], [-1, 1, 1], [-1, -1, 1]]) self.pLoader_params = pLoader_params self.pLoader = particleLoader(**pLoader_params) mLoader_params['load_type'] = 'box' mLoader_params['resolution'] = [2] mLoader_params['store_node_pos'] = True self.mLoader_params = mLoader_params self.mLoader = meshLoader(**mLoader_params) self.m = mesh() self.kpa = kpps_analysis()
def test_kpps(self): print("Running: " + self.analysis_params['particleIntegrator'] + " at dt = " + str(self.dt)) print("************************ Setup *******************************") sim = controller(**self.sim_params) analyser = kpps_analysis(**self.analysis_params) spec1 = species(**self.species_params[0]) species_list = [spec1] pLoader1 = pLoader(**self.pLoader_params[0]) mLoader = meshLoader(**self.mLoader_params) mesh1 = mesh() pLoader1.run(species_list,sim) mLoader.run(mesh1,sim) analyser.run_preAnalyser(species_list,mesh1,controller=sim) print("*************************** Run ******************************") for t in range(1,self.steps+1): self.print_step(species_list,t) sim.updateTime() analyser.run_fieldIntegrator(species_list,mesh1,sim) analyser.run_particleIntegrator(species_list,mesh1,sim) analyser.runHooks(species_list,mesh1,controller=sim) print("*************************** Done *****************************") return species_list, mesh1
def run(): spark = SparkSession\ .builder\ .appName("HeatFlow")\ .getOrCreate() #context.addPyFile("src/point.py") spark.sparkContext.addPyFile("src/point.py") spark.sparkContext("src/config.py") # pyspark context #context = pyspark.SparkContext('local[*]') #context.addPyFile("src/point.py") #context.addPyFile("src/config.py") my_mesh = mesh(constants.length_val, (int)(constants.length_val / stepping.space_delta)) data =[] for step in range(simulation.max_step_num): diff = my_mesh.step_mesh(stepping.time_delta, context) if (diff < simulation.expected_diff): print('Finished after ' + str(step) + ' steps') break data.append(my_mesh.data_return()) my_mesh.update_mesh() print(my_mesh) with open('Results.txt', 'w') as f: for item in data: f.write("%s\n" % item)
def main(argv): try: opts, args = getopt.getopt(argv, "i:o:s:h", ["help", "input=", "output=", "subject="]) except getopt.GetoptError as err: # print help information and exit: print(err) # will print something like "option -a not recognized" usage() sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit() elif opt in ("-i", "--input"): img = nib.load(arg) elif opt in ("-o", "--output"): outputFileName = arg elif opt in ("-s", "--subjectID"): subjectID = arg else: assert False, "unhandled option" [vert, elem] = mesh.mesh(img.get_data()) vert = dot(concatenate((vert, ones((vert.shape[0], 1))), 1), transpose(img.get_affine())) a = {} a['vert'] = vert a['subjectID'] = subjectID a['elem'] = elem try: savemat(outputFileName, a) except NameError: print "input or output is not defined correctly!"
def meshShift(self, m, u=1): ''' Returns mesh m with triShift applied to all its triangles. ''' newTris = [] for tri in m.tris: newTris.append(self.triShift(tri, u)) return mesh.mesh(newTris)
def __init__(self, gravity=True, units="MKS"): self.mesh = mesh.mesh() self.domain = domain.domain() self.forces = [] self.constraints = [] self.globalStiffnessMatrix = np.array([]) self.globalForceVector = [] self.globalDisplacementVector = []
def meshShift(self, m, u=1): """ Returns mesh m with triShift applied to all its triangles. """ newTris = [] for tri in m.tris: newTris.append(self.triShift(tri, u)) return mesh.mesh(newTris)
def load_mesh(self, mesh, file_name = ""): """load_mesh(file_name:string). Function to load a mesh from the file file_name. """ new_mesh = mesh_module.mesh() new_mesh.raw_mesh = ocaml.mesh_readfile(file_name) # read mesh print "read mesh: ok" return new_mesh
def tstTravelSurfOutsideMesh( tstFileName, phiFileName=None, tstDataIn=False, phiDataIn=None, borderSize=10, threshold="auto"): if tstDataIn: #don't want to read in if calling function already did it for us tstD = tstDataIn else: tstD = tstdata.tstData( tstFileName, necessaryKeys=tstdata.tstData.necessaryKeysForMesh) if phiDataIn is not None: phiData = phiDataIn else: phiData = phi(phiFileName) # read in the phimap if possible if 'CONVEX_HULL_TRI_POINT_LIST' not in tstD.dict.keys(): print "Run tstConvexHull.py on this tst data file first." sys.exit(1) #these sets are useful to construct convexHullPoints = set() for record in tstD.dict['CONVEX_HULL_TRI_POINT_LIST']: convexHullPoints.update(record[1:]) maxPhi = phiData.getMaxValues() if threshold == "auto" and maxPhi == 1.0: threshold = 0.6 if threshold == "auto" and maxPhi == 10.0: threshold = 6.0 gridD, mins, maxs = grid.makeTrimmedGridFromPhi( phiData, tstD.dict['POINT_XYZ'], convexHullPoints, threshold, -2, 0, borderSize) gridSize = 1.0/phiData.scale del phiData # no longer needed in this function, so delete this reference #do the biggest disjoint set of tris/points stuff allPoints, allTris, cavPoints, cavTris = cavity.assumeNoCavities( tstD.dict['POINT_XYZ'], tstD.dict['TRIANGLE_POINT'], tstD.dict['POINT_NEIGHBOR']) #here is where code is mesh-specific meshData = mesh.mesh( gridD, tstD.dict['POINT_XYZ'], tstD.dict['POINT_NEIGHBOR'], gridSize, 0, -2, "X") # no between meshData.calculateTravelDistance("surfout", [3], [0, 2]) #transform grid to actual travel distance maxTD = grid.finalizeGridTravelDist(gridD, gridSize) gridMaximaRanking = grid.getMaximaRanking(gridD) #output the grids and the gridmaxima.... phiDataOut = phi() phiDataOut.createFromGrid( gridMaximaRanking, gridSize, toplabel="travel depth maxima rank") phiDataOut.write(tstFileName + ".mesh.travel.out.max.rank.phi") phiDataOut = phi() phiDataOut.createFromGrid( gridD, gridSize, toplabel="travel depth surf-out", defaultValue=maxTD + 1.0) phiDataOut.write(tstFileName+".mesh.travel.out.phi")
def test_poisson_setup_fixed(self): p = species() m = mesh() sim_params = {} sim_params['xlimits'] = [-1, 1] sim_params['ylimits'] = [-1, 1] sim_params['zlimits'] = [-1, 1] sim = controller(**sim_params) mLoader_params = cp.copy(self.mLoader_params) mLoader_params['res'] = [4, 6, 8] mLoader = meshLoader(**mLoader_params) mLoader.run(m, sim) kpa = kpps_analysis() sim.ndim = 1 Dk = kpa.poisson_cube2nd_setup(p, m, sim) Dk = Dk.toarray() sim.ndim = 2 Ek = kpa.poisson_cube2nd_setup(p, m, sim) Ek = Ek.toarray() sim.ndim = 3 Fk = kpa.poisson_cube2nd_setup(p, m, sim) Fk = Fk.toarray() #Test all FDM matrices are the correct size assert np.all(Dk.shape == m.zres - 1) assert np.all(Ek.shape == (m.yres - 1) * (m.zres - 1)) assert np.all(Fk.shape == (m.yres - 1) * (m.zres - 1) * (m.xres - 1)) #Test 1D matrix values assert Dk[1, 0] == 1 / m.dz**2 assert Dk[1, 1] == -2 * (1 / m.dz**2) assert Dk[1, 2] == 1 / m.dz**2 #Test 2D matrix values assert Ek[1, 0] == 1 / m.dz**2 assert Ek[1, 1] == -2 * (1 / m.dy**2 + 1 / m.dz**2) assert Ek[1, 2] == 1 / m.dz**2 assert Ek[1, 1 + np.int(m.zres - 1)] == 1 / m.dy**2 #Test 3D matrix values assert Fk[1, 0] == 1 / m.dz**2 assert Fk[1, 1] == -2 * (1 / m.dx**2 + 1 / m.dy**2 + 1 / m.dz**2) assert Fk[1, 2] == 1 / m.dz**2 assert Fk[1, 1 + np.int(m.zres - 1)] == 1 / m.dy**2 assert Fk[1, 1 + np.int((m.zres - 1) * (m.yres - 1))] == 1 / m.dx**2 return Dk, Ek, Fk
def meshConstruct( tstD, phiData, tstFileName="temp.tst", borderSize=2, threshold="auto", cavities=False): '''returns a phi and a grid, modifies tstD in place.''' if 'CONVEX_HULL_TRI_POINT_LIST' not in tstD.dict.keys(): print "Run tstConvexHull.py on this tst data file first." sys.exit(1) #these sets are useful to construct convexHullPoints = set() for record in tstD.dict['CONVEX_HULL_TRI_POINT_LIST']: convexHullPoints.update(record[1:]) maxPhi = phiData.getMaxValues() if threshold == "auto" and maxPhi == 1.0: threshold = 0.6 if threshold == "auto" and maxPhi == 10.0: threshold = 6.0 gridD, mins, maxs = grid.makeTrimmedGridFromPhi( phiData, tstD.dict['POINT_XYZ'], convexHullPoints, threshold, -2.0, -1.0, borderSize) gridSize = 1.0 / phiData.scale del phiData # no longer needed in this function, so delete this reference #needs border = 2 so all surface points have a grid point on either side... #tstdebug.debugGridCountVals(gridD) #tstdebug.debugGridNoBlue(gridD, "debug.phigrid.py") #do the biggest disjoint set of tris/points stuff if not cavities: allPoints, allTris, cavPoints, cavTris = cavity.assumeNoCavities( tstD.dict['POINT_XYZ'], tstD.dict['TRIANGLE_POINT'], tstD.dict['POINT_NEIGHBOR']) cavPointLists = False else: allPoints, allCavPoints, cavPointLists = \ cavity.findBiggestDisjointSetsBreakCavities( tstD.dict['POINT_XYZ'], tstD.dict['TRIANGLE_POINT'], tstD.dict['POINT_NEIGHBOR']) convexTriTuples = geometry.cacheTriangle( tstD.dict['CONVEX_HULL_TRI_POINT_LIST'], tstD.dict['POINT_XYZ']) #this marks the editable volume between the two surfaces orstHelper.decideInside( gridD, convexTriTuples, convexHullPoints, tstD.dict['CONVEX_HULL_POINT_TRI_LIST'], tstD.dict['POINT_XYZ'], tstD.dict['CONVEX_HULL_TRI_POINT_LIST'], 0, -1, 2) #0 inside convex hull, -1 outside (only valid to change), 2 = max tris #grid encoding -1 = outside ch, 0 = between ch, ms, -2 = inside ms #tstdebug.debugGridNoBlue(gridD, "debug.phigrid.py") meshData = mesh.mesh( gridD, tstD.dict['POINT_XYZ'], tstD.dict['POINT_NEIGHBOR'], gridSize, -1, -2, 0, allPoints, cavPointLists) #now mesh is initialized return meshData, gridD
def laplaceEF(meshname): G=mesh() G.lecture(meshname) G.info() # assemblage print "Resolution Laplacien EF " F=ones(G.nn) A=Assemblage(G) B=Smb(G,F) # conditions limites for i in range(G.nn): if G.Frt[i]==1: A[i,:]=0.; A[:,i]=0.; A[i,i]=1.0; B[i]=0.0 return A,B,G
def laplaceEF(meshname): G = mesh() G.lecture(meshname) G.info() # assemblage print "Resolution Laplacien EF " F = ones(G.nn) A = Assemblage(G) B = Smb(G, F) # conditions limites for i in range(G.nn): if G.Frt[i] == 1: A[i, :] = 0. A[:, i] = 0. A[i, i] = 1.0 B[i] = 0.0 return A, B, G
def restart(self, folder, sim_name, tstep, **kwargs): self.tStart = time.time() ## Load required modules sim_file = io.open(folder + sim_name + "/sim", mode='rb') sim = pk.load(sim_file) sim_file.close() print("Restarting ' " + sim_name + " ' at time " + str(tstep * sim.dt) + "s...") sim.ts = tstep sim.restarted = True p = species_class() fields = mesh(**sim.meshSettings) mLoader = meshLoader(**sim.mLoaderSettings) mLoader.run(fields, sim) species_list = [p] analyser = kpps_analysis(simulationManager=sim, **sim.analysisSettings) analyser.run_preAnalyser(species_list, fields, controller=sim) species_list = [] speciesSettings = sim.speciesSettings for setting in speciesSettings: spec_file = io.open(folder + sim_name + "/p_" + setting['name'] + "_t" + str(tstep), mode='rb') species = pk.load(spec_file) species_list.append(species) spec_file.close() mesh_file = io.open(folder + sim_name + "/m" + "_t" + str(tstep), mode='rb') fields = pk.load(mesh_file) mesh_file.close() dHandler = dataHandler(controller_obj=sim, **sim.dataSettings) dHandler.run_setup(sim) ########################## RUN TIME! ################################## dHandler = self.run(species_list, fields, sim, analyser, dHandler) return dHandler
def test_laplacian_3d(self): sim = simulationManager() p = species() kpa = kpps_analysis() m = mesh() case = caseHandler(mesh=m, **self.case_params) sim.ndim = 3 z = m.pos[2, 0, 0, :] Lz = m.zlimits[1] y = m.pos[1, 0, :, 0] Ly = m.ylimits[1] x = m.pos[0, :, 0, 0] Lx = m.xlimits[1] phi = np.zeros((m.res[0:3] + 1), dtype=np.float) sol = np.zeros((m.res[0:3] + 1), dtype=np.float) b = np.zeros((m.res[0:3] + 1), dtype=np.float) for zi in range(0, m.res[2] + 1): for yi in range(0, m.res[1] + 1): for xi in range(0, m.res[0] + 1): phi[xi, yi, zi] = (z[zi] * (z[zi] - Lz) * y[yi] * (y[yi] - Ly) * x[xi] * (x[xi] - Lx)) sol[xi, yi, zi] = (2 * z[zi] * (z[zi] - Lz) * y[yi] * (y[yi] - Ly) + 2 * y[yi] * (y[yi] - Ly) * x[xi] * (x[xi] - Lx) + 2 * x[xi] * (x[xi] - Lx) * z[zi] * (z[zi] - Lz)) phi_F_vector = kpa.meshtoVector(phi[1:-1, 1:-1, 1:-1]) Fk = kpa.poisson_cube2nd_setup(p, m, sim).toarray() b_vector = np.dot(Fk, phi_F_vector) b[1:-1, 1:-1, 1:-1] = kpa.vectortoMesh(b_vector, phi[1:-1, 1:-1, 1:-1].shape) assert np.allclose(b[1:-1, 1:-1, 1:-1], sol[1:-1, 1:-1, 1:-1]) assert np.sum(b[1:-1, 1:-1, 1:-1]) <= np.sum(sol[1:-1, 1:-1, 1:-1]) + 0.01 assert np.sum(b[1:-1, 1:-1, 1:-1]) >= np.sum(sol[1:-1, 1:-1, 1:-1]) - 0.01 return b, phi, phi_F_vector, sol
def test_laplacian_1d(self): sim = simulationManager() p = species() kpa = kpps_analysis() m = mesh() case = caseHandler(mesh=m, **self.case_params) sim.ndim = 1 z = m.pos[2, 0, 0, :] Lz = m.zlimits[1] phi = z * (z - Lz) phi = phi[np.newaxis, np.newaxis, :] phi_D_vector = kpa.meshtoVector(phi) Dk = kpa.poisson_cube2nd_setup(p, m, sim).toarray() b = np.dot(Dk, phi_D_vector) bSum = (m.res[2] - 1) * 2 assert np.allclose(b[1:-1], np.ones(m.res[2] - 1) * 2) assert bSum - 0.001 <= np.sum(b[1:-1]) <= bSum + 0.001 return b, phi
def test_external_E(self): spec = species() field = mesh() kpa = kpps_analysis() spec.pos = np.array([[10, 0, 0]]) spec.a = 1 spec.nq = spec.pos.shape[0] omegaB = 25 omegaE = 4.9 epsilon = -1 kpa.E_type = 'transform' kpa.E_transform = np.array([[1, 0, 0], [0, 1, 0], [0, 0, -2]]) kpa.E_magnitude = -epsilon * omegaE**2 / spec.a kpa.B_type = 'uniform' kpa.B_transform = np.array([0, 0, 1]) kpa.B_magnitude = omegaB / spec.a spec = kpa.eFieldImposed(spec, field) assert spec.E.shape == (1, 3) assert math.isclose(spec.E[0, 0], 240.1)
blank = False slim = False basic = False POPULATION_SIZE = 70 #create set of nodes, and test infrastructure world = [] city = aj.infrastructure(800, 500) city.buildBasicCity() for i in range(POPULATION_SIZE): world.append(aj.node(None, None, city)) world.append(aj.node(city.width-10, city.height-10, city)) #create mesh network network = mesh.mesh(world, city) gui.buildButtonPanel(city) gui.drawMesh(network) def refresh(full=True): global world global dijkstras global batman global fullMesh global network if(full): world = [] print(POPULATION_SIZE) for i in range(POPULATION_SIZE): world.append(aj.node(None, None, city)) world.append(aj.node(city.width-10, city.height-10, city))
Me=MatMasse(G,k) ni=G.Tbc[k,:] Fe=F[ix_(ni)] B[ix_(ni)] += dot(Me,Fe) return B # tracer champ Z sur maillage def isosurf(G,Z,titre): """ trace isosurface de Z sur le maillage G""" triang=tri.Triangulation(G.X[:,0],G.X[:,1],triangles=G.Tbc) plt.tricontourf(triang, Z) plt.colorbar() plt.title(titre) return # G=mesh() G.lecture("ellipse.msh") G.info() # assemblage print "Resolution Laplacien maillage grossier" F=ones(G.nn) A=Assemblage(G) B=Smb(G,F) # conditions limites for i in range(G.nn): if G.Frt[i]==1: A[i,:]=0.; A[:,i]=0.; A[i,i]=1.0; B[i]=0.0 # resolution U=linalg.solve(A,B) print "solution min/max=",amin(U),amax(U)
import randomStack as rng import mesh as mes import numpy as np from scipy.spatial import Delaunay import matplotlib.pyplot as plt import Triangulate as tri_tim posdist = rng.randomStack(1000,'boxdist.txt') veldist = rng.randomStack(1000,'boxdist2.txt') refdist = rng.randomStack(1000,'reflectdist.txt') test_tri = tri_tim.Triangulate("test2") test_tri.add_hole(test_tri.POLYGON, .5, .5, 10, .1) # Adds a 10 sides hole centered at x=0.5, y=0.5, with a radius of .1 test_tri.add_hole(test_tri.RECTANGLE, .2, .2, .1, .15) # Adds a rectangular hole centered at x=0.2, y=0.2, and width=0.1, height=0.15 test_tri.Delaunay("-q34") p = test_tri.get_points() print p s = test_tri.get_indices() print len(s) testmesh = mes.mesh(xrange = [0,1],yrange = [0,1],pointsArray = p,simplices = s,initPosDist = [posdist,posdist],initVelDist = [veldist,veldist],initParticles=3) testmesh.runSim(simduration = 8, dt = 0.01, inputPosDist= [posdist,posdist],inputVelDist=[veldist,veldist],reflectDist = [refdist,refdist],p_scatter = 0.003,decayConst = 1.8)
N = 101 # Airfoil number of points M = 50 # 20 c = 1. # Chord [m] m = 2. # Is the maximum camber (100 m is the first of the four digits), p = 5. # Is the location of maximum camber (10 p is the second digit in the NACA xxxx description). t = 12. # Is the maximum thickness as a fraction of the chord # (so t gives the last two digits in the NACA 4-digit denomination divided by 100) ######################################################################################################### ######################################################################################################### ######################################################################################################### af.airfoil(c, N, m, p, t) cordxy = np.loadtxt('perfilCoordenadas.txt', float) [X, Y] = mh.mesh(1., M, cordxy) ########################### Plot mesh & airfoil ############################### plt.plot(X, Y, "b", X.T, Y.T, "g") plt.title('Airfoil NACA %d%d%d' % (m, p, t)) plt.xlabel('x') plt.ylabel('y') plt.grid() plt.axis("equal") ##################### Coordinates, Mesh & Boundary ############################ X = X[:-1, :] # remove the last element from the column X = X.T.ravel() # Convert an array in a column Y = Y[:-1, :] Y = Y.T.ravel()
import os # Parse options parser = argparse.ArgumentParser() parser.add_argument('label', type=str, help='label used when saving pictures') parser.add_argument('-s', '--step', type=int, default=1, help='step for iterations') parser.add_argument('--input', type=str, default="output", help='directory of data files') parser.add_argument('--output', type=str, default="pictures", help='directory for figure files') args = parser.parse_args() # Extract boundary of domain initial_mesh = mesh.mesh(args.input + '/mesh.msh') edges = initial_mesh.get_matplotlib_triangulation_edges() initial_triangulation, nil = initial_mesh.export_matplotlib_triangulation() # Calculate limits size of domain x = initial_triangulation.x y = initial_triangulation.y dx = max(x) - min(x) dy = max(y) - min(y) padding = 0.1 * min(dx, dy) xlim = (min(x) - padding, max(x) + padding) ylim = (min(y) - padding, max(y) + padding) c_orientation = "vertical" if (dy > dx) else "horizontal" # Set canvas and font sizes inch_size = 20
def plot_iteration(iteration): print("Generating plots for iteration " + str(iteration) + ".") # Load mesh if needed if adaptation: file_mesh = args.input + '/mesh/mesh-' + str(iteration) + '.msh' tri_data, tri_mesh = \ mesh.mesh(file_mesh).export_matplotlib_triangulation() else: tri_data = triangulation_data tri_mesh = triangulation_mesh # Load data files data = {} for f in fields: data[f] = mesh.read_data(args.input + '/' + f + '/' + f + '-' + str(iteration) + '.msh') # Set figure size and padding plt.figure(figsize=(inch_size, inch_size)) plt.xlim(xlim) plt.ylim(ylim) # Edges for entity in edges: vertices_x = [v[0] for v in entity] vertices_y = [v[1] for v in entity] plt.plot(vertices_x, vertices_y, 'gray') plt.axis('scaled') plt.axis('off') # Mesh if args.mesh: plt.triplot(tri_mesh, lw=0.5, color='gray') # Interface plt.tricontour(tri_data, data['phi'], levels=[0], colors='k') for f in fields: if f == 'phi': tricontourf = plt.tricontourf(tri_data, data[f], levels=np.linspace(-1.1, 1.1, 40), cmap='jet') elif f == 'mu': tricontourf = plt.tricontourf(tri_data, data[f], 40, cmap='jet') # tri_data, data[f], levels=np.linspace(-4, 2.5, 80), cmap='jet') # tri_data, data[f], levels=np.linspace(0, 8, 80), cmap='jet') elif f == 'pressure': tricontourf = plt.tricontourf(tri_data, data[f], 40, cmap='jet') elif f == 'velocity': vx = [data[f][i][0] for i in range(len(data[f]))] vy = [data[f][i][1] for i in range(len(data[f]))] abs_v = [ np.sqrt(vx[i] * vx[i] + vy[i] * vy[i]) for i in range(len(data[f])) ] tricontourf = plt.tricontourf(tri_data, abs_v, 40) if not args.nocolorbar: if f == 'phi': colorbar = plt.colorbar(tricontourf, orientation=c_orientation, fraction=c_fraction, pad=0.01) # fraction=c_fraction, pad=0.01, ticks=[-1, -.5, 0, .5, 1]) elif f == 'mu': colorbar = plt.colorbar(tricontourf, orientation=c_orientation, fraction=c_fraction, pad=0.01) # fraction=c_fraction, pad=0.01, ticks=[-4, -3, -2, -1, 0, 1, 2]) # fraction=c_fraction, pad=0.01, ticks=list(range(9))) else: colorbar = plt.colorbar(tricontourf, orientation=c_orientation, fraction=c_fraction, pad=0.01) for c in tricontourf.collections: c.set_edgecolor("face") # Fix for white lines between levels if f == 'Velocity': plt.quiver(x, y, vx, vy) if not args.notitle: # plt.title(titles[f], y=1.02) plt.title("Iteration: {}, time: {:.2f}".format( iteration, time[iteration]), y=1.02) output = args.output + '/' + f + '/' + args.label + '-' + f + '-' + \ '%06d' % (iteration) + '.' + args.extension plt.xticks([]) plt.yticks([]) plt.tight_layout() plt.savefig(output, bbox_inches='tight') for c in tricontourf.collections: c.remove() if not args.nocolorbar: colorbar.remove() plt.close()
dy[-1] = 0.0 # Create the differential eqn's coefficients f0 = 0.0 c0 = 1.0 a110 = 0.5 * (vol1**2.0) a220 = 0.5 * (vol2**2.0) a120 = pcorr * vol1 * vol2 b10 = rate b20 = rate G = -1.0 * rate # Call Fortran Mesh routine # NOTA BENE: The connectivity matirx NODF has indices # according to the FORTRAN CONVENTION! nodf, glxy = tri.mesh(nx, ny, nex1, ney1, nem, nnm, dx, dy, x0, y0) # Switch NODF indices for the Python convention fort2py = ones(shape(nodf), dtype=int) nodp = nodf - fort2py # Find IdaigF and Idiag where they are the Fortran and Python # index of the diagonal for the non-symmetric stiffness matrix # respectively -> RECALL: Python starts indexing at 0! IdiagF = 0 for i in range(nem): for j in range(npe): for k in range(npe): nw = (int(abs(nodf[i, j] - nodf[i, k]) + 1)) * ndf if IdiagF < nw: IdiagF = nw
f = open(path + '%s.mcfunction' % filename, 'w+', encoding='utf-8') counter = 0 counter_ = 1 for command in commands: if counter > 65535: f.close() f = open(path + '%s_%s.mcfunction' % (filename, counter_), 'w+', encoding='utf-8') counter_ += 1 counter = 0 print('\nLoop Finished.') f.write(command + '\n') counter += 1 print('\rLoop%s' % counter, end='') f.close() print('\nSave Completed.') if __name__ == '__main__': i = input('(1.Img)(2.Mesh):') if i == '1': f = input('Img File:') c = img.main(f) save(input('Save File:'), c) elif i == '2': f = input('Obj File:') p, f = mesh.readData(f) c = _make_commands(_union_points(mesh.mesh(p, f)), 'concrete') save(input('Save File:'), c)
#!/usr/bin/env python3 import os import mesh import codecad chord = 200 span = 80 wall = 1 spacing = 20 rod_size = 2 path = os.path.join(os.path.dirname(__file__), "s1210-il.dat") airfoil = codecad.shapes.airfoils.load_selig(path).scaled(chord) base = airfoil.extruded(span, symmetrical=False) inside = mesh.mesh(spacing, rod_size, -1) & base skin = airfoil.shell(wall).extruded(span, symmetrical=False) endcap = airfoil.extruded(wall, symmetrical=False) o = (inside + skin + endcap).rotated_x(90) if __name__ == "__main__": codecad.commandline_render(o)
def stl_import(fileName): #Imports an ASCII stl file containing ONE solid model. output = None #Holding variable for the output mesh object currentTris = [ ] #list of tris which have been created but not yet included into a solid. currentPoints = [ ] #list of points which have been created but not yet included in a tri #Support for arbitrary normals from file removed for now # currentNormal=None #Holding variable for one normal vector which has not yet been included in a tri. inMesh = None #Boolean flag to ensure currentTris isn't populated outside a mesh. inTri = False #Boolean flag to ensure currentPoints isn't populated outside a tri stl = open(fileName, 'r') for line in stl: #Terminating a tri resets currentPoints, and stores the tri in currentTris lineList = line.split() if lineList[0] == 'outer': continue #I don't understand why loops exist. if lineList[0] == 'endloop': continue #I don't understand why loops exist. if lineList[0] == 'endfacet': if not inTri: print "Error: endfacet found outside of tri." return currentTris.append(Basics.tri(currentPoints)) currentPoints = [] #Support for arbitrary normals from file removed for now # currentNormal=[] inTri = False continue #Initiating a new mesh if lineList[0] == 'solid': if inMesh: print "Error: solid initiated inside another solid." return inMesh = True continue #Ending a mesh if lineList[0] == 'endsolid': if not inMesh: print "Error: endsolid found outside of mesh." return inMesh = False output = mesh.mesh(currentTris) continue #Initiating a new triangle wipes all old points. if lineList[0] == 'facet': if inTri: print "Error: facet initiated inside another facet." return inTri = True #Support for arbitrary normals from file removed for now # currentNormal=sp.array([[float(lineList[2]),float(lineList[3]),float(lineList[4])],[0,0,0]]) continue #Put vertices into currentPoints list if lineList[0] == 'vertex': if len(currentPoints) > 2: print "Error, nontriangle facet in file." return currentPoints.append( sp.array([ float(lineList[1]), float(lineList[2]), float(lineList[3]) ])) continue if output != None: return output else: print "Error: endsolid not found!" return
''' Run calibration for other (non-demonstration) purposes ONLY ''' # cb.run_calibrate() ''' Set configurations for each individual modelview settings: (followed by default) 1. grab, decode thresh, scan directory, smooth round Remeber to toggle UNDISTORTED to false if using distorted scans ''' GRAB = 0 SCANDIR = "../scans_undistort/teapot/grab_%d_u/" % GRAB UNDISTORTED = True THRESH = 0.015 ''' 2. Bound box limit for meshing part 1 ''' x_up_limit = 250 #250 x_low_limit = 0 #-250 y_up_limit = 0 #250 y_low_limit = -270 #-250 z_up_limit = 400 #600 z_low_limit = 200 #0 XRANGE = [ x_up_limit, x_low_limit, y_up_limit, y_low_limit, z_up_limit, z_low_limit ] ''' 3. Triangle max edge limit for part 2 ''' TRITHRESH = 15 #10 ''' 4. NBR smoothing round (in MATLAB) ''' NBR_PASS = 3 ''' Run meshing function ''' ms.mesh(GRAB, SCANDIR, UNDISTORTED, THRESH, XRANGE, TRITHRESH, NBR_PASS)
def tstTravelSurfInsideMesh(tstFileName, phiFileName, threshold="auto"): '''calculates the burial depth''' print "reading in tst and phi files" tstD = tstdata.tstData( tstFileName, necessaryKeys=tstdata.tstData.necessaryKeysForMesh + ['PDB_RECORD']) phiData = phi(phiFileName) # read in the phimap if possible if 'CONVEX_HULL_TRI_POINT_LIST' not in tstD.dict.keys(): print "Run tstConvexHull.py on this tst data file first." sys.exit(1) #these sets are useful to construct convexHullPoints = set() for record in tstD.dict['CONVEX_HULL_TRI_POINT_LIST']: convexHullPoints.update(record[1:]) maxPhi = phiData.getMaxValues() if threshold == "auto" and maxPhi == 1.0: threshold = 0.6 if threshold == "auto" and maxPhi == 10.0: threshold = 6.0 gridD, mins, maxs = grid.makeTrimmedGridFromPhi( phiData, tstD.dict['POINT_XYZ'], convexHullPoints, threshold, 0, -2, 2) gridSize = 1.0 / phiData.scale del phiData # no longer needed in this function, so delete this reference #do the biggest disjoint set of tris/points stuff allPoints, allTris, cavPoints, cavTris = cavity.assumeNoCavities( tstD.dict['POINT_XYZ'], tstD.dict['TRIANGLE_POINT'], tstD.dict['POINT_NEIGHBOR']) #here is where code is mesh-specific print "setting up mesh data structure" meshData = mesh.mesh( gridD, tstD.dict['POINT_XYZ'], tstD.dict['POINT_NEIGHBOR'], gridSize, -2, 0, "X") # no between print "calculating burial depth" meshData.calculateTravelDistance("travelin", [3], [1]) gridTravelInDepth = meshData.getGridTravelDistance(gridD, "travelin") #tstdebug.debugGridCountVals(gridTravelInDepth) print "writing phi file output" phiDataOut = phi() phiDataOut.createFromGrid( gridTravelInDepth, gridSize, toplabel="travel depth surf-in") phiDataOut.write(tstFileName+".mesh.travel.in.phi") print "writing pdb file output" pdbD = pdb.pdbData() for line in tstD.dict['PDB_RECORD']: pdbD.processLine(line) atomTravelInDepths = grid.assignAtomDepths( gridTravelInDepth, gridSize, mins, maxs, pdbD) #make a pdb file with the bfactor replaced for index, atomTID in enumerate(atomTravelInDepths): pdbD.updateFactors(index, (pdbD.factors[index][0], atomTID)) pdbD.write(tstFileName+".mesh.travelin.pdb") #also add record to tstD atomTIDRecord = [] for index, atomTID in enumerate(atomTravelInDepths): atomTIDRecord.append([index + 1, atomTID]) print "updating tst file" tstD.dict['ATOM_TRAVEL_IN'] = atomTIDRecord #write data into tst file tstFile = open(tstFileName, 'a') tstFile.write("ATOM_TRAVEL_IN\n") for line in tstD.dict['ATOM_TRAVEL_IN']: lineOut = "%8d" % line[0] for count in xrange(1, len(line)): lineOut += "%+9.4f " % line[count] noPlusLine = string.replace(lineOut, "+", " ") tstFile.write(noPlusLine) tstFile.write("\n") tstFile.write("END ATOM_TRAVEL_IN\n") tstFile.close() print "burial depth done"
import randomStack as rng import mesh as mes posdist = rng.randomStack(1000,'boxdist.txt') veldist = rng.randomStack(1000,'boxdist2.txt') refdist = rng.randomStack(1000,'reflectdist.txt') testmesh = mes.mesh(xrange = [0,1.1],yrange = [0,1.1],initPosDist = [posdist,posdist],initVelDist = [veldist,veldist], initParticles=3) testmesh.runSim(simduration = 8, dt = 0.01, inputPosDist= [posdist,posdist],inputVelDist=[veldist,veldist],reflectDist = [refdist,refdist],p_scatter = 0.003,decayConst = 1.8)
B[ix_(ni)] += dot(Me, Fe) return B # tracer champ Z sur maillage def isosurf(G, Z, titre): """ trace isosurface de Z sur le maillage G""" triang = tri.Triangulation(G.X[:, 0], G.X[:, 1], triangles=G.Tbc) plt.tricontourf(triang, Z) plt.colorbar() plt.title(titre) return # G = mesh() G.lecture("ellipse.msh") G.info() # assemblage print "Resolution Laplacien maillage grossier" F = ones(G.nn) A = Assemblage(G) B = Smb(G, F) # conditions limites for i in range(G.nn): if G.Frt[i] == 1: A[i, :] = 0. A[:, i] = 0. A[i, i] = 1.0 B[i] = 0.0 # resolution
def start(self, **kwargs): self.tStart = time.time() ## Read input settings self.simSettings = {} self.speciesSettings = [] self.pLoaderSettings = [] self.meshSettings = {} self.mLoaderSettings = {} self.analysisSettings = {} self.dataSettings = {} if 'simSettings' in kwargs: simSettings = kwargs['simSettings'] simSettings['simSettings'] = cp.copy(simSettings) if 'speciesSettings' in kwargs: speciesSettings = kwargs['speciesSettings'] simSettings['speciesSettings'] = speciesSettings if 'meshSettings' in kwargs: meshSettings = kwargs['meshSettings'] simSettings['meshSettings'] = meshSettings if 'pLoaderSettings' in kwargs: pLoaderSettings = kwargs['pLoaderSettings'] simSettings['pLoaderSettings'] = pLoaderSettings if 'mLoaderSettings' in kwargs: mLoaderSettings = kwargs['mLoaderSettings'] simSettings['mLoaderSettings'] = mLoaderSettings if 'analysisSettings' in kwargs: analysisSettings = kwargs['analysisSettings'] simSettings['analysisSettings'] = analysisSettings if 'dataSettings' in kwargs: dataSettings = kwargs['dataSettings'] simSettings['dataSettings'] = dataSettings ## Load required modules sim = controller(**simSettings) sim.inputPrint() print("Setting up...") t_setup = time.time() species_list = [] for setting in speciesSettings: species = species_class(**setting) species_list.append(species) pLoader_list = [] for setting in pLoaderSettings: pLoader = pLoader_class(**setting) pLoader_list.append(pLoader) fields = mesh(**meshSettings) mLoader = meshLoader(**mLoaderSettings) analyser = kpps_analysis(simulationManager=sim, **analysisSettings) dHandler = dataHandler(controller_obj=sim, **dataSettings) t_ploader = time.time() for loader in pLoader_list: loader.run(species_list, sim) t_mloader = time.time() mLoader.run(fields, sim) t_pre = time.time() analyser.run_preAnalyser(species_list, fields, sim) t_Start = time.time() sim.runTimeDict['object_instantiation'] = t_ploader - t_setup sim.runTimeDict['particle_load'] = t_mloader - t_ploader sim.runTimeDict['mesh_load'] = t_pre - t_mloader sim.runTimeDict['pre_processing'] = t_Start - t_pre dHandler.run_setup(sim) dHandler.run(species_list, fields, sim) ########################## RUN TIME! ################################## sim.runTimeDict['setup'] = time.time() - self.tStart dHandler = self.run(species_list, fields, sim, analyser, dHandler) return dHandler
###----------extra convergence params----------------------- 'checkOutputIntegrity' : False, # if true, check the radex output (sometimes although it converges, the numbers do not make sense) 'popDensSumExpected' : 1.0, 'popDensSumTol' : 1e-2, #'popDensSumTol' : 10, 'changeFracTrial' : 0.001, 'nMaxTrial' : 100, }, } ##############################################setting up and reading the data############################################################### # reading the archive arxv = meshUtils.meshArxv(readDb = True, **parms) #setting up a mesh object for temporary use (utility stuff) pdrMeshObj = mesh.mesh(chemNet = arxv.chemNet, metallicity = arxv.metallicity) # setting the x,y,z quantities to be used for ploting arxv.set_grid_axes_quantity_values(relativeGmech = parms['relativeGmech']) #reading all the available precomputed radex databases ###arxv.readDbsRadex(species = ['CO']) ############################extracting what we want and plotting#################################### ###arxv.use_radexDb('CO') #%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% def get_intensities_and_ratios(pdrMeshObj): #get the intensities from a model flux = collections.OrderedDict()