Esempio n. 1
0
        def save_vtk(self, modei, scale):
            path = str(
                QFileDialog.getExistingDirectory(self,
                                                 "Select Directory")) + '/'
            print path

            U = self.MODOS.coord.copy()
            nnos = self.MODOS.nnos
            ngl = self.MODOS.ngl
            nodesr = self.MODOS.nodesr
            nodesl = list(set(range(nnos)) - set(nodesr))
            scale = float(scale)
            modei = int(modei) - 1
            g = self.MODOS.g
            U_i = zeros((nnos, g), float)
            U_i[nodesl] = self.MODOS.modo[:, modei].reshape(
                self.MODOS.modo[:, modei].size / g, g)
            Ux, Uy, Uz = U_i[:, 0].copy(), U_i[:, 1].copy(), U_i[:, 2].copy()
            U_i = U_i * scale
            U = U + U_i[:, :3]

            connec_face = self.MODOS.connec_face

            vtk = pyvtk.VtkData(
                pyvtk.UnstructuredGrid(U, triangle=connec_face),
                pyvtk.PointData(pyvtk.Scalars(Ux, name='Ux'),
                                pyvtk.Scalars(Uy, name='Uy'),
                                pyvtk.Scalars(Uz, name='Uz')))

            vtk.tofile(path + 'MODAL_' + str(modei + 1))
Esempio n. 2
0
 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)
Esempio n. 3
0
    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')
Esempio n. 4
0
 def visitPrint(self, k):
     """
     Uses PyVTK to write out data in a VisIt Visualization Tool capable format.
     """
     import pyvtk
     uVel = pyvtk.Scalars(self.fluid.u().flatten(), name='u')
     vVel = pyvtk.Scalars(self.fluid.v().flatten(), name='v')
     totp = pyvtk.Scalars(self.fluid.p().flatten(), name='p')
     celldat = pyvtk.PointData(uVel, vVel, totp)
     grid = pyvtk.RectilinearGrid(self.domain.x, self.domain.y,
                                  self.domain.z)
     vtk = pyvtk.VtkData(grid, celldat)
     vtk.tofile('data%i' % k)
Esempio n. 5
0
    def exportVtk(self, filename):
        """Method for exporting fem calculation output to VTK-compatible format"""
        print("Exporting results to '%s'..." % filename)

        # --- Create points and polygon definitions from our node network
        points = self.outputData.coords.tolist()

        # --- Make sure topology is VTK-compatible; i.e.: 0-based
        #polygons = (self.outputData.edof-1).tolist()
        topo = np.zeros([self.outputData.edof.shape[0], 3], dtype=int)
        for i in range(self.outputData.edof.shape[0]):
            topo[i, 0] = self.outputData.edof[i, 1] / 2 - 1
            topo[i, 1] = self.outputData.edof[i, 3] / 2 - 1
            topo[i, 2] = self.outputData.edof[i, 5] / 2 - 1

        polygons = (topo).tolist()

        # --- Specify both vector and scalar data for each element
        #pointData = vtk.PointData(vtk.Scalars(self.outputData.a.tolist(), name="Displacement"))
        #cellData = vtk.CellData(vtk.Scalars(max(self.outputData.stress), name="maxvmstress"),\
        #                        vtk.Vectors(self.outputData.stress, "stress"))
        cellData = vtk.CellData(
            vtk.Scalars(self.outputData.stress, name="Von Mises"))

        # --- Create the structure of the element network
        structure = vtk.PolyData(points=points, polygons=polygons)

        # --- Store everything in a vtk instance
        #vtkData = vtk.VtkData(structure, pointData, cellData)
        vtkData = vtk.VtkData(structure, cellData)

        # --- Save the data to the specified file
        vtkData.tofile(filename, "ascii")
