Beispiel #1
0
 def write_vtk(self, filename):
     import pyvtk
     if self.mesh_type is "cube":
         vtkelements = pyvtk.VtkData(
             pyvtk.UnstructuredGrid(self.points, hexahedron=self.elements),
             "Mesh")
         vtkelements.tofile(filename)
Beispiel #2
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')
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
Beispiel #4
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))
Beispiel #5
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')
Beispiel #6
0
 def write_vtk(self, filename):
     import pyvtk
     vtkelements = pyvtk.VtkData(
         pyvtk.UnstructuredGrid(
             self.points,
             tetra=self.elements),
         "Mesh")
     vtkelements.tofile(filename)
Beispiel #7
0
    def inp2vtk(self, inp_file=''):
        """

        :rtype : object
        """
        if self._inp_file:
            inp_file = self._inp_file
        else:
            self._inp_file = inp_file

        if inp_file == '':
            sys.exit('ERROR: Please provide inp filename!')

        if self._vtk_file:
            vtk_file = self._vtk_file
        else:
            vtk_file = inp_file[:-4]

        self._vtk_file = vtk_file + '.vtk'

        print("--> Reading inp data")

        with open(inp_file, 'r') as f:
            line = f.readline()
            num_nodes = int(line.strip(' ').split()[0])
            num_elems = int(line.strip(' ').split()[1])

            coord = np.zeros((num_nodes, 3), 'float')
            elem_list_tri = []
            elem_list_tetra = []

            for i in range(num_nodes):
                line = f.readline()
                coord[i, 0] = float(line.strip(' ').split()[1])
                coord[i, 1] = float(line.strip(' ').split()[2])
                coord[i, 2] = float(line.strip(' ').split()[3])

            for i in range(num_elems):
                line = f.readline().strip(' ').split()
                line.pop(0)
                line.pop(0)
                elem_type = line.pop(0)
                if elem_type == 'tri':
                    elem_list_tri.append([int(i) - 1 for i in line])
                if elem_type == 'tet':
                    elem_list_tetra.append([int(i) - 1 for i in line])

        print('--> Writing inp data to vtk format')

        vtk = pv.VtkData(
            pv.UnstructuredGrid(coord,
                                tetra=elem_list_tetra,
                                triangle=elem_list_tri),
            'Unstructured pflotran grid')
        vtk.tofile(vtk_file)
Beispiel #8
0
def inp2vtk_python(self, inp_file=''):
    import pyvtk as pv
    """ Using Python VTK library, convert inp file to VTK file.  then change name of CELL_DATA to POINT_DATA.
    """
    print("--> Using Python to convert inp files to VTK files")
    if self._inp_file:
        inp_file = self._inp_file
    else:
        self._inp_file = inp_file

    if inp_file == '':
        sys.exit('ERROR: Please provide inp filename!')

    if self._vtk_file:
        vtk_file = self._vtk_file
    else:
        vtk_file = inp_file[:-4]
        self._vtk_file = vtk_file + '.vtk'

    print("--> Reading inp data")

    with open(inp_file, 'r') as f:
        line = f.readline()
        num_nodes = int(line.strip(' ').split()[0])
        num_elems = int(line.strip(' ').split()[1])

        coord = np.zeros((num_nodes, 3), 'float')
        elem_list_tri = []
        elem_list_tetra = []

        for i in range(num_nodes):
            line = f.readline()
            coord[i, 0] = float(line.strip(' ').split()[1])
            coord[i, 1] = float(line.strip(' ').split()[2])
            coord[i, 2] = float(line.strip(' ').split()[3])

        for i in range(num_elems):
            line = f.readline().strip(' ').split()
            line.pop(0)
            line.pop(0)
            elem_type = line.pop(0)
            if elem_type == 'tri':
                elem_list_tri.append([int(i) - 1 for i in line])
            if elem_type == 'tet':
                elem_list_tetra.append([int(i) - 1 for i in line])

    print('--> Writing inp data to vtk format')

    vtk = pv.VtkData(
        pv.UnstructuredGrid(coord,
                            tetra=elem_list_tetra,
                            triangle=elem_list_tri),
        'Unstructured pflotran grid')
    vtk.tofile(vtk_file)
