Esempio n. 1
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. 2
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. 3
0
    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')
Esempio n. 4
0
def make_vtk(**kwargs):
    args = []
    if 'grid' in kwargs:
        args.append(kwargs.get('grid'))
    if 'point_data' in kwargs:
        data = kwargs['point_data']
        args.append(pyvtk.PointData(*data))
    if 'cell_data' in kwargs:
        data = kwargs['cell_data']
        args.append(pyvtk.CellData(*data))
    if 'header' in kwargs:
        args.append(kwargs.get('header'))
    return pyvtk.VtkData(*args)
Esempio n. 5
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. 6
0
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
points = list(zip(x, y, z))
Esempio n. 7
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. 8
0
#for inc in range(11):
#print inc
#fid = open('SkullPO_'+AA[inc]+'stress.log')
#SS = fid.read()
#SS = SS.split(strSplit)
#SS1 = SS[0]
#SS2 = SS[1]
#SS1 = SS1.split('\n')
#SS2 = SS2.split('\n')
#SS1 = SS1[0:1687791]
#SS2 = SS2[0:1687791]
#for i in range(1687791):
#SS1[i] = SS1[i].split(' ')
#SS2[i] = SS2[i].split(' ')
#ST1 = np.array(SS1,float)
#ST2 = np.array(SS2,float)
#Stress = np.c_[ST1[:,1:],ST2[:,1:]]
#vonMisses = np.sqrt(Stress[:,0]*Stress[:,0]+Stress[:,1]*Stress[:,1]+Stress[:,2]*Stress[:,2]-Stress[:,1]*Stress[:,2]-Stress[:,0]*Stress[:,2]-Stress[:,0]*Stress[:,1]+3*(Stress[:,3]*Stress[:,3]+Stress[:,4]*Stress[:,4]+Stress[:,5]*Stress[:,5]))
#Stress = np.c_[Stress,vonMisses]
#np.ma.dump(Stress,'Skull'+AA[inc]+'Stress')

Tet = np.ma.load('SkullPO_TetUse')
NC = np.ma.load('SkullPO_NC050')
for inc in range(11):
    print 'Skull ' + AA[inc] + ' on Average Shape'
    Stress = np.ma.load('Skull' + AA[inc] + 'Stress')
    print Stress[:, 6]
    skvtk = pv.VtkData(pv.UnstructuredGrid(points=NC, tetra=Tet),
                       'skull ' + AA[inc] + ' vM stress',
                       pv.CellData(pv.Scalars(Stress[:, 6], 'von Misses')))
    skvtk.tofile('SkullAver_' + AA[inc] + 'vM.vtk')
Esempio n. 9
0
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')
#vtk2 = VtkData('example1')t
Esempio n. 10
0
import numpy as np
import pyvtk as pv

### Von Mises of average stress tensor of P and O skulls
fname = 'SkullPO_AveragePO'
S = (np.ma.load('Skull100Stress')[:, 0:6] +
     np.ma.load('Skull000Stress')[:, 0:6]) / 2
NCS = (np.ma.load('SkullPO_NC100') + np.ma.load('SkullPO_NC000')) / 2
TetT = np.ma.load('SkullPO_TetUse')
VonM = np.sqrt(
    (np.power(S[:, 0] - S[:, 1], 2) + np.power(S[:, 1] - S[:, 2], 2) +
     np.power(S[:, 0] - S[:, 2], 2) + 6 *
     (S[:, 3] * S[:, 3] + S[:, 4] * S[:, 4] + S[:, 5] * S[:, 5])) / 2)
skvtk = pv.VtkData(pv.UnstructuredGrid(points=NCS, tetra=TetT),
                   'skull unique mesh',
                   pv.CellData(pv.Scalars(VonM, 'VonMises')))
skvtk.tofile(fname + '.vtk')
np.ma.dump(VonM, fname + 'VonMises')

### Von Mises of Difference in stress tensor for Average and Average between P and O
fname = 'SkullPO_AvPOminAverage'
S = S - np.ma.load('Skull050Stress')[:, 0:6]
NCS = np.ma.load('SkullPO_NC050')
TetT = np.ma.load('SkullPO_TetUse')
VonM = np.sqrt(
    (np.power(S[:, 0] - S[:, 1], 2) + np.power(S[:, 1] - S[:, 2], 2) +
     np.power(S[:, 0] - S[:, 2], 2) + 6 *
     (S[:, 3] * S[:, 3] + S[:, 4] * S[:, 4] + S[:, 5] * S[:, 5])) / 2)
skvtk = pv.VtkData(pv.UnstructuredGrid(points=NCS, tetra=TetT),
                   'skull unique mesh',
                   pv.CellData(pv.Scalars(VonM, 'VonMises')))