def tovtk(self, N, filename): """Dump probes to VTK file.""" is_root = comm.Get_rank() == 0 z = self.array(N=N) if is_root: d = self.dims d = (d[0], d[1], d[2]) if len(d) > 2 else (d[0], d[1], 1) grid = pyvtk.StructuredGrid(d, self.create_dense_grid()) v = pyvtk.VtkData(grid, "Probe data. Evaluations = {}".format(self.probes.number_of_evaluations())) if self.probes.value_size() == 1: v.point_data.append(pyvtk.Scalars(z, name="Scalar", lookup_table='default')) elif self.probes.value_size() == 3: v.point_data.append(pyvtk.Vectors(z, name="Vector")) elif self.probes.value_size() == 9: # StatisticsProbes if N == 0: num_evals = self.probes.number_of_evaluations() v.point_data.append(pyvtk.Vectors(z[:, :3]/num_evals, name="UMEAN")) rs = ["uu", "vv", "ww", "uv", "uw", "vw"] for i in range(3, 9): v.point_data.append(pyvtk.Scalars(z[:, i]/num_evals, name=rs[i-3], lookup_table='default')) else: # Just dump latest snapshot v.point_data.append(pyvtk.Vectors(z[:, :3], name="U")) else: raise TypeError("Only vector or scalar data supported for VTK") v.tofile(filename)
def omf2vtk(input_omf_file, output_vtk_file, output_format='ascii' ): """ Convert a given input_omf_file into a VTK file in ascii or binary format Magnetisation (direction and magnitude) values are stored as cell values """ data = MagnetisationData(input_omf_file) data.generate_field() data.generate_coordinates() grid = (np.linspace(data.xmin * 1e9, data.xmax * 1e9, data.nx + 1), np.linspace(data.ymin * 1e9, data.ymax * 1e9, data.ny + 1), np.linspace(data.zmin * 1e9, data.zmax * 1e9, data.nz + 1)) structure = pyvtk.RectilinearGrid(* grid) vtk_data = pyvtk.VtkData(structure, "") # Save the magnetisation vtk_data.cell_data.append(pyvtk.Vectors(np.column_stack((data.field_x, data.field_y, data.field_z)), "m")) # Save Ms as scalar field vtk_data.cell_data.append(pyvtk.Scalars(data.field_norm, "Ms")) # Save to VTK file with specified output filename vtk_data.tofile(output_vtk_file, output_format)
def _vtk_addPointdata(vtk, data, name): """vtk is a vtk object (from pyvtk) to which the data will be appended. data is a list of lists. The inner lists contain the data, the outer lists the sites. Example: data = [[0.1],[0.2],[0.3],....] is scalar data data = [[0.1,1],[0.2,0.5],[0.3,0.4],....] is 2d vector data name is the name of the data (used in vtk file to label the field)""" log.debug("Adding dof %s to vtk object" % name) if type(data[0]) in [types.FloatType, types.IntType]: #raw data in scalar data set, convert float a into [a]: data = map(lambda a: [a], data) #print "In vtk_addPointdata. What is the structure of data?" #from IPython.Shell import IPShellEmbed #ipshell = IPShellEmbed() #ipshell() if len(data[0]) == 1: vtk.point_data.append( pyvtk.Scalars(data, name=name, lookup_table='default')) elif len(data[0]) in [2, 3]: if len(data[0]) == 2: #make 3d data = map(lambda a: a + [0.], data) vtk.point_data.append(pyvtk.Vectors(data, name=name)) else: raise NfemValueError, "Can only deal with scalar or vector data" return vtk
def dump_vtk_grid(self, path: str): self.set_sigma() point_coords = np.zeros([self.n_nodes, 3]) point_coords += self.a.reshape([self.n_nodes, 3]) point_coords[:, 0] += self.x_0 point_coords[:, 1] += self.y_0 point_velocities = self.a_t.reshape([self.n_nodes, 3]) pd = pvtk.PointData(pvtk.Vectors(point_velocities, name='Velocity')) pd.append(pvtk.Scalars(point_coords[:, 2], name='z')) triangles = [] sigmas = [] for elem in self.elements: triangles.append(list(elem.node_ind)) sigmas.append(elem.sigma) cd = [] names = [ 'sigma_xx', 'sigma_yy', 'sigma_zz', 'tau_xy', 'tau_yz', 'tau_xz' ] sigmas = np.array(sigmas) for i in range(6): cd.append(pvtk.Scalars(sigmas[:, i], name=names[i])) usg = pvtk.UnstructuredGrid(point_coords, triangle=triangles) vtk = pvtk.VtkData(usg, pd) for e in cd: vtk.cell_data.append(e) vtk.tofile(path, 'binary')
def exportVtk(self, filename): """Export results to VTK""" print("Exporting results to %s." % filename) # --- Skapa punkter och polygon definitioner från vårt nät points = self.outputData.coords.tolist() # --- Tänk på att topologin i VTK är 0-baserad varför vi måste minskar **edof** med 1. #polygons = (self.outputData.edof-1).tolist() # --- För spänningsproblemet användas, se också nästa stycke: polygons = (self.outputData.topo - 1).tolist() # --- Resultat från beräkningen skapas i separata objekt. Punkter i vtk.PointData och # --- elementdata i vtk.CellData. Nedan anger vi både vektor data och skalärvärden för elementen. # --- Tänk på att vektorerna måste ha 3 komponenter, så lägg till detta i beräkningsdelen. #pointData = vtk.PointData(vtk.Scalars(self.outputData.a.tolist(), name="Nodal Properties")) #ellData = vtk.CellData(vtk.Scalars(self.outputData.vonMises, name="Von Mises"), vtk.Vectors(self.outputData.flow, "flow")) # --- För spänningsproblemet blir det istället (ingen pointData) #HÄR BLIR DET KNAS# cellData = vtk.CellData( vtk.Scalars(self.outputData.vonMises, name="mises"), vtk.Vectors(self.outputData.stresses1, "principal stress 1"), vtk.Vectors(self.outputData.stresses2, "principal stress 2")) # --- Skapa strukturen för elementnätet. structure = vtk.PolyData(points=points, polygons=polygons) # --- Lagra allting i en vtk.VtkData instans # vtkData = vtk.VtkData(structure, pointData, cellData) # --- För spänningsfallet vtkData = vtk.VtkData(structure, cellData) # --- Spara allt till filen vtkData.tofile(filename, "ascii")
def test_vtk_writer_speed(): """ Comparison of C backend with the old pyvtk interface For this we use a 200 x 200 x 1 mesh and convert the OMF file into a VTK file using both the C library and the PyVTK library. We run the same conversion for each method during 20 times and print a mean. """ # C backend --------------------------------------------------------------- _file = glob.glob('./vtk_writer_omfs/isolated_sk_Cnv_n_200-Oxs*.omf')[0] data = op.MagnetisationData(_file) data.generate_field() data.generate_coordinates() output_vtk_file = 'vtk_writer_omfs/isolated_sk_Cnv_n_200.vtk' C_timings = [] for i in range(20): start = timeit.default_timer() ot.clib.WriteVTK_RectilinearGrid_C(data.grid[0], data.grid[1], data.grid[2], data.field.reshape(-1), data.field_norm, data.nx, data.ny, data.nz, output_vtk_file) end = timeit.default_timer() C_timings.append(end - start) print('C writer (best of 20): ', np.mean(np.array(C_timings))) # PyVTK ------------------------------------------------------------------- output_vtk_file = 'vtk_writer_omfs/isolated_sk_Cnv_n_200_pyvtk.vtk' pyvtk_timings = [] for i in range(20): start = timeit.default_timer() structure = pyvtk.RectilinearGrid(*data.grid) vtk_data = pyvtk.VtkData(structure, "") # Save the magnetisation vtk_data.cell_data.append(pyvtk.Vectors(data.field, "m")) # Save Ms as scalar field vtk_data.cell_data.append(pyvtk.Scalars(data.field_norm, "Ms")) # Save to VTK file with specified output filename vtk_data.tofile(output_vtk_file, 'binary') end = timeit.default_timer() pyvtk_timings.append(end - start) print('PyVTK writer (best of 20): ', np.mean(np.array(pyvtk_timings)))
def _convert_field_vec_full(self, fld): """ Convert the given scalar or vector fields from the openPMD format to a VTK container. Parameters ---------- fld: str Scalar and vector fields to be converted ex. : 'E', 'B', 'J', 'rho' converts all available components provided by OpenPMDTimeSeries Returns ------- vec: vtk.Vectors VTK vector containter """ # Select the tools for the given geometry if self.geom=='3dcartesian': comps = self.ts.fields_metadata[fld]['axis_labels'] get_field = self._get_opmd_field_3d make_mesh = self._make_vtk_mesh_3d get_origin = self._get_origin_3d elif self.geom=='thetaMode': comps = ['x', 'y', 'z'] get_field = self._get_opmd_field_circ make_mesh = self._make_vtk_mesh_circ get_origin = self._get_origin_circ flds = [] origins = [] for comp in comps: fld_data, self.info = get_field(fld, comp=comp) flds.append(fld_data) make_mesh() origins.append(get_origin()) staggered=False for i in range(len(origins)-1): if not np.allclose(origins[i+1], origins[i]): staggered=True if staggered: print("Warning: components of {:}-field seem staggered"\ .format(fld), "and option CommonMesh=True is used") flds = np.array(flds).T vecs = vtk.Vectors(flds, name=fld) return vecs
def _writevtk(self, filename): grid = [ pmini + np.linspace(0, li, ni + 1) for pmini, li, ni in zip(self.mesh.pmin, self.mesh.l, self.mesh.n) ] structure = pyvtk.RectilinearGrid(*grid) vtkdata = pyvtk.VtkData(structure) vectors = [self.__call__(i) for i in self.mesh.coordinates] vtkdata.cell_data.append(pyvtk.Vectors(vectors, self.name)) for i, component in enumerate(dfu.axesdict.keys()): name = "{}_{}".format(self.name, component) vtkdata.cell_data.append( pyvtk.Scalars(list(zip(*vectors))[i], name)) vtkdata.tofile(filename)
def _convert_field(self, comp, iteration): """ Convert the given scalar or vector fields from the openPMD format to a VTK container. Parameters ---------- comp: str Scalar and vector fields to be converted ex. : 'E', 'B', 'J', 'rho' converts all available components provided by OpenPMDTimeSeries iteration: int iteration number to treat (default 0) """ # Choose the get_field and make_grid finctions for the given geometry if self.geom == '3dcartesian': get_field = self._get_opmd_field_3d make_mesh = self._make_vtk_mesh_3d # Converting the vector field if self.ts.fields_metadata[comp]['type'] == 'vector': coords = self.ts.fields_metadata[comp]['axis_labels'] flds = [] for coord in coords: self.fld, self.info = get_field(comp, iteration, coord=coord) flds.append(self.fld.astype(np.float32).T.ravel()) make_mesh() return vtk.Vectors(np.array(flds).T, name=comp) # Converting the scalar field elif self.ts.fields_metadata[comp]['type'] == 'scalar': self.fld, self.info = get_field(comp, iteration) make_mesh() return vtk.Scalars(self.fld.astype(np.float32).T.ravel(), name=comp) else: print('Error') return None
def loadVecToVTK(self, name, ndofs=1): from petsc4py import PETSc length = np.array(self._size).prod() print 'loading', self._file_prefix + name vec = PETSc.Vec().createSeq(length * ndofs) viewer = PETSc.Viewer().createBinary(self._file_prefix + name, PETSc.Viewer.Mode.R) vec.load(viewer) if self._size[2] == 1: length = 2 * length npvec = vec[...].reshape((self._size_r + (ndofs, )))[:] npvec = np.repeat(npvec, 2, axis=0) npvec = npvec.reshape((length, ndofs)) else: npvec = vec[...].reshape((length, ndofs))[:] # scale if name.startswith('u'): npvec = npvec * self._scalefactor print np.where(np.abs(npvec) / np.abs(npvec).mean() > 1e2)[0] npvec = np.where( np.abs(npvec) / np.abs(npvec).mean() > 1e2, 0., npvec) if ndofs == 1: data = pyvtk.Scalars(npvec, self._prefix.strip('_') + ' ' + name[:-7], 'default') else: data = pyvtk.Vectors([tuple(npvec[i, :]) for i in range(length)], self._prefix.strip('_') + ' ' + name[:-7]) viewer.destroy() vec.destroy() del viewer del vec return data
def _vtk_createVtkData(meshpoints, meshsimplices, data, name, header="Data header (unused)"): #If data is list of float, convert into list of lists, each list containing one float if type(data[0]) in [types.FloatType, types.IntType]: #raw data in scalar data set, convert float a into [a]: data = map(lambda a: [a], data) #Due to inflexibility in pyvtk, we need to distinguish 4 different cases for #2d-meshes with scalar data #2d-meshes with vector data #3d-meshes with scalar data #3d-meshes with vector data #Here we go: if len(meshpoints[0]) == 2: log.debug("Mesh seems 2d") #make 3d for pyvtk meshpoints = map(lambda pos: pos + [0.], meshpoints) if len(data[0]) == 1: log.debug("Data seems 1d (scalar)") log.debug("Creating vtk data structure with dof '%s'" % name) vtk = pyvtk.VtkData( pyvtk.UnstructuredGrid(meshpoints, triangle=meshsimplices), pyvtk.PointData( pyvtk.Scalars(data, name=name, lookup_table='default')), header) elif len(data[0]) in [2, 3]: if len(data[0]) == 2: log.debug("Data seems 2d (vector)") #make 3d for pyvtk data = map(lambda a: a + [0.], data) else: log.debug("Data seems 3d (vector)") log.debug("Creating vtk data structure with dof '%s'" % name) vtk = pyvtk.VtkData( pyvtk.UnstructuredGrid(meshpoints, triangle=meshsimplices), pyvtk.PointData(pyvtk.Vectors(data, name=name)), header) else: raise NfemValueError, "Can only deal with scalar or vector data" elif len(meshpoints[0]) == 3: log.debug("Mesh seems 3d") if len(data[0]) == 1: log.debug("Data seems 1d (scalar)") log.debug("Creating vtk data structure with dof '%s'" % name) vtk = pyvtk.VtkData( pyvtk.UnstructuredGrid(meshpoints, tetra=meshsimplices), pyvtk.PointData( pyvtk.Scalars(data, name=name, lookup_table='default')), header) elif len(data[0]) in [2, 3]: if len(data[0]) == 2: log.debug("Data seems 2d (vector)") #make 3d for pyvtk data = map(lambda a: a + [0.], data) else: log.debug("Data seems 3d (vector)") log.debug("Creating vtk data structure with dof '%s'" % name) vtk = pyvtk.VtkData( pyvtk.UnstructuredGrid(meshpoints, tetra=meshsimplices), pyvtk.PointData(pyvtk.Vectors(data, name=name)), header) else: raise NfemValueError, "Can only deal with scalar or vector data" elif len(meshpoints[0]) == 1: log.debug("Mesh seems 1d") #make 3d for pyvtk meshpoints = map(lambda pos: pos + [0., 0.], meshpoints) if len(data[0]) == 1: log.debug("Data seems 1d (scalar)") log.debug("Creating vtk data structure with dof '%s'" % name) vtk = pyvtk.VtkData( pyvtk.UnstructuredGrid(meshpoints, line=meshsimplices), pyvtk.PointData( pyvtk.Scalars(data, name=name, lookup_table='default')), header) elif len(data[0]) in [2, 3]: if len(data[0]) == 2: log.debug("Data seems 2d (vector)") #make 3d for pyvtk data = map(lambda a: a + [0.], data) else: log.debug("Data seems 3d (vector)") log.debug("Creating vtk data structure with dof '%s'" % name) vtk = pyvtk.VtkData( pyvtk.UnstructuredGrid(meshpoints, line=meshsimplices), pyvtk.PointData(pyvtk.Vectors(data, name=name)), header) else: raise NfemValueError, "Can only deal with scalar or vector data" else: NfemValueError, "Mesh seems to be %d dimensional. Can only do 1, 2 or 3." % len( meshpoints[0]) return vtk
def save_vector(self, v, name="my_field", step=0): self.vtk_data.cell_data.append(pyvtk.Vectors(v, name))
def ovf2vtk_main(): start_time = time.time() banner_doc = 70 * "-" + \ "\novf2vtk --- converting ovf files to vtk files" + "\n" + \ "Hans Fangohr, Richard Boardman, University of Southampton\n"""\ + 70 * "-" # extracts command line arguments # If any of the arguments given appear in the command line, a list of... # ...these args and corresponding values (if any) is returned -> ('args'). # Any arguments that dont dont match the given ones are retuned in a... # ...separate list -> ('params') # Note (fangohr 30/12/2006 20:52): the use of getopt is historic, args, params = getopt.getopt(sys.argv[1:], 'Vvhbta:', [ "verbose", "help", "add=", "binary", "text", "ascii", "surface-effects", "version", "datascale=", "posscale=" ]) # default value surfaceEffects = False datascale = 0.0 # 0.0 has special meaning -- see help text posscale = 0.0 # 0.0 has special meaning -- see help text # provide data from getopt.getopt (args) in form of dictionary options = {} for item in args: if item[1] == '': options[item[0]] = None else: options[item[0]] = item[1] keys = options.keys() # set system responses to arguments given if "--surface-effects" in keys: surfaceEffects = True if "--posscale" in keys: posscale = float(options["--posscale"]) if "--datascale" in keys: datascale = float(options["--datascale"]) if "-v" in keys or "--verbose" in keys: print("running in verbose mode") debug = True else: debug = False if "-h" in keys or "--help" in keys: print(__doc__) sys.exit(0) if "-V" in keys or "--version" in keys: print("This is version {:s}.".format(version)) sys.exit(0) if len(params) == 0: print(__doc__) print("ERROR: An input file (and an output file need to be " "specified).") sys.exit(1) else: infile = params[0] if len(params) == 1: print(__doc__) print("ERROR: An input file AND an output file need to be specified.") print("specify output file") sys.exit(1) else: outfile = params[1] # okay: it seems the essential parameters are given. # Let's check for others: print(banner_doc) if debug: print("infile = {}".format(infile)) print("outfile = {}".format(outfile)) print("args = {}".format(args)) print("options = {}".format(options)) print("datascale = {}".format(datascale)) print("posscale = {}".format(posscale)) # read data from infile vf = omf.read_structured_omf_file(infile, debug) # compute magnitude for all cells Ms = ana.magnitude(vf) # Compute number of cells with non-zero Ms (rpb01r) Ms_num_of_nonzeros = Numeric.sum(Numeric.not_equal(Ms, 0.0)) print("({:5.2f}% of {:d} cells filled)".format( 100.0 * Ms_num_of_nonzeros / len(Ms), len(Ms))) # scale magnetisation data as required: if datascale == 0.0: scale = max(Ms) print("Will scale data down by {:f}".format(scale)) else: scale = datascale # normalise vectorfield by scale vf = Numeric.divide(vf, scale) # read metadata in data file ovf_run = omf.analyze(infile) datatitle = ovf_run["Title:"] + "/{:g}".format(scale) # # need x, y and z vectors for vtk format # # taking actual spacings for dx, dy and dz results generally in # poor visualisation results (in particular for thin films, one # would like to have some magnification in z-direction). Also:vtk # is not happy with positions on the 10e-9 scale, so one better # scales this to something closer to unity. # extract dimensions from file dimensions = (int(ovf_run["xnodes:"]), int(ovf_run["ynodes:"]), int(ovf_run["znodes:"])) # scale data by given factor if posscale != 0.0: # find range between max and min values of components xrange = abs(float(ovf_run["xmax:"]) - float(ovf_run["xmin:"])) yrange = abs(float(ovf_run["ymax:"]) - float(ovf_run["ymin:"])) zrange = abs(float(ovf_run["zmax:"]) - float(ovf_run["zmin:"])) # define no. of x,y,z nodes xnodes = float(ovf_run["xnodes:"]) ynodes = float(ovf_run["ynodes:"]) znodes = float(ovf_run["znodes:"]) # define stepsizes xstepsize = float(ovf_run["xstepsize:"]) ystepsize = float(ovf_run["ystepsize:"]) zstepsize = float(ovf_run["zstepsize:"]) # define bases xbase = float(ovf_run["xbase:"]) ybase = float(ovf_run["ybase:"]) zbase = float(ovf_run["zbase:"]) # find dx, dy, dz in SI units: dx = xrange / xnodes dy = yrange / ynodes dz = zrange / znodes # find scale factor that OOMMF uses for xstepsize and xnodes, # etc. (Don't know how to get this directly.) xscale = dx * xstepsize yscale = dy * ystepsize zscale = dz * zstepsize # extract x, y and z positions from ovf file. xbasevector = [None] * dimensions[0] # create empty vector for i in range(dimensions[0]): # data is stored for 'centre' of each cuboid, therefore (i+0.5) xbasevector[i] = xbase + (i + 0.5) * xstepsize * xscale ybasevector = [None] * dimensions[1] for i in range(dimensions[1]): ybasevector[i] = ybase + (i + 0.5) * ystepsize * yscale zbasevector = [None] * dimensions[2] for i in range(dimensions[2]): zbasevector[i] = zbase + (i + 0.5) * zstepsize * zscale # finally, convert list to numeric (need to have this consistent) xbasevector = Numeric.array(xbasevector) / float(posscale) ybasevector = Numeric.array(ybasevector) / float(posscale) zbasevector = Numeric.array(zbasevector) / float(posscale) else: # posscale == 0.0 # this generally looks better: xbasevector = Numeric.arange(dimensions[0]) ybasevector = Numeric.arange(dimensions[1]) zbasevector = Numeric.arange(dimensions[2]) # # write ascii or binary vtk-file (default is binary) # vtk_data = 'binary' if '--ascii' in keys or '-t' in keys or '--text' in keys: vtk_data = 'ascii' if debug: print("switching to ascii vtk-data") if '--binary' in keys or '-b' in keys: vtk_data = 'binary' if debug: print("switching to binary vtk-data") # # and now open vtk-file # vtkfilecomment = "Output from ovf2vtk (version {:s}), {:s}, infile={:s}. "\ .format(version, time.asctime(), infile) vtkfilecomment += "Calling command line was '{:s}' executed in '{:s}'"\ .format(" ".join(sys.argv), os.getcwd()) # define inputs RecGrid = pyvtk.RectilinearGrid(xbasevector.tolist(), ybasevector.tolist(), zbasevector.tolist()) PData = pyvtk.PointData(pyvtk.Vectors(vf.tolist(), datatitle)) # define vtk file. vtk = pyvtk.VtkData(RecGrid, vtkfilecomment, PData, format=vtk_data) # now compute all the additional data such as angles, etc # check whether we should do all keys = map(lambda x: x[1], args) if "all" in keys: args = [] for add_arg in add_features: args.append(("--add", add_arg)) # when ovf2vtk was re-written using Numeric, I had to group # certain operations to make them fast. Now some switches are # unneccessary. (fangohr 25/08/2003 01:35) # To avoid executing the # same code again, we remember what we have computed already: done_angles = 0 done_comp = 0 for arg in args: if arg[0] == "-a" or arg[0] == "--add": print("working on {}".format(arg)) data = [] lookup_table = 'default' # compute observables that need more than one field value # i.e. div, rot if arg[1][0:6] == "divrot": # rotation = vorticity, curl (div, rot, rotx, roty, rotz, rotmag) = \ ana.divergence_and_curl(vf, surfaceEffects, ovf_run) # change order of observables for upcoming loop observables = (rotx, roty, rotz, rotmag, rot, div) comments = [ "curl, x-comp", "curl, y-comp", "curl, z-comp", "curl, magnitude", "curl", "divergence" ] # append data to vtk file for obs, comment in zip(observables, comments): # for rotx, roty, rotz, rotmag, div if comment != "curl": vtk.point_data.append( pyvtk.Scalars(obs.tolist(), comment, lookup_table)) # for rot else: vtk.point_data.append( pyvtk.Vectors(obs.tolist(), comment)) # components elif arg[1] in ["Mx", "My", "Mz", "Ms"]: if done_comp == 0: done_comp = 1 comments = "x-component", "y-component", "z-component" for data, comment in zip(ana.components(vf), comments): vtk.point_data.append( pyvtk.Scalars(data.tolist(), comment, lookup_table)) # magnitude of magnitisation Mmag = ana.magnitude(vf) vtk.point_data.append( pyvtk.Scalars(Mmag.tolist(), "Magnitude", lookup_table)) elif arg[1] in ["xy", "xz", "yz"]: if done_angles == 0: done_angles = 1 # in-plane angles comments = ("xy in-plane angle", "yz in-plane angle", "xz in-plane angle") for data, comment in zip(ana.plane_angles(vf), comments): vtk.point_data.append( pyvtk.Scalars(data.tolist(), comment, lookup_table)) else: print("only xy, xz, Mx, My, Mz, divergence, Ms, or 'all' \ allowed after -a or --add") print("Current choice is {}".format(arg)) print(__doc__) sys.exit(1) # # eventually, write the file # print("saving file ({:s})".format(outfile)) vtk.tofile(outfile, format=vtk_data) print("finished conversion (execution time {:5.3s} seconds)".format( str(time.time() - start_time)))
fmat_last = fmat eleTag_last = etag wdotf = np.tensordot(weights[istation], fmat, ([0], [1])) exparray = 2. * np.exp(np.arange(0, nu_p_1) * 1j * azims[istation]) exparray[0] = 1. spz = wdotf.dot(exparray).real if args.norm: disp_norm[istation] = np.linalg.norm(spz) else: disp[istation, 0] = spz[0] * np.cos(dist) - spz[2] * np.sin(dist) disp[istation, 1] = spz[1] disp[istation, 2] = spz[0] * np.sin(dist) + spz[2] * np.cos(dist) if args.norm: vtk = pyvtk.VtkData( vtk_points, pyvtk.PointData(pyvtk.Scalars(disp_norm, name='disp_norm')), 'surface animation') else: vtk = pyvtk.VtkData( vtk_points, pyvtk.PointData(pyvtk.Vectors(disp, name='disp_RTZ')), 'surface animation') vtk.tofile(args.out_vtk + '/surface_vtk.' + str(it) + '.vtk', 'binary') if args.verbose: elapsed = time.clock() - clock0s print(' Done with snapshot t = %f s; tstep = %d / %d, rank = %d, elapsed = %f' \ % (var_time[istep], it + 1, len(steps), mpi_rank, elapsed)) if args.verbose and mpi_rank == 0: elapsed = time.clock() - clock0 print('Generating snapshots done, ' + '%f sec elapsed.' % (elapsed))
# -*- coding: utf-8 -*- """ Created on Wed Jun 7 14:58:44 2017 @author: Jonas Lindemann """ import numpy as np import pyvtk as vtk print("Reading from uvw.dat...") xyzuvw = np.loadtxt('uvw.dat', skiprows=2) print("Converting to points and vectors") points = xyzuvw[:, 0:3].tolist() vectors = xyzuvw[:, 3:].tolist() pointdata = vtk.PointData(vtk.Vectors(vectors, name="vec1"), vtk.Vectors(vectors, name="vec2")) data = vtk.VtkData(vtk.StructuredGrid([96, 65, 48], points), pointdata) data.tofile('uvw', 'ascii')
def field2VTKData (self,name=None,lookupTable=None): """ Creates VTK representation of the receiver. Useful for visualization. Requires pyvtk module. :param str name: human-readable name of the field :param pyvtk.LookupTable lookupTable: color lookup table :return: Instance of pyvtk :rtype: pyvtk """ import pyvtk if name is None: name=self.getFieldIDName() if lookupTable and not isinstance(lookupTable,pyvtk.LookupTable): log.info('ignoring lookupTable which is not a pyvtk.LookupTable instance.') lookupTable=None if lookupTable is None: lookupTable=pyvtk.LookupTable([(0,.231,.298,1.0),(.4,.865,.865,1.0),(.8,.706,.016,1.0)],name='coolwarm') #Scalars use different name than 'coolwarm'. Then Paraview uses its own color mapping instead of taking 'coolwarm' from *.vtk file. This prevents setting Paraview's color mapping. scalarsKw=dict(name=name,lookup_table='default') else: scalarsKw=dict(name=name,lookup_table=lookupTable.name) # see http://cens.ioc.ee/cgi-bin/cvsweb/python/pyvtk/examples/example1.py?rev=1.3 for an example vectorsKw=dict(name=name) # vectors don't have a lookup_table if (self.fieldType == FieldType.FT_vertexBased): if (self.getValueType() == ValueType.Scalar): return pyvtk.VtkData(self.mesh.getVTKRepresentation(), pyvtk.PointData(pyvtk.Scalars([val[0] for val in self.value],**scalarsKw),lookupTable), 'Unstructured Grid Example') elif (self.getValueType() == ValueType.Vector): return pyvtk.VtkData(self.mesh.getVTKRepresentation(), pyvtk.PointData(pyvtk.Vectors(self.value,**vectorsKw),lookupTable), 'Unstructured Grid Example') elif (self.getValueType() == ValueType.Tensor): return pyvtk.VtkData(self.mesh.getVTKRepresentation(), pyvtk.PointData(pyvtk.Tensors(self.getMartixForTensor(self.value),**vectorsKw),lookupTable),'Unstructured Grid Example') else: if (self.getValueType() == ValueType.Scalar): return pyvtk.VtkData(self.mesh.getVTKRepresentation(), pyvtk.CellData(pyvtk.Scalars([val[0] for val in self.value],**scalarsKw),lookupTable), 'Unstructured Grid Example') elif (self.getValueType() == ValueType.Vector): return pyvtk.VtkData(self.mesh.getVTKRepresentation(), pyvtk.CellData(pyvtk.Vectors(self.value,**vectorsKw),lookupTable), 'Unstructured Grid Example') elif (self.getValueType() == ValueType.Tensor): return pyvtk.VtkData(self.mesh.getVTKRepresentation(), pyvtk.CellData(pyvtk.Tensors(self.getMartixForTensor(self.value),**vectorsKw),lookupTable),'Unstructured Grid Example')
def citcom2vtk(t): print "Timestep:", t benchmarkstr = "" #Assign create_bottom and create_surface to bottom and surface #to make them valid in methods namespace bottom = create_bottom surface = create_surface ordered_points = [] #reset Sequences for points ordered_temperature = [] ordered_velocity = [] ordered_visc = [] #Surface and Bottom Points #Initialize empty sequences surf_vec = [] botm_vec = [] surf_topo = [] surf_hflux = [] botm_topo = [] botm_hflux = [] surf_points = [] botm_points = [] for capnr in xrange(nproc_surf): ###Benchmark Point 1 Start## #start = datetime.now() ############################ print "Processing cap", capnr + 1, "of", nproc_surf cap = f.root._f_getChild("cap%02d" % capnr) #Information from hdf #This information needs to be read only once hdf_coords = cap.coord[:] hdf_velocity = cap.velocity[t] hdf_temperature = cap.temperature[t] hdf_viscosity = cap.viscosity[t] ###Benchmark Point 1 Stop## #delta = datetime.now() - start #benchmarkstr += "%.5lf," % (delta.seconds + float(delta.microseconds)/1e6) ###Benchmark Point 2 Start## #start = datetime.now() ############################ #Create Iterator to change data representation nx_redu_iter = reduce_iter(nx, nx_redu) ny_redu_iter = reduce_iter(ny, ny_redu) nz_redu_iter = reduce_iter(nz, nz_redu) #vtk_i = vtk_iter(el_nx_redu,el_ny_redu,el_nz_redu) # read citcom data - zxy (z fastest) for j in xrange(el_ny_redu): j_redu = ny_redu_iter.next() nx_redu_iter = reduce_iter(nx, nx_redu) for i in xrange(el_nx_redu): i_redu = nx_redu_iter.next() nz_redu_iter = reduce_iter(nz, nz_redu) for k in xrange(el_nz_redu): k_redu = nz_redu_iter.next() colat, lon, r = map(float, hdf_coords[i_redu, j_redu, k_redu]) x_coord, y_coord, z_coord = RTF2XYZ(colat, lon, r) ordered_points.append((x_coord, y_coord, z_coord)) ordered_temperature.append( float(hdf_temperature[i_redu, j_redu, k_redu])) ordered_visc.append( float(hdf_viscosity[i_redu, j_redu, k_redu])) vel_colat, vel_lon, vel_r = map( float, hdf_velocity[i_redu, j_redu, k_redu]) x_velo, y_velo, z_velo = velocity2cart( vel_colat, vel_lon, vel_r, colat, lon, r) ordered_velocity.append((x_velo, y_velo, z_velo)) ##Delete Objects for GC del hdf_coords del hdf_velocity del hdf_temperature del hdf_viscosity ###Benchmark Point 2 Stop## #delta = datetime.now() - start #benchmarkstr += "%.5lf," % (delta.seconds + float(delta.microseconds)/1e6) ###Benchmark Point 3 Start## #start = datetime.now() ############################ #Bottom Information from hdf if bottom == True: try: hdf_bottom_coord = cap.botm.coord[:] hdf_bottom_heatflux = cap.botm.heatflux[t] hdf_bottom_topography = cap.botm.topography[t] hdf_bottom_velocity = cap.botm.velocity[t] except: print "\tCould not find bottom information in file.\n \ Set create bottom to false" bottom = False #Surface Information from hdf if surface == True: try: hdf_surface_coord = cap.surf.coord[:] hdf_surface_heatflux = cap.surf.heatflux[t] hdf_surface_topography = cap.surf.topography[t] hdf_surface_velocity = cap.surf.velocity[t] except: print "\tCould not find surface information in file.\n \ Set create surface to false" surface = False ###Benchmark Point 3 Stop## #delta = datetime.now() - start #benchmarkstr += "%.5lf," % (delta.seconds + float(delta.microseconds)/1e6) ###Benchmark Point 4 Start## #start = datetime.now() ############################ #Compute surface/bottom topography mean if create_topo: surf_mean = 0.0 botm_mean = 0.0 if surface: for i in xrange(nx): surf_mean += numpy.mean(hdf_surface_topography[i]) surf_mean = surf_mean / ny if bottom: for i in xrange(nx): botm_mean += numpy.mean(hdf_bottom_topography[i]) botm_mean = botm_mean / nx ###Benchmark Point 4 Stop## #delta = datetime.now() - start #benchmarkstr += "%.5lf," % (delta.seconds + float(delta.microseconds)/1e6) ###Benchmark Point 5 Start## #start = datetime.now() ############################ #Read Surface and Bottom Data if bottom == True or surface == True: for i in xrange(nx): for j in xrange(ny): if bottom == True: #Bottom Coordinates if create_topo == True: colat, lon = hdf_bottom_coord[i, j] x, y, z = RTF2XYZ( colat, lon, radius_inner + float( (hdf_bottom_topography[i, j] - botm_mean) * (10**21) / (6371000**2 / 10**(-6)) / (3300 * 10) / 1000)) botm_points.append((x, y, z)) else: colat, lon = hdf_bottom_coord[i, j] x, y, z = RTF2XYZ(colat, lon, radius_inner) botm_points.append((x, y, z)) #Bottom Heatflux botm_hflux.append(float(hdf_bottom_heatflux[i, j])) #Bottom Velocity vel_colat, vel_lon = map(float, hdf_bottom_velocity[i, j]) x, y, z = velocity2cart(vel_colat, vel_lon, radius_inner, colat, lon, radius_inner) botm_vec.append((x, y, z)) if surface == True: #Surface Information if create_topo == True: colat, lon = hdf_surface_coord[i, j] #637100 = Earth radius, 33000 = ? x, y, z = RTF2XYZ( colat, lon, radius_outer + float( (hdf_surface_topography[i, j] - surf_mean) * (10**21) / (6371000**2 / 10**(-6)) / (3300 * 10) / 1000)) surf_points.append((x, y, z)) else: colat, lon = hdf_surface_coord[i, j] x, y, z = RTF2XYZ(colat, lon, radius_outer) surf_points.append((x, y, z)) #Surface Heatflux surf_hflux.append(float(hdf_surface_heatflux[i, j])) #Surface Velocity vel_colat, vel_lon = map(float, hdf_surface_velocity[i, j]) x, y, z = velocity2cart(vel_colat, vel_lon, radius_outer, colat, lon, radius_outer) surf_vec.append((x, y, z)) #del variables for GC if bottom == True: del hdf_bottom_coord del hdf_bottom_heatflux del hdf_bottom_velocity if surface == True: del hdf_surface_coord del hdf_surface_heatflux del hdf_surface_velocity ###Benchmark Point 5 Stop## #delta = datetime.now() - start #benchmarkstr += "%.5lf," % (delta.seconds + float(delta.microseconds)/1e6) ###Benchmark Point 6 Start## #start = datetime.now() ############################ ################################################################## #Create Connectivity info if counter == 0: #For 3d Data i = 1 #Counts X Direction j = 1 #Counts Y Direction k = 1 #Counts Z Direction for n in xrange((el_nx_redu * el_ny_redu * el_nz_redu) - (el_nz_redu * el_nx_redu)): if (i % el_nz_redu) == 0: #X-Values!!! j += 1 #Count Y-Values if (j % el_nx_redu) == 0: k += 1 #Count Z-Values if i % el_nz_redu != 0 and j % el_nx_redu != 0: #Check if Box can be created #Get Vertnumbers n0 = n + (capnr * (el_nx_redu * el_ny_redu * el_nz_redu)) n1 = n0 + el_nz_redu n2 = n1 + el_nz_redu * el_nx_redu n3 = n0 + el_nz_redu * el_nx_redu n4 = n0 + 1 n5 = n4 + el_nz_redu n6 = n5 + el_nz_redu * el_nx_redu n7 = n4 + el_nz_redu * el_nx_redu #Created Polygon Box polygons3d.append([n0, n1, n2, n3, n4, n5, n6, n7]) #Hexahedron VTK Representation i += 1 if bottom == True or surface == True: #Connectivity for 2d-Data i = 1 for n in xrange((nx) * (ny) - ny): if i % ny != 0: n0 = n + (capnr * ((nx) * (ny))) n1 = n0 + 1 n2 = n0 + ny n3 = n2 + 1 polygons2d.append([n0, n1, n2, n3]) i += 1 ###Benchmark Point 6 Stop## #delta = datetime.now() - start #benchmarkstr += "%.5lf\n" % (delta.seconds + float(delta.microseconds)/1e6) #print benchmarkstr ################################################################# #Write Data to VTK #benchmarkstr = "\n\nIO:\n" ###Benchmark Point 7 Start## #start = datetime.now() ############################ print 'Writing data to vtk...' #Surface Points if surface == True: struct_coords = pyvtk.UnstructuredGrid(surf_points, pixel=polygons2d) #topo_scal = pyvtk.Scalars(surf_topo,'Surface Topography', lookup_table='default') hflux_scal = pyvtk.Scalars(surf_hflux, 'Surface Heatflux', lookup_table='default') vel_vec = pyvtk.Vectors(surf_vec, 'Surface Velocity Vectors') ## tempdata = pyvtk.PointData(hflux_scal, vel_vec) data = pyvtk.VtkData( struct_coords, tempdata, 'CitcomS Output %s Timestep %s' % ('surface info', t)) if create_ascii: data.tofile(vtk_path + (vtkfile % ('surface', t)), ) else: data.tofile(vtk_path + (vtkfile % ('surface', t)), 'binary') print "Written Surface information to file" ###Benchmark Point 7 Stop## #delta = datetime.now() - start #benchmarkstr += "%.5lf," % (delta.seconds + float(delta.microseconds)/1e6) ###Benchmark Point 8 Start## #start = datetime.now() ############################ if bottom == True: #Bottom Points struct_coords = pyvtk.UnstructuredGrid(botm_points, pixel=polygons2d) #topo_scal = pyvtk.Scalars(botm_topo,'Bottom Topography','default') hflux_scal = pyvtk.Scalars(botm_hflux, 'Bottom Heatflux', 'default') vel_vec = pyvtk.Vectors(botm_vec, 'Bottom Velocity Vectors') ## tempdata = pyvtk.PointData(hflux_scal, vel_vec) data = pyvtk.VtkData( struct_coords, tempdata, 'CitcomS Output %s Timestep %s' % ('Bottom info', t)) if create_ascii: data.tofile(vtk_path + (vtkfile % ('bottom', t))) else: data.tofile(vtk_path + (vtkfile % ('bottom', t)), 'binary') print "Written Bottom information to file" ###Benchmark Point 8 Stop## #delta = datetime.now() - start #benchmarkstr += "%.5lf," % (delta.seconds + float(delta.microseconds)/1e6) ###Benchmark Point 9 Start## #start = datetime.now() #General Data struct_coords = pyvtk.UnstructuredGrid(ordered_points, hexahedron=polygons3d) vel_vec = pyvtk.Vectors(ordered_velocity, 'Velocity Vectors') temp_scal = pyvtk.Scalars(ordered_temperature, 'Temperature Scalars', 'default') visc_scal = pyvtk.Scalars(ordered_visc, 'Viscosity Scalars', 'default') ## tempdata = pyvtk.PointData(temp_scal, visc_scal, vel_vec) data = pyvtk.VtkData( struct_coords, tempdata, 'CitcomS Output %s Timestep:%d NX:%d NY:%d NZ:%d Radius_Inner:%f' % (path, t, el_nx_redu, el_ny_redu, el_nz_redu, radius_inner)) ############################ if create_ascii: data.tofile(vtk_path + (vtkfile % ('general', t))) else: data.tofile(vtk_path + (vtkfile % ('general', t)), 'binary') print "Written general data to file"
import os f, jac = lorenz_attractor(10., 28., 8. / 3) T = 40. tau = 1e-2 ipf = 4 n_steps = int(T / tau) n_particles = 10000 deviation = 0.01 start_point = np.array([0., 0., 0.]) starts = np.random.normal(start_point, deviation, (n_particles, 3)) r_0 = np.linalg.norm(starts - start_point, axis=1, ord=2) cloud = [RK45Solver(f, x_0, 0., T, n_steps) for x_0 in starts] for particle in cloud: particle.solve() dirpath = 'vtk/000_10k/' if not os.path.exists(dirpath): os.mkdir(dirpath) for i in range(0, n_steps + 1, ipf): points = [p.x[:, i] for p in cloud] velocities = [f(i, x) for x in points] vtk = pyvtk.VtkData( pyvtk.UnstructuredGrid(points), pyvtk.PointData(pyvtk.Vectors(velocities, name='Velocity'), pyvtk.Scalars(r_0, name='r_0'))) vtk.tofile(dirpath + f'f{i}')
def write_fields_vtk(self, flds=None, iteration=0, format='binary', zmin_fixed=None, Nth=24, CommonMesh=True, sample=None): """ Convert the given list of scalar and vector fields from the openPMD format to a VTK container, and write it to the disk. Parameters ---------- flds: list or None List of scalar and vector fields to be converted. If None, it converts all available components provided by OpenPMDTimeSeries iteration: int iteration number to treat (default 0) format: str format for the VTK file, either 'ascii' or 'binary' zmin_fixed: float or None When treating the simulation data for the animation, in some cases (e.g. with moving window) it is useful to fix the origin of the visualization domain. If float number is given it will be use as z-origin of the visualization domain Nth: int, optional Number of nodes of the theta-axis of a cylindric grid in case of thetaMode geometry. Note: for high the Nth>>10 the convertion may become rather slow. CommonMesh: bool If True, the same mesh will be used and fields will be converted to the scalar and vector types. If False, each component will be saved as a separate file with its own grid. sample: tuple of 2 or 3 integers or None If not None, the field arrays will be reduced by skipping elements, i.e. for 3D geometry field F is replaced by F[::sample[0],::sample[1],::sample[2]] """ # Check available fields if comps is not defined if flds is None: flds = self.ts.avail_fields # Register constant parameters self.iteration = iteration self.zmin_fixed = zmin_fixed self.CommonMesh = CommonMesh self.Nth = Nth if sample is None: self.sample = (1, 1, 1) else: self.sample = sample # Set grid to None, in order to recomupte it self.grid = None # Make a numer string for the file to write istr = str(self.iteration) while len(istr) < 7: istr = '0' + istr if self.CommonMesh: # get and store fields Scalars and Vectors vtk_container = [] for fld in flds: field_type = self.ts.fields_metadata[fld]['type'] if field_type == 'vector': fdata, fname = self._get_field_vec_full(fld) print(fdata.shape, fname) vecs = vtk.Vectors(fdata, name=fname) vtk_container.append(vecs) elif field_type == 'scalar': fdata, fname = self._get_field_scl(fld) scl = vtk.Scalars(fdata, name=fname) vtk_container.append(scl) # write VTK file vtk.VtkData(self.grid, vtk.PointData(*vtk_container))\ .tofile(self.path+'vtk_fields_'+istr, format=format) else: for fld in flds: field_type = self.ts.fields_metadata[fld]['type'] if field_type == 'vector': comps = ['x', 'y', 'z'] for comp in comps: fld_full = fld + comp file_name = self.path+'vtk_fields_{}_{}'\ .format(fld_full, istr) fdata, fname = self._get_field_vec_comp(fld, comp) scl = vtk.Scalars(fdata, name=fname) vtk.VtkData(self.grid, vtk.PointData(scl))\ .tofile(file_name, format=format) elif field_type == 'scalar': file_name = self.path+'vtk_fields_{}_{}'\ .format(fld, istr) fdata, fname = self._get_field_vec_comp(fld, comp) scl = vtk.Scalars(fdata, name=fname) vtk.VtkData(self.grid, vtk.PointData(scl))\ .tofile(file_name, format=format)
def ovf2vtk_main(): start_time = time.time() banner_doc = 70*"-"+\ "\novf2vtk --- converting ovf files to vtk files"+"\n"+\ "Hans Fangohr, Richard Boardman, University of Southampton\n"""+70*"-" #extract command line arguments additions,params = getopt.getopt( sys.argv[1:], 'Vvhbta:', ["verbose","help","add=","binary","text","ascii","surface-effects","version","datascale=","posscale="] ) #Note (fangohr 30/12/2006 20:52): the use of getopt is historic, #and so is the use of the name 'additions'. #default value surfaceEffects = False datascale = 0.0 #0.0 has special meaning -- see help text posscale = 0.0 #0.0 has special meaning -- see help text #provide data from getopt.getopt (additions) in form of hash table options = {} for item in additions: if item[1]=='': options[item[0]] = None else: options[item[0]] = item[1] keys = options.keys() if "--surface-effects" in keys: surfaceEffects = True if "--posscale" in keys: posscale = float(options["--posscale"]) if "--datascale" in keys: datascale = float(options["--datascale"]) if "-v" in keys or "--verbose" in keys: print "running in verbose mode" debug = True else: debug = False if "-h" in keys or "--help" in keys: print __doc__ sys.exit(0) if "-V" in keys or "--version" in keys: print "This is version %s." % ovf2vtk.__version__ sys.exit(0) if len( params ) == 0: print __doc__ print "ERROR: An input file (and an output file need to be specified)." sys.exit(1) else: infile = params[0] if len( params ) == 1: print __doc__ print "ERROR: An input file AND an output file need to be specified." print "specify output file" sys.exit(1) else: outfile = params[1] # okay: it seems the essential parameters are given. Let's check for others: print banner_doc if debug: print "infile = ", infile print "outfile = ",outfile print "additions= ",additions print "options = ",options print "datascale=",datascale print "posscale=",posscale #read data from infile vf = read_structured_omf_file( infile, debug ) #compute magnitude for all cells Ms = magnitude( vf ) # Compute number of cells with non-zero Ms (rpb01r) Ms_num_of_nonzeros = Numeric.sum( Numeric.not_equal( Ms, 0.0 ) ) print "(%5.2f%% of %d cells filled)" % (100.0*Ms_num_of_nonzeros/len(Ms), len(Ms)) #read metadata in data file ovf_run = analyze( infile ) #scale magnetisation data as required: if datascale == 0.0: scale = max( Ms ) print "Will scale data down by %f" % scale else: scale = datascale vf = Numeric.divide( vf, scale ) datatitle = ovf_run["Title:"]+"/%g" % (scale) # #need x, y and z vectors for vtk format # #taking actual spacings for dx, dy and dz results generally in #poor visualisation results (in particular for thin films, one #would like to have some magnification in z-direction). Also:vtk #is not happy with positions on the 10e-9 scale, so one better #scales this to something closer to unity. #extract dimensions from file dimensions = ( int( ovf_run["xnodes:"] ), \ int( ovf_run["ynodes:"] ), \ int( ovf_run["znodes:"] )) if posscale != 0.0: #scale data by given factor #find dx, dy, dz in SI units: Lx = abs(float(ovf_run["xmax:"])-float(ovf_run["xmin:"])) Ly = abs(float(ovf_run["ymax:"])-float(ovf_run["ymin:"])) Lz = abs(float(ovf_run["zmax:"])-float(ovf_run["zmin:"])) dx = Lx / float( ovf_run["xnodes:"] ) dy = Ly / float( ovf_run["ynodes:"] ) dz = Lz / float( ovf_run["znodes:"] ) #find scale factor that OOMMF uses for xstepsize and xnodes, #etc. (Don't know how to get this directly.) xscale = Lx / (float( ovf_run["xnodes:"])*float(ovf_run["xstepsize:"])) yscale = Ly / (float( ovf_run["ynodes:"])*float(ovf_run["ystepsize:"])) zscale = Lz / (float( ovf_run["znodes:"])*float(ovf_run["zstepsize:"])) #extract x, y and z positions from ovf file. xbasevector = [None] * dimensions[0] #create empty vector for i in range( dimensions[0] ): #data is stored for 'centre' of each cuboid, therefore (i+0.5) xbasevector[i] = float( ovf_run["xbase:"] ) +\ (i+0.5) *float( ovf_run["xstepsize:"] )*xscale ybasevector = [None]* dimensions[1] for i in range( dimensions[1] ): ybasevector[i] = float( ovf_run["ybase:"] ) + (i+0.5) *float( ovf_run["ystepsize:"] )*yscale zbasevector = [None]* dimensions[2] for i in range( dimensions[2] ): zbasevector[i] = float( ovf_run["zbase:"] ) + (i+0.5) *float( ovf_run["zstepsize:"] )*zscale #finally, convert list to numerix (need to have this consistent) xbasevector = Numeric.array(xbasevector)/float(posscale) ybasevector = Numeric.array(ybasevector)/float(posscale) zbasevector = Numeric.array(zbasevector)/float(posscale) else: #posscale == 0.0 # #this generally looks better: # xbasevector = Numeric.arange( dimensions[0] ) ybasevector = Numeric.arange( dimensions[1] ) zbasevector = Numeric.arange( dimensions[2] ) # # write ascii or binary vtk-file (default is binary) # vtk_data = 'binary' if '--ascii' in keys or '-t' in keys or '--text' in keys: vtk_data = 'ascii' if debug: print "switching to ascii vtk-data" if '--binary' in keys or '-b' in keys: vtk_data = 'binary' if debug: print "switching to binary vtk-data" # #and now open vtk-file # vtkfilecomment = "Output from ovf2vtk (version %s), %s, infile=%s. " % (ovf2vtk.__version__,\ time.asctime(),\ infile) vtkfilecomment += "Calling command line was '%s' executed in '%s'" % (" ".join(sys.argv),\ os.getcwd()) vtk = pyvtk.VtkData( pyvtk.RectilinearGrid(xbasevector.tolist(),ybasevector.tolist(),zbasevector.tolist()), vtkfilecomment, pyvtk.PointData(pyvtk.Vectors( vf.tolist(), datatitle ) ), format=vtk_data) # # now compute all the additional data such as angles, etc # # check whether we should do all keys = map(lambda x:x[1], additions) if "all" in keys: additions = [] for add in add_features: additions.append(("--add",add)) # when ovf2vtk was re-written using Numeric, I had to group # certain operations to make them fast. Now some switches are # unneccessary. (fangohr 25/08/2003 01:35) # To avoid executing the # same code again, we remember what we have computed already: done_angles = 0 done_comp = 0 for add in additions: if add[0]=="-a" or add[0]=="--add": print "working on",add data=[] #compute observables that need more than one field value, i.e. div, rot if add[1][0:6] == "divrot": #rotation = vorticity, curl (div, rot, rotx, roty, rotz, rotmag) = divergence_and_curl( vf, surfaceEffects, ovf_run ) comment = "curl, x-comp" vtk.point_data.append( pyvtk.Scalars( rotx.tolist() , comment , lookup_table='default') ) Comment = "curl, y-comp" vtk.point_data.append( pyvtk.Scalars( roty.tolist() , comment , lookup_table='default') ) comment = "curl, z-comp" vtk.point_data.append( pyvtk.Scalars( rotz.tolist() , comment , lookup_table='default') ) comment = "curl, magnitude" vtk.point_data.append( pyvtk.Scalars( rotmag.tolist(), comment , lookup_table='default') ) comment = "curl" vtk.point_data.append( pyvtk.Vectors( rot.tolist() , comment ) ) comment = "divergence" vtk.point_data.append( pyvtk.Scalars( div.tolist() , comment , lookup_table='default') ) done_div_rot = True elif add[1] in ["Mx","My","Mz","Ms"]: # components if not done_comp: done_comp = 1 comments = "x-component", "y-component", "z-component" for data, comment in zip( components( vf ), comments): vtk.point_data.append( pyvtk.Scalars( data.tolist(), comment,lookup_table='default' ) ) # magnitude of magnitisation Mmag = magnitude( vf ) vtk.point_data.append( pyvtk.Scalars(Mmag.tolist(), "Magnitude",lookup_table='default' ) ) elif add[1] in ["xy","xz","yz"]: if not done_angles: done_angles = 1 # in-plane angles comments = "xy in-plane angle", "yz in-plane angle", "xz in-plane angle" for data, comment in zip( plane_angles( vf ), comments): vtk.point_data.append( pyvtk.Scalars( data.tolist(), comment, lookup_table='default' ) ) else: print "only xy, xz, Mx, My, Mz, divergence, Ms, or 'all' allowed after -a or --add" print "Current choice is",add print __doc__ sys.exit(1) # #eventually, write the file # print "saving file (%s)" % (outfile) vtk.tofile(outfile,format=vtk_data) print "finished conversion (execution time %5.3s seconds)" % (time.time()-start_time)
def write_vtk(iproc): if args.nproc == 1: nc_surf_local = Dataset(args.in_surface_nc, 'r', format='NETCDF4') iproc = 0 else: # copy netcdf file for parallel access tempnc = args.out_vtk + '/surface_temp.nc' + str(iproc) shutil.copy(args.in_surface_nc, tempnc) nc_surf_local = Dataset(tempnc, 'r', format='NETCDF4') # write vtk if args.verbose and iproc == 0: clock0 = time.clock() print('Generating snapshot...') for it, istep in enumerate(steps): if it % args.nproc != iproc: continue if args.min_step is not None: if it < args.min_step: continue if args.max_step is not None: if it > args.max_step: continue if args.norm: disp_norm = np.zeros(nstation) else: disp = np.zeros((nstation, 3)) eleTag_last = -1 fourier_last = None for istation, dist in enumerate(dists): if eleTags[istation] == eleTag_last: fourier = fourier_last else: fourier_r = nc_surf_local.variables['edge_' + str(eleTags[istation]) + 'r'][istep, :] fourier_i = nc_surf_local.variables['edge_' + str(eleTags[istation]) + 'i'][istep, :] fourier = fourier_r[:] + fourier_i[:] * 1j fourier_last = fourier eleTag_last = eleTags[istation] nu_p_1 = int(len(fourier) / nPntEdge / 3) wdotf = np.zeros((3, nu_p_1), dtype=fourier.dtype) for idim in np.arange(0, 3): start = idim * nPntEdge * nu_p_1 end = idim * nPntEdge * nu_p_1 + nPntEdge * nu_p_1 fmat = fourier[start:end].reshape(nPntEdge, nu_p_1) wdotf[idim] = weights[istation].dot(fmat) exparray = 2. * np.exp(np.arange(0, nu_p_1) * 1j * azims[istation]) exparray[0] = 1. spz = wdotf.dot(exparray).real if args.norm: disp_norm[istation] = np.linalg.norm(spz) else: disp[istation, 0] = spz[0] * np.cos(dist) - spz[2] * np.sin(dist) disp[istation, 1] = spz[1] disp[istation, 2] = spz[0] * np.sin(dist) + spz[2] * np.cos(dist) if args.norm: vtk = pyvtk.VtkData( vtk_points, pyvtk.PointData(pyvtk.Scalars(disp_norm, name='disp_norm')), 'surface animation') else: vtk = pyvtk.VtkData( vtk_points, pyvtk.PointData(pyvtk.Vectors(disp, name='disp_RTZ')), 'surface animation') vtk.tofile(args.out_vtk + '/surface_vtk.' + str(it) + '.vtk', 'binary') if args.verbose: print(' Done with snapshot t = %f s; tstep = %d / %d; iproc = %d' \ % (var_time[istep], it + 1, len(steps), iproc)) # close nc_surf_local.close() # remove temp nc if args.nproc > 1: os.remove(tempnc) if args.verbose and iproc == 0: elapsed = time.clock() - clock0 print('Generating snapshots done, ' + '%f sec elapsed.' % (elapsed))
def export_vtk_stress(filename, coords, topo, a=None, el_scalar=None, el_vec1=None, el_vec2=None): """ Export mesh and results for a 2D stress problem. Parameters: filename Filename of vtk-file coords Element coordinates (np.array) topo Element topology (not dof topology). mesh.topo. (np.array) a Element displacements 2-dof (np.array) el_scalar Scalar values for each element (list) el_vec1 Vector value for each element (list) el_vec2 Vector value for each element (list) """ points = coords.tolist() polygons = (topo - 1).tolist() displ = [] point_data = None scalars = None vectors1 = None vectors2 = None cell_data = None if a is not None: for i in range(0, len(a), 2): displ.append([np.asscalar(a[i]), np.asscalar(a[i + 1]), 0.0]) point_data = vtk.PointData(vtk.Vectors(displ, name="displacements")) if el_scalar is not None: scalars = vtk.Scalars(el_scalar, name="scalar") if el_vec1 is not None: vectors1 = vtk.Vectors(el_vec1, name="principal1") if el_vec2 is not None: vectors2 = vtk.Vectors(el_vec2, name="principal2") if el_scalar is not None and el_vec1 is None and el_vec2 is None: cell_data = vtk.CellData(scalars) if el_scalar is not None and el_vec1 is None and el_vec2 is not None: cell_data = vtk.CellData(scalars, vectors2) if el_scalar is not None and el_vec1 is not None and el_vec2 is None: cell_data = vtk.CellData(scalars, vectors1) if el_scalar is not None and el_vec1 is not None and el_vec2 is None: cell_data = vtk.CellData(scalars, vectors1, vectors2) if el_scalar is None and el_vec1 is None and el_vec2 is not None: cell_data = vtk.CellData(vectors2) if el_scalar is None and el_vec1 is not None and el_vec2 is None: cell_data = vtk.CellData(vectors1) if el_scalar is None and el_vec1 is not None and el_vec2 is None: cell_data = vtk.CellData(vectors1, vectors2) structure = vtk.PolyData(points=points, polygons=polygons) if cell_data is not None and point_data is not None: vtk_data = vtk.VtkData(structure, cell_data, point_data) if cell_data is None and point_data is not None: vtk_data = vtk.VtkData(structure, point_data) if cell_data is None and point_data is None: vtk_data = vtk.VtkData(structure) vtk_data.tofile("exm6.vtk", "ascii")
def make_vector(array, name=None): return pyvtk.Vectors(array, name)