Esempio n. 6
0
def numpy2vtkgrid_file(outfilename,
                       xmin,
                       xmax,
                       ymin,
                       ymax,
                       numpy_matrix,
                       zlevel=0.0,
                       vtk_format='ascii',
                       vtkfilecomment="Created with numpy2vtkgrid",
                       vtkdatacomment="Scalar field"):
    assert len(numpy_matrix.shape) == 2,\
           "data needs to be 2d, but shape is '%s'" % numpy_matrix.shape

    nx, ny = numpy_matrix.shape

    xpos = numpy.linspace(xmin, xmax, nx)
    ypos = numpy.linspace(ymin, ymax, ny)

    print "point set = %d*%d=%d" % (nx, ny, nx * ny)

    vtk = pyvtk.VtkData(
        pyvtk.RectilinearGrid(\
            xpos.tolist(),ypos.tolist(),[zlevel]
            ),
        vtkfilecomment,
        pyvtk.PointData(
             pyvtk.Scalars( numpy_matrix.flatten().tolist(),
                            vtkdatacomment )
             ),
        format=vtk_format
        )
    vtk.tofile(outfilename, format=vtk_format)
Esempio n. 7
0
    def _convert_field_scl(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
        -------
        scl: vtk.Scalars
            VTK scalar containter
        """
        # 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
        elif self.geom=='thetaMode':
            get_field = self._get_opmd_field_circ
            make_mesh = self._make_vtk_mesh_circ

        fld_data, self.info = get_field(fld)
        make_mesh()
        scl = vtk.Scalars(fld_data, name=fld)
        return scl
Esempio n. 8
0
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)
Esempio n. 9
0
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
Esempio n. 10
0
def test_tet_mesh(visualize=False):
    pytest.importorskip("meshpy")

    from math import pi, cos, sin
    from meshpy.tet import MeshInfo, build
    from meshpy.geometry import \
            GeometryBuilder, generate_surface_of_revolution, EXT_CLOSED_IN_RZ

    pytest.importorskip("meshpy")

    big_r = 3
    little_r = 1.5

    points = 50
    dphi = 2 * pi / points

    rz = np.array(
        [[big_r + little_r * cos(i * dphi), little_r * sin(i * dphi)]
         for i in range(points)])

    geo = GeometryBuilder()
    geo.add_geometry(*generate_surface_of_revolution(
        rz, closure=EXT_CLOSED_IN_RZ, radial_subdiv=20))

    mesh_info = MeshInfo()
    geo.set(mesh_info)

    mesh = build(mesh_info)

    def tet_face_vertices(vertices):
        return [
            (vertices[0], vertices[1], vertices[2]),
            (vertices[0], vertices[1], vertices[3]),
            (vertices[0], vertices[2], vertices[3]),
            (vertices[1], vertices[2], vertices[3]),
        ]

    face_map = {}
    for el_id, el in enumerate(mesh.elements):
        for fid, face_vertices in enumerate(tet_face_vertices(el)):
            face_map.setdefault(frozenset(face_vertices), []).append(
                (el_id, fid))

    adjacency = {}
    for face_vertices, els_faces in face_map.items():
        if len(els_faces) == 2:
            (e1, f1), (e2, f2) = els_faces
            adjacency.setdefault(e1, []).append(e2)
            adjacency.setdefault(e2, []).append(e1)

    cuts, part_vert = pymetis.part_graph(17, adjacency)

    if visualize:
        import pyvtk

        vtkelements = pyvtk.VtkData(
            pyvtk.UnstructuredGrid(mesh.points, tetra=mesh.elements), "Mesh",
            pyvtk.CellData(pyvtk.Scalars(part_vert, name="partition")))
        vtkelements.tofile('split.vtk')
Esempio n. 11
0
 def writeVTK(self, filename):
     import pyvtk
     origin = N.array([self.x_axis[0], self.y_axis[0], self.z_axis[0]])
     spacing = N.array([self.x_axis[1], self.y_axis[1], self.z_axis[1]]) \
               - origin
     values = pyvtk.Scalars(N.ravel(N.transpose(self.data)),
                            'electron density')
     data = pyvtk.VtkData(
         pyvtk.StructuredPoints(self.data.shape, origin, spacing),
         'Density map', pyvtk.PointData(values))
     data.tofile(filename, format='binary')
Esempio n. 12
0
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)))
Esempio n. 13
0
    def _convert_species(self, species):
        """
        Convert the given species from the openPMD format to a VTK container.

        Parameters
        ----------
        species: str
            Name of the specis
            ex. : 'electrons', 'He+1'

        Returns
        -------
        pts_vtk: vtk.PolyData
            VTK PolyData container with the particles 3D positions

        scalars_vtk: list of vtk.Scalars
            List of scalars associated with the particles
        """
        # Get the particle data
        pts = self.ts.get_particle(var_list=['x', 'y', 'z']+self.scalars,
                                   species=species, iteration=self.iteration,
                                   select=self.select)

        # Split coordinates and scalars
        coords = np.array(pts[:3]).astype(self.dtype).T
        scalars_to_add = pts[3:]

        # Convert microns to meters
        # Note: in further release of openPMD-viewer, coords
        #       are expected to be meters by default
        coords *= 1e-6

        # If zmin_fixed mode is chosen, shift the z-coordinates
        # to match the fields box
        if self.zmin_fixed is not None:
            if self.zmin_orig is None:
                print('zmin_fixed mode can only be use after the fields')
            else:
                coords[:,2] -= self.zmin_orig - self.zmin_fixed

        # Create the points container
        pts_vtk = vtk.PolyData(coords)

        # Create the scalars containers
        scalars_vtk = []
        for i, scalar in enumerate(scalars_to_add):
            scalars_vtk.append(vtk.Scalars(scalar.astype(self.dtype),
                               name=self.scalars[i]))

        return pts_vtk, scalars_vtk
Esempio n. 14
0
def savevtk(v, fn='', lons=[], lats=[], levels=[]):
    """save tracer field into vtk format,
    """
    import pyvtk

    def norm(c):
        return (c - c[0]) / (c[-1] - c[0])

    z = levels / abs(levels).max() * (lons.max() - lons.min()) * 0.7

    point_data = pyvtk.PointData(pyvtk.Scalars(v.T.flatten()))
    vtk_object = pyvtk.VtkData(pyvtk.RectilinearGrid(x=lons, y=lats, z=z),
                               point_data)
    vtk_object.tofile(fn)
    return
Esempio n. 15
0
def plot_vtk(A, V, partition) :
   V = numpy.append( V, numpy.zeros((A.shape[0],1)), axis=1 )

   triples = []
   A = scipy.sparse.triu(A,k=1).tocsr()
   for i in range(A.shape[0]-1):
      row = A.indices[A.indptr[i]:A.indptr[i+1]].tolist()
      for t1,t2 in itertools.combinations(row, 2) :
	if A[t1,t2] : 
	   triples.append((i,t1,t2))

   vtkelements = pyvtk.VtkData(
       pyvtk.UnstructuredGrid(V, triangle=triples),
       "Mesh",
       pyvtk.PointData(pyvtk.Scalars(partition, name="partition")))
   vtkelements.tofile('{0}_{1}.vtk'.format(graph_name,num_parts))
Esempio n. 16
0
    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")
Esempio n. 17
0
    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)
Esempio n. 18
0
    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
Esempio n. 19
0
def export_paraview(self):
    if self.export_paraview == 0:
        self.vtk_points = [_v.coord for _v in self.vertices[1:]]
        self.vtk_triangle = [[
            _e.vertices[0].tag - 1, _e.vertices[1].tag - 1,
            _e.vertices[2].tag - 1
        ] for _e in self.elements[1:] if _e.typ == 2]
    pressure = [np.abs(_v.sol[3]) for _v in self.vertices[1:]]

    # Bidouille pour que la tour et les lettres clignotent dans IAGS 20201
    pressure_max = max(pressure)
    light_on = self.export_paraview % 4
    if light_on < 2:
        tower_on = 0
    else:
        tower_on = 1

    for _ent in self.fem_entities:
        if _ent.dim == 2:
            if _ent.mat.MEDIUM_TYPE == "eqf":
                if _ent.mat.name == "tower":
                    for _elem in _ent.elements:
                        for _v in _elem.vertices:
                            _v.sol[3] = (1 +
                                         (-1)**tower_on) * (pressure_max / 2.)
                if _ent.mat.name == "letter":
                    for _elem in _ent.elements:
                        for _v in _elem.vertices:
                            _v.sol[3] = (1 + (-1)**
                                         (tower_on + 1)) * (pressure_max / 2.)

    pressure = [np.abs(_v.sol[3]) for _v in self.vertices[1:]]
    vtk = pyvtk.VtkData(
        pyvtk.UnstructuredGrid(self.vtk_points, triangle=self.vtk_triangle),
        pyvtk.PointData(pyvtk.Scalars(pressure, name='Pressure')))
    vtk.tofile("vtk/" + self.name_project + "-{}".format(self.export_paraview))
    self.export_paraview += 1
    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
Esempio n. 21
0
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")
Esempio n. 22
0
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
Esempio n. 23
0
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))
Esempio n. 24
0
#---------- </LOAD VARIABLES> ----------

#---------- <CREATE VTK FILE> ----------

wc = WavefieldComputer(wavefield, nu, s, z, sem_mesh)

for i_slice in range(SLICES):
    x_slice, y_slice, z_slice, wvf_slice = wc.compute_slice(
        RMIN[i_slice], RMAX[i_slice], PHIS_SLICES[i_slice])
    points_slice = list(zip(x_slice, y_slice, z_slice))
    range_slice = range(len(x_slice))
    for it in range(num_steps):
        vtk = pyvtk.VtkData(
            pyvtk.UnstructuredGrid(points_slice, range_slice),
            pyvtk.PointData(
                pyvtk.Scalars(wvf_slice[it], name='wavefield_slice')),
            'animation')
        vtk.tofile(OUTPUT_DIR + 'slices/' + 'slice_' +
                   str(int(RMIN[i_slice] * 1.e-3)) + '_' +
                   str(int(RMAX[i_slice] * 1.e-3)) + '_' +
                   str(PHIS_SLICES[i_slice]) + '_' + str(it) + '.vtk')

    ### write info file for each slice
    f = open(
        OUTPUT_DIR + 'slices/'
        'slice_' + str(int(RMIN[i_slice] * 1.e-3)) + '_' +
        str(int(RMAX[i_slice] * 1.e-3)) + '_' + str(PHIS_SLICES[i_slice]) +
        '_INFO.txt', 'w')
    f.write('########## SLICE INFO ##########\n')
    f.write('PHI (degrees) ' + str(PHIS_SLICES[i_slice]) + '\n')
    f.write('RMIN (m) ' + str(RMIN[i_slice]) + '\n')
Esempio n. 25
0
    def _getStructure(self):

        ##maxX = self.distanceVar.mesh.faceCenters[0].max()
        ##minX = self.distanceVar.mesh.faceCenters[0].min()

        IDs = numerix.nonzero(self.distanceVar._cellInterfaceFlag)[0]
        coordinates = numerix.take(
            numerix.array(self.distanceVar.mesh.cellCenters).swapaxes(0, 1),
            IDs)

        coordinates -= numerix.take(
            numerix.array(self.distanceVar.grad * self.distanceVar).swapaxes(
                0, 1), IDs)

        coordinates *= self.zoomFactor

        shiftedCoords = coordinates.copy()
        shiftedCoords[:, 0] = -coordinates[:, 0]  ##+ (maxX - minX)
        coordinates = numerix.concatenate((coordinates, shiftedCoords))

        from lines import _getOrderedLines

        lines = _getOrderedLines(
            range(2 * len(IDs)),
            coordinates,
            thresholdDistance=self.distanceVar.mesh._cellDistances.min() * 10)

        data = numerix.take(self.surfactantVar, IDs)

        data = numerix.concatenate((data, data))

        tmpIDs = numerix.nonzero(data > 0.0001)[0]
        if len(tmpIDs) > 0:
            val = numerix.take(data, tmpIDs).min()
        else:
            val = 0.0001

        data = numerix.where(data < 0.0001, val, data)

        for line in lines:
            if len(line) > 2:
                for smooth in range(self.smooth):
                    for arr in (coordinates, data):
                        tmp = numerix.take(arr, line)
                        tmp[1:-1] = tmp[2:] * 0.25 + tmp[:-2] * 0.25 + tmp[
                            1:-1] * 0.5
                        if len(arr.shape) > 1:
                            for i in range(len(arr[0])):
                                arrI = arr[:, i].copy()
                                numerix.put(arrI, line, tmp[:, i])
                                arr[:, i] = arrI
                        else:
                            numerix.put(arrI, line, tmp)

        name = self.title
        name = name.strip()
        if name == '':
            name = None

        coords = numerix.zeros((coordinates.shape[0], 3), 'd')
        coords[:, :coordinates.shape[1]] = coordinates

        import pyvtk

        ## making lists as pyvtk doesn't know what to do with numpy arrays

        coords = list(coords)
        coords = map(
            lambda coord: [float(coord[0]),
                           float(coord[1]),
                           float(coord[2])], coords)

        data = list(data)
        data = map(lambda item: float(item), data)

        return (pyvtk.UnstructuredGrid(points=coords, poly_line=lines),
                pyvtk.PointData(pyvtk.Scalars(data, name=name)))
Esempio n. 26
0
 def save_scalar(self, s, name="my_field", step=0):
     self.vtk_data.cell_data.append(pyvtk.Scalars(s, name))
Esempio n. 27
0
# Compute the 2D Delaunay triangulation in the x-y plane
xTmp = list(zip(x, y))
tri = Delaunay(xTmp)

# Generate Cell Data
nCells = tri.nsimplex
cellTemp = np.random.rand(nCells)

# Zip the point co-ordinates for the VtkData input
points = list(zip(x, y, z))

vtk = pyvtk.VtkData(\
  pyvtk.UnstructuredGrid(points,
    triangle=tri.simplices
    ),
pyvtk.PointData(pyvtk.Scalars(pointPressure,name='Pressure')),
pyvtk.CellData(pyvtk.Scalars(cellTemp,name='Temperature')),
'2D Delaunay Example'
                    )
vtk.tofile('Delaunay2D')
vtk.tofile('Delaunay2Db', 'binary')

# Compute the 3D Delaunay triangulation in the x-y plane
xTmp = list(zip(x, y, z))
tri = Delaunay(xTmp)

# Generate Cell Data
nCells = tri.nsimplex
cellTemp = np.random.rand(nCells)

# Zip the point co-ordinates for the VtkData input
Esempio n. 28
0
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
        disp_curl = np.zeros(nstation)
        eleTag_last = -1
        fourier_last = None
        for istation, dist in enumerate(dists):
            # poles cannot be computed correctly
            if (dist < delta or dist > np.pi - delta):
                disp_curl[istation] = 0.
                continue
            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)
            wdotf1 = 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)
                wdotf1[idim] = weights1[istation].dot(fmat)
            exparray = 2. * np.exp(np.arange(0, nu_p_1) * 1j * azims[istation])
            exparray[0] = 1.
            exparray1 = 2. * np.exp(
                np.arange(0, nu_p_1) * 1j * (azims[istation] + delta))
            exparray1[0] = 1.
            spz = wdotf.dot(exparray).real
            spz_dist1 = wdotf1.dot(exparray).real
            spz_azim1 = wdotf.dot(exparray1).real
            uR = spz[0] * np.cos(dist) - spz[2] * np.sin(dist)
            uR_azim1 = spz_azim1[0] * np.cos(dist) - spz_azim1[2] * np.sin(
                dist)
            duR = (uR_azim1 - uR) / delta / np.sin(dist)
            uT = spz[1]
            uT_dist1 = spz_dist1[1]
            duT = (uT_dist1 - uT) / (dists1[istation] - dist)
            disp_curl[istation] = duR - duT
        vtk = pyvtk.VtkData(
            vtk_points,
            pyvtk.PointData(pyvtk.Scalars(disp_curl, name='disp_curl')),
            'surface animation')
        vtk.tofile(args.out_vtk + '/surface_vtk_zcurl.' + 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))
Esempio n. 29
0
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)))
Esempio n. 30
0
# generate the data.
from numpy import *
import scipy
x = (arange(50.0) - 25) / 2.0
y = (arange(50.0) - 25) / 2.0
r = sqrt(x**2 + y**2)
z = x * 5.0 * sin(x)  # Bessel function of order 0
# now dump the data to a VTK file.
import pyvtk
# Flatten the 2D array data as per VTK's requirements.
z1 = reshape(transpose(z), (-1, ))
point_data = pyvtk.PointData(pyvtk.Scalars(z1))
grid = pyvtk.StructuredPoints((50, 50, 1), (-12.5, -12.5, 0), (0.5, 0.5, 1))
data = pyvtk.VtkData(grid, point_data)
data.tofile('/tmp/test.vtk')