Beispiel #9
0
    def getVTKRepresentation(self):
        """
        Get VTK representatnion of the mesh.

        return: VTK representation of the receiver. Requires pyvtk module.
        :rtype: pyvtk.UnstructuredGrid
        """
        import pyvtk

        vertices = []
        hexahedrons = []
        tetrahedrons = []
        quads = []
        triangles = []

        #loop over receiver vertices and create list of vertex coordinates
        for v in range(len(self.vertexList)):
            vertices.append(self.vertexList[v].coords)
        #loop over receiver cells
        for c in range(len(self.cellList)):
            cell = self.cellList[c]
            cgt = cell.getGeometryType()
            if (cgt == CellGeometryType.CGT_TRIANGLE_1):
                triangles.append(cell.vertices)
            elif (cgt == CellGeometryType.CGT_QUAD):
                quads.append(cell.vertices)
            elif (cgt == CellGeometryType.CGT_TETRA):
                tetrahedrons.append(cell.vertices)
            elif (cgt == CellGeometryType.CGT_HEXAHEDRON):
                hexahedrons.append(cell.vertices)
            elif (cgt == CellGeometryType.CGT_TRIANGLE_2):
                # no direct support in pyvtk. map it to linear tringles
                triangles.append(
                    (cell.vertices[0], cell.vertices[3], cell.vertices[5]))
                triangles.append(
                    (cell.vertices[1], cell.vertices[4], cell.vertices[3]))
                triangles.append(
                    (cell.vertices[2], cell.vertices[5], cell.vertices[4]))
                triangles.append(
                    (cell.vertices[3], cell.vertices[4], cell.vertices[5]))
            else:
                msg = "Unsupported cell geometry type encountered: " + str(cgt)
                raise APIError.APIError(msg)

        return pyvtk.UnstructuredGrid(vertices,
                                      hexahedron=hexahedrons,
                                      tetra=tetrahedrons,
                                      quad=quads,
                                      triangle=triangles)
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))
Beispiel #11
0
    def write2vtk(self, G):

        # import sys
        # sys.path = ['..'] + sys.path
        import pyvtk

        points = [list(node) for node, data in G.nodes(data=True)]
        line = []
        for edge in G.edges():
            for i, node in enumerate(G.nodes()):
                if node == edge[0]:
                    n1 = i
            for i, node in enumerate(G.nodes()):
                if node == edge[1]:
                    n2 = i
            line.append([n1, n2])

        vtk = pyvtk.VtkData(pyvtk.UnstructuredGrid(points, line=line))
        vtk.tofile('example1', 'ascii')
    def write2vtk(self, G, filename):
        """
        Exports a graph to a vtk file to be visualized with paraview
        """
        # import sys
        # sys.path = ['..'] + sys.path
        import pyvtk

        points = [list(node) for node, data in G.nodes(data=True)]
        line = []
        for edge in G.edges():
            for i, node in enumerate(G.nodes()):
                if node == edge[0]:
                    n1 = i
            for i, node in enumerate(G.nodes()):
                if node == edge[1]:
                    n2 = i
            line.append([n1, n2])

        vtk = pyvtk.VtkData(pyvtk.UnstructuredGrid(points, line=line))
        vtk.tofile(filename, 'ascii')
Beispiel #13
0
def write_vtk(filename, points, tetra, vals, name=None):
    """Writes a vtk from the given set of grid locations, values and connectivity

    :param points: An ndarray containing all the grid locations in cartesion coordinates
           in the form of:  | x0 y0 z0 |
                            | :  :  :  |
                            | xn yn zn |

    :param vals: an array containing the values to be specified on the mesh
    :param tetra: connectivity of the mesh

    """
    import pyvtk
    from pyvtk import PointData, Scalars
    vtkElements = pyvtk.VtkData(
                    pyvtk.UnstructuredGrid(
                    points,
                    tetra=tetra),
                    PointData(Scalars(vals, name)),
                    "Mesh")

    vtkElements.tofile(filename)
def make_grid(coords, connect, **kw):
    grid = None
    gridtype = kw.get('gridtype', 'unstructured')
    if gridtype == 'unstructured':
        (nex, ney) = connect
        (nx, ny) = (nex + 1, ney + 1)
        conn = numpy.zeros((nex * ney, 4), dtype=int)

        def node(i, j):
            return ny * i + j

        for i in xrange(nex):
            for j in xrange(ney):
                e = (ney) * i + j
                n1 = node(i, j)
                n2 = node(i + 1, j)
                n3 = node(i + 1, j + 1)
                n4 = node(i, j + 1)
                conn[e] = (n1, n2, n3, n4)
        grid = pyvtk.UnstructuredGrid(coords, quad=conn)
    else:
        raise Exception('Unknown grid type')
    return grid
Beispiel #15
0
pointPressure = np.random.rand(npoints)

