コード例 #1
0
ファイル: femModel.py プロジェクト: alphacheng/dxf_fem
    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")
コード例 #2
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
コード例 #3
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")
コード例 #4
0
    def __init__(self, mesh, header="", directory=".", filename="unnamed"):
        self.mesh = mesh
        self.directory = directory
        self.filename = filename

        if isinstance(mesh, HexagonalMesh):
            structure = pyvtk.PolyData(points=mesh.vertices,
                                       polygons=mesh.hexagons)
        elif isinstance(mesh, CuboidMesh):
            # for keyword argument dimensions: if the mesh is made up of
            # nx * ny * nz cells, it has (nx + 1) * (ny + 1) * (nz + 1)
            # vertices.
            structure = pyvtk.RectilinearGrid(*mesh.grid)
        else:
            raise NotImplementedError(
                "Mesh should be CuboidMesh or HexagonalMesh, is {}.".format(
                    mesh.__class__.__name__))
        self.structure = structure
        self.header = header

        self.init_VtkData(structure, header)
コード例 #5
0
def off_mesh_file_to_vtk(input_filename,
                         output_filename,
                         data_format="binary",
                         coord_transform=None):
    """Convert a mesh file from OFF format to VTK format"""
    print("Reading {}".format(input_filename))
    with gzip.open(input_filename, "rt") as f:
        header_keyword = f.readline().strip()
        match = re.match(r"(ST)?(C)?(N)?(4)?(n)?OFF", header_keyword)
        # TODO check features from header keyword
        assert match
        assert not match.group(5)  # nOFF is unsupported
        dimension_line = f.readline().strip()
        match = re.match(r"([+-]?[0-9]+)\s+([+-]?[0-9]+)(\s+([+-]?[0-9]+))?",
                         dimension_line)
        assert match
        num_vertices = int(match.group(1))
        num_triangles = int(match.group(2))
        vertices = np.empty((num_vertices, 3), dtype=np.float)
        for i in range(num_vertices):
            components = f.readline().split()
            assert len(components) >= 3
            vertices[i, 0] = float(components[0])
            vertices[i, 1] = float(components[1])
            vertices[i, 2] = float(components[2])
        triangles = np.empty((num_triangles, 3), dtype=np.int_)
        for i in range(num_triangles):
            components = f.readline().split()
            assert len(components) >= 4
            assert components[0] == "3"
            triangles[i, 0] = float(components[1])
            triangles[i, 1] = float(components[2])
            triangles[i, 2] = float(components[3])
    print()
    print("{0} vertices and {1} triangles read".format(num_vertices,
                                                       num_triangles))

    points = vertices

    if coord_transform is not None:
        if coord_transform.shape[0] == 4:
            assert np.all(coord_transform[3, :] == [0, 0, 0, 1])
        points = points.T
        points = np.dot(coord_transform[:3, :3], points)
        points += coord_transform[:3, 3, np.newaxis]
        points = points.T
        if np.linalg.det(coord_transform[:3, :3]) < 0:
            # Flip the triangles to fix inside/outside
            triangles = np.flip(triangles, axis=1)

    # Gifti uses millimetres, Neuroglancer expects nanometres
    points *= 1e6

    # Workaround: dtype must be np.int_ (pyvtk does not recognize int32 as
    # integers)
    triangles = triangles.astype(np.int_)

    vtk_mesh = pyvtk.PolyData(points, polygons=triangles)

    vtk_data = pyvtk.VtkData(
        vtk_mesh, "Converted using "
        "https://github.com/HumanBrainProject/neuroglancer-scripts")
    vtk_data.tofile(output_filename, format=data_format)
コード例 #6
0
ファイル: utils.py プロジェクト: bagustris/calfem-python
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")
コード例 #7
0
ファイル: pyvtk.py プロジェクト: hightower8083/opmd2VTK
    def write_species_vtk(self,
                          species=None,
                          iteration=0,
                          format='binary',
                          scalars=['ux', 'uy', 'uz', 'w'],
                          select=None,
                          zmin_fixed=None,
                          sample_ptcl=None):
        """
        Convert the given list of species from the openPMD format to
        a VTK container, and write it to the disk.

        Parameters
        ----------
        species: list or None
            List of species names to be converted. If None, it
            converts all available species provided by OpenPMDTimeSeries

        scalars: list of strings
            list of values associated with each paricle to be included.
            ex. : 'charge', 'id', 'mass', 'x', 'y', 'z', 'ux', 'uy', 'uz', 'w'

        iteration: int
            iteration number to treat (default 0)

        select: dict
            dictonary to impoer selection on the particles,
            as it is defined in opnePMD_viewer

        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

        sample_ptcl: integer or None
            If not None, the species arrays will be reduced by skipping
            elements
        """
        # Check available fields if comps is not defined
        if species is None:
            species = self.ts.avail_species

        # register constants
        self.iteration = iteration
        self.zmin_fixed = zmin_fixed
        self.select = select
        self.scalars = scalars

        if sample_ptcl is None:
            self.sample_ptcl = 1
        else:
            self.sample_ptcl = sample_ptcl

        # Make a numer string for the file to write
        istr = str(self.iteration)
        while len(istr) < 7:
            istr = '0' + istr
        name_base = self.path + 'vtk_specie_{:}_{:}'

        # Convert and save all the species
        for specie in species:
            points, scalars_to_add = self._get_species(specie)

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

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

            vtk.VtkData(pts_vtk, vtk.PointData(*scalars_vtk) )\
                .tofile(name_base.format(specie,istr), format=format)
コード例 #8
0
ファイル: vtkTest.py プロジェクト: nikolaikk/First_try
import sys
sys.path = ['..'] + sys.path

#from pyvtk import *
import pyvtk as vtk

structure = vtk.PolyData(points=[[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0],
                                 [0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]],
                         polygons=[[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4],
                                   [2, 3, 7, 6], [0, 4, 7, 3], [1, 2, 6, 5]])
pointdata = vtk.PointData(
    vtk.Scalars([0, 1, 2, 3, 4, 5, 6, 7],
                name='sample_scalars',
                lookup_table='my_table'),
    vtk.LookupTable([[0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1], [1, 1, 0, 1],
                     [0, 0, 1, 1], [1, 0, 1, 1], [0, 1, 1, 1], [1, 1, 1, 1]],
                    name='my_table'))

celldata = vtk.CellData(
    vtk.Scalars([0, 1, 2, 3, 4, 5], name='cell_scalars'),
    vtk.Normals(
        [[0, 0, -1], [0, 0, 1], [0, -1, 0], [0, 1, 0], [-1, 0, 0], [1, 0, 0]],
        name='cell_normals'),
    vtk.Field('FieldData',
              cellIds=[[0], [1], [2], [3], [4], [5]],
              faceAttributes=[[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]))

vtkdata = vtk.VtkData(structure, pointdata, celldata)
vtkdata.tofile('example1ascii', 'ascii')

#vtkdata.tofile('example1binary','binary')