# 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)
Beispiel #16
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)))
Beispiel #17
0
 def run(self):
     vtk = pyvtk.VtkData(\
         pyvtk.UnstructuredGrid(self.p.points,
                        hexahedron=self.p.cells),
         'm2v output')
     vtk.tofile('m2v_file')
Beispiel #18
0
    DegNd = DegNd.reshape((DegNd.size, ))
    DegRep = np.array(find_repeats(DegNd)[0], int)
    for i in DegRep:
        DegNd = DegNd[DegNd <> i]
    DegNd = np.r_[DegNd, DegRep]
    NCS[DegNd, ] = NCSprev[DegNd, ] + DS[DegNd, ]
    #DegNd = np.array(find_repeats(np.r_[DegNd,outer])[0],int)
    DegNd.sort()
    PointConst = np.zeros((NCS.shape[0], ))
    PointConst[outer, ] = 1
    PointConst[DegNd, ] = 0
    PointConst = np.array(PointConst, int)

    print 'Construct VTK object for optimization'
    ##ADD CONTRAINTS AS POINT SCALARS
    skvtk = pv.VtkData(pv.UnstructuredGrid(points=NCS, tetra=TetT),
                       'skull 4 symm',
                       pv.PointData(pv.Scalars(PointConst, 'fixed')))
    skvtk.tofile(fname[0:6] + '015constr.vtk')
    os.system('~/Software/Trilinos/Mesquite/msqshape -s ./' + fname[0:6] +
              '015constr.vtk ./' + fname[0:6] + '015constrOUT.vtk')

    fil = open(fname[0:6] + '015constrOUT.vtk', 'r+')
    fil.writelines('# vtk DataFile Version 2.0\n')
    fil.close()
    skvtk = pv.VtkData(fname[0:6] + '015constrOUT.vtk')
    NCS = np.array(skvtk.structure.points)
    NCSprev = np.r_[NCS]
    EQ, delt, Sn2, Sig = qu.elemQual_mu(np.array(range(TetT.shape[0])), NCS,
                                        TetT)
    print '					Average Element Quality: 	', np.average(EQ)
Beispiel #19
0
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}')
Beispiel #20
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
Beispiel #21
0
def inp2vtk_python(self):
    """ Using Python VTK library, convert inp file to VTK file.  

    Parameters
    ----------
        self : object 
            DFN Class

    Returns
    --------
        None

    Notes
    --------
        For a mesh base.inp, this dumps a VTK file named base.vtk
    """
    import pyvtk as pv
    if self.flow_solver != "PFLOTRAN":
        error = "ERROR! Wrong flow solver requested"
        sys.stderr.write(error)
        sys.exit(1)

    print("--> Using Python to convert inp files to VTK files")
    if self.inp_file:
        inp_file = self.inp_file

    if inp_file == '':
        error = 'ERROR: Please provide inp filename!'
        sys.stderr.write(error)
        sys.exit(1)

    if self.vtk_file:
        vtk_file = self.vtk_file
    else:
        vtk_file = inp_file[:-4]
        self.vtk_file = vtk_file + '.vtk'

    print("--> Reading inp data")

    with open(inp_file, 'r') as f:
        line = f.readline()
        num_nodes = int(line.strip(' ').split()[0])
        num_elems = int(line.strip(' ').split()[1])

        coord = np.zeros((num_nodes, 3), 'float')
        elem_list_tri = []
        elem_list_tetra = []

        for i in range(num_nodes):
            line = f.readline()
            coord[i, 0] = float(line.strip(' ').split()[1])
            coord[i, 1] = float(line.strip(' ').split()[2])
            coord[i, 2] = float(line.strip(' ').split()[3])

        for i in range(num_elems):
            line = f.readline().strip(' ').split()
            line.pop(0)
            line.pop(0)
            elem_type = line.pop(0)
            if elem_type == 'tri':
                elem_list_tri.append([int(i) - 1 for i in line])
            if elem_type == 'tet':
                elem_list_tetra.append([int(i) - 1 for i in line])

    print('--> Writing inp data to vtk format')
    vtk = pv.VtkData(
        pv.UnstructuredGrid(coord,
                            tetra=elem_list_tetra,
                            triangle=elem_list_tri),
        'Unstructured pflotran grid')

    vtk.tofile(vtk_file)
Beispiel #22
0
            ntpts += npts

            fi.close()

    data = np.array(datal, dtype=float).T
    elems = np.array(elems, dtype=int).T

    pl = []
    for i in np.arange(data.shape[1]):
        pl.append(tuple(data[:3, i]))

    el = []
    for i in np.arange(elems.shape[1]):
        el.append(tuple(elems[:, i]))

    grid = pyvtk.UnstructuredGrid(pl, tetra=el)

    pointdata = pyvtk.PointData()
    for j, var in enumerate(vars[3:]):
        pointdata.append(
            pyvtk.Scalars(data[j + 3, :].tolist(),
                          name=var,
                          lookup_table='default'))

    vtk = pyvtk.VtkData(grid, pointdata, title)
    if binary:
        vtk.tofile(t_step + '.vtk', 'binary')
    else:
        vtk.tofile(t_step + '.vtk', 'ascii')

    print t_step + '.vtk written'
Beispiel #23
0
#============================================================
#- Triangulation.
#============================================================

for i in range(0, m.shape[0]):
    S = m[i, :]
    outfile = outfilename + '.' + str(i) + '.vtk'
    print('Compute Delauney triangulation ...')

    x = 6371.0 * np.cos(lat * np.pi / 180.0) * np.cos(lon * np.pi / 180.0)
    y = 6371.0 * np.cos(lat * np.pi / 180.0) * np.sin(lon * np.pi / 180.0)
    z = 6371.0 * np.sin(lat * np.pi / 180.0)

    pts = np.array((x, y, z)).T
    mesh_info = MeshInfo()
    mesh_info.set_points(pts)
    opts = Options("Q")
    mesh = build(mesh_info, options=opts)
    elements = mesh.elements

    #============================================================
    #- Write vtk file.
    #============================================================

    print('Write vtk file ...')

    vtkElements = pyvtk.VtkData(pyvtk.UnstructuredGrid(pts, tetra=elements),
                                PointData(Scalars(S, 'grad_PSD_ZZ')), "Mesh")
    vtkElements.tofile(outfile)
Beispiel #24
0
num_steps = int((END_TSTEP - START_TSTEP) / INT_TSTEP)

#---------- </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')
# -2, -2, -2, -2, +2, -2, +2, +2, -2, +2, -2, -2, -2, -2, +2, +2, -2,
#         +2, +2, +2, +2, -2, +2, +2;


#
# specfem = Specfem(interp_method='trilinear_interpolation')
# first_element = specfem.connectivity[0,:]
# element_vtcs = specfem.nodes[first_element]
#
# permutation = [0,3,2,1,4,5,6,7] # looks like this is the correct one
# i = np.argsort(permutation)
# element_perturbed = first_element[i]
# element_vtcs = specfem.nodes[element_perturbed]
#
# #pnt = np.mean(element_vtcs, axis=0)
# pnt = (element_vtcs[4,:] + element_vtcs[6,:]) / 2
# solution = tlp.check_hull(pnt, element_vtcs)
# print(solution)
# print(tlp.interpolate_at_point(solution[1]))
#
import pyvtk
from pyvtk import PointData, Scalars
vtkElements = pyvtk.VtkData(pyvtk.UnstructuredGrid(
    specfem.nodes, hexahedron=specfem.connectivity),
    PointData(Scalars(grid_data.get_component('vsv'), 'node_number')),
               "Mesh")

vtkElements.tofile('specfem_mesh.vtk')

Beispiel #26
0
zmin = np.cos(np.radians(args.max_dist))
zmax = np.cos(np.radians(args.min_dist))
xyz, connect = SpherifiedCube(divisions, zmin, zmax)
nstation = len(xyz)
ncell = len(connect)
if args.verbose:
    elapsed = time.clock() - clock0
    print('    Number of sampling points: %d' % (nstation))
    print('    Number of quad cells: %d' % (ncell))
    print('Sampling surface done, ' + '%f sec elapsed.\n' % (elapsed))

###### generate mesh vtk
if args.verbose:
    clock0 = time.clock()
    print('Generating vtk mesh...')
vtk_points = pyvtk.UnstructuredGrid(list(zip(xyz[:, 0], xyz[:, 1], xyz[:, 2])),
                                    quad=connect)
if args.verbose:
    elapsed = time.clock() - clock0
    print('Generating vtk mesh done, ' + '%f sec elapsed.\n' % (elapsed))

###### dist, azim
if args.verbose:
    clock0 = time.clock()
    print('Computing (distances, azimuths) of points...')
# dists
dists = np.arccos(xyz[:, 2] / r_plot)
azims = np.arctan2(xyz[:, 1], xyz[:, 0])
if args.verbose:
    elapsed = time.clock() - clock0
    print('Computing (distances, azimuths) of points done, ' +
          '%f sec elapsed.\n' % (elapsed))
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"