Lisandro Dalcin avatar Lisandro Dalcin committed 321ec90

initial import

Comments (0)

Files changed (12)

+include makefile
+
+=======================
+README: PyVTK2
+=======================
+
+:Author:       Lisandro Dalcin
+:Organization: CIMEC_
+:Address:      PTLC, 3000 Santa Fe, Argentina
+:Contact:      dalcinl@gmail.com
+
+.. _CIMEC:            http://www.cimec.org.ar/
+# -*- makefile -*-
+
+.PHONY: default build install sdist clean distclean
+
+PYTHON = python
+
+default: build
+
+build:
+	${PYTHON} setup.py build ${BUILDOPT}
+
+install: build
+	${PYTHON} setup.py install --home=${HOME}
+
+sdist:
+	${PYTHON} setup.py sdist
+
+clean:
+	${PYTHON} setup.py clean --all
+
+distclean: clean 
+	-${RM} `find . -name '*~'`
+	-${RM} -r MANIFEST build dist *.egg-info
+[sdist]
+force_manifest=1
+# !/usr/bin/env python
+
+metadata = dict(
+    keywords = ['VTK'],
+    classifiers=[
+    'Development Status :: 3 - Alpha',
+    'Intended Audience :: Science/Research',
+    'License :: OSI Approved',
+    'Natural Language :: English',
+    'Operating System :: OS Independent',
+    'Programming Language :: Python',
+    'Topic :: Scientific/Engineering :: Visualization',
+    ],
+    platforms = 'All',
+    )
+
+from distutils.core import setup
+
+setup(name = "PyVTK2",
+      version = '0.0.1',
+      description = "PyVTK2 - tools for writing VTK files in Python",
+      url = 'http://example.com/',
+      author = "Lisandro Dalcin",
+      author_email = "dalcinl@gmail.com",
+      packages = ['pyvtk2'],
+      package_dir = {'pyvtk2': 'src'},
+      **metadata)
+      
+# --------------------------------------------------------------------
+
+from numpy \
+     import core as _npy
+
+def _file_is_binary(fd):
+    return ('b' in fd.mode)
+
+def _array_is_little_endian(array):
+    _le = _npy.little_endian
+    _bo = array.dtype.byteorder
+    return (_le and (_bo == '=')) or (_bo == '<')
+
+def _array_as_big_endian(array):
+    if _array_is_little_endian(array):
+        array = array.byteswap()
+    return array
+
+def _dump_array(array, fd):
+    _as_binary = _file_is_binary(fd)
+    if _as_binary:
+        array = _array_as_big_endian(array)
+    array.tofile(fd, sep=' ' * (not _as_binary))
+
+# --------------------------------------------------------------------
+
+class DataSet(object):
+
+    dataset_type = None
+
+    def dump(self, fd):
+        self.dump_head(fd)
+        self.dump_body(fd)
+        self.dump_tail(fd)
+
+    def dump_head(self, fd):
+        fd.write('DATASET %s' % self.dataset_type)
+        fd.write('\n')
+
+    def dump_body(self, fd):
+        raise NotImplementedError
+
+    def dump_tail(self, fd):
+        pass
+
+# --------------------------------------------------------------------
+
+class DataSetAttr(object):
+
+    attr_type = None
+    attr_size = None
+
+    data_type = 'double'
+    npy_dtype = _npy.float64
+
+    def __init__(self, data, name=None):
+        data_array = _npy.asarray(data, dtype=self.npy_dtype)
+        data_array = data_array.reshape(-1, self.attr_size)
+        self.data_array = data_array
+        if name is not None:
+            assert isinstance(name, str)
+            name = name.strip()
+            assert len(name) > 0
+            self.attr_name = name.replace(' ','_')
+        else:
+            name = str(self.attr_type).lower()
+            self.attr_name = name
+
+    def __len__(self):
+        return len(self.data_array)
+
+    def dump(self, fd):
+        self.dump_head(fd)
+        self.dump_body(fd)
+        self.dump_tail(fd)
+
+    def dump_head(self, fd):
+        header = '%s %s %s' % \
+                 (self.attr_type, self.attr_name, self.data_type)
+        fd.write(header)
+        fd.write('\n')
+
+    def dump_body(self, fd):
+        _dump_array(self.data_array, fd)
+        fd.write('\n')
+
+    def dump_tail(self, fd):
+        pass
+
+class LookupTable(DataSetAttr):
+    attr_type = 'LOOKUP_TABLE'
+    attr_size = 4
+
+    def __init__(self, data, name=None):
+        DataSetAttr.__init__(self, data, name)
+        assert self.data_array.min() >= 0
+        assert self.data_array.max() <= 1
+
+    def dump_head(self, fd):
+        header = '%s %s %d' % \
+                 (self.attr_type, self.attr_name, len(self))
+        fd.write(header)
+        fd.write('\n')
+
+    def dump_body(self, fd):
+        data = self.data_array
+        if _file_is_binary(fd):
+            data = data * 255
+            data.round(out=data)
+            data = data.astype('uint8')
+        _dump_array(data, fd)
+        fd.write('\n')
+
+class Scalars(DataSetAttr):
+    attr_type = 'SCALARS'
+    attr_size = 1
+
+    lookup_table = 'default'
+
+    def __init__(self, data, name=None, lookup_table=None):
+        DataSetAttr.__init__(self, data, name)
+        if lookup_table is not None:
+            assert isinstance(lookup_table, str)
+            lookup_table = lookup_table.strip()
+            assert len(lookup_table) > 0
+            self.lookup_table = lookup_table.replace(' ','_')
+
+    def dump_head(self, fd):
+        DataSetAttr.dump_head(self, fd)
+        fd.write('LOOKUP_TABLE %s' % self.lookup_table)
+        fd.write('\n')
+
+class Vectors(DataSetAttr):
+    attr_type = 'VECTORS'
+    attr_size = 3
+
+class Normals(DataSetAttr):
+    attr_type = 'NORMALS'
+    attr_size = 3
+
+class Tensors(DataSetAttr):
+    attr_type = 'TENSORS'
+    attr_size = 9
+
+# --------------------------------------------------------------------
+
+class DataSetAttrList(list):
+
+    data_type = None
+
+    def __init__(self, *sequence):
+        list.__init__(self)
+        for item in sequence:
+            assert isinstance(item, DataSetAttr)
+            assert len(item) == len(sequence[0])
+        self.extend(sequence)
+
+    def dump(self, fd):
+        if not self: return
+        self.dump_head(fd)
+        self.dump_body(fd)
+        self.dump_tail(fd)
+
+    def dump_head(self, fd):
+        header = '%s %d' % (self.data_type, len(self[0]))
+        fd.write(header)
+        fd.write('\n')
+
+    def dump_body(self, fd):
+        for item in self:
+            item.dump(fd)
+
+    def dump_tail(self, fd):
+        pass
+
+class PointData(DataSetAttrList):
+    data_type = 'POINT_DATA'
+
+class CellData(DataSetAttrList):
+    data_type = 'CELL_DATA'
+
+# --------------------------------------------------------------------
+
+__all__ =   [ ] \
+          + [cls.__name__ for cls in DataSetAttr.__subclasses__()] \
+          + [cls.__name__ for cls in DataSetAttrList.__subclasses__()]
+
+# --------------------------------------------------------------------

src/RectilinearGrid.py

+# --------------------------------------------------------------------
+
+from numpy \
+     import core as _npy
+
+from DataSet \
+     import DataSet, _dump_array
+
+# --------------------------------------------------------------------
+
+class RectilinearGrid(DataSet):
+
+    dataset_type = 'RECTILINEAR_GRID'
+
+    data_type = 'double'
+    npy_dtype = _npy.float64
+
+    def __init__(self, x=(0,), y=(0,), z=(0,)):
+        x = _npy.asarray(x, dtype=self.npy_dtype).reshape(-1)
+        y = _npy.asarray(y, dtype=self.npy_dtype).reshape(-1)
+        z = _npy.asarray(z, dtype=self.npy_dtype).reshape(-1)
+        assert len(x) > 0
+        assert len(y) > 0
+        assert len(z) > 0
+        self.x = x
+        self.y = y
+        self.z = z
+
+    def dump_body(self, fd):
+        nx, ny, nz = (len(self.x), len(self.y), len(self.z))
+        fd.write('DIMENSIONS %d %d %d' % (nx, ny, nz))
+        fd.write('\n')
+        for axis in ('X', 'Y', 'Z'):
+            ax = getattr(self, axis.lower())
+            fd.write('%s_COORDINATES %d %s' % \
+                     (axis, len(ax), self.data_type))
+            fd.write('\n')
+            _dump_array(ax, fd)
+            fd.write('\n')
+
+# --------------------------------------------------------------------
+
+__all__ = ['RectilinearGrid']
+
+# --------------------------------------------------------------------

src/StructuredGrid.py

+# --------------------------------------------------------------------
+
+from numpy \
+     import core as _npy
+
+from DataSet \
+     import DataSet
+
+from UnstructuredGrid \
+     import PointSet
+
+# --------------------------------------------------------------------
+
+class StructuredGrid(DataSet):
+
+    dataset_type = 'STRUCTURED_GRID'
+
+    def __init__(self, dimensions, points):
+        dimensions = tuple(dimensions)
+        points     = PointSet(points)
+        assert len(points) == _npy.product(dimensions)
+        self.dimensions = dimensions
+        self.points     = points
+
+    def dump_body(self, fd):
+        fd.write('DIMENSIONS %d %d %d' % self.dimensions)
+        fd.write('\n')
+        self.points.dump(fd)
+
+# --------------------------------------------------------------------
+
+__all__ = ['StructuredGrid']
+
+# --------------------------------------------------------------------

src/StructuredPoints.py

+# --------------------------------------------------------------------
+
+from DataSet \
+     import DataSet
+
+# --------------------------------------------------------------------
+
+class StructuredPoints(DataSet):
+
+    dataset_type = 'STRUCTURED_POINTS'
+
+    def __init__(self, dimensions, origin=(0,0,0), spacing=(1,1,1)):
+        dimensions = tuple(dimensions)
+        origin     = tuple(origin)
+        spacing    = tuple(spacing)
+        assert len(dimensions) == 3
+        assert len(origin) == 3
+        assert len(spacing) == 3
+        self.dimensions = dimensions
+        self.origin     = origin
+        self.spacing    = spacing
+
+    def dump_body(self, fd):
+        fd.write('DIMENSIONS %d %d %d' % self.dimensions)
+        fd.write('\n')
+        fd.write('ORIGIN %g %g %g' % self.origin)
+        fd.write('\n')
+        fd.write('SPACING %g %g %g' % self.spacing)
+        fd.write('\n')
+
+# --------------------------------------------------------------------
+
+__all__ = ['StructuredPoints']
+
+# --------------------------------------------------------------------

src/UnstructuredGrid.py

+# --------------------------------------------------------------------
+
+from numpy \
+     import core as _npy
+
+from DataSet \
+     import DataSet, _dump_array
+
+# --------------------------------------------------------------------
+
+class UnstructuredGrid(DataSet):
+
+    dataset_type = 'UNSTRUCTURED_GRID'
+
+    def __init__(self, points, *cells):
+        self.points = PointSet(points)
+        self.cells  = CellSetList(cells)
+
+    def dump_body(self, fd):
+        self.points.dump(fd)
+        self.cells.dump(fd)
+
+# --------------------------------------------------------------------
+
+class PointSet(object):
+
+    data_type = 'double'
+    npy_dtype = _npy.float64
+
+    def __init__(self, data):
+        point_array = _npy.asarray(data, dtype=self.npy_dtype)
+        point_array = point_array.reshape(-1, 3)
+        self.point_array = point_array
+
+    def __len__(self):
+        return len(self.point_array)
+
+    def dump(self, fd):
+        self.dump_head(fd)
+        self.dump_body(fd)
+        self.dump_tail(fd)
+
+    def dump_head(self, fd):
+        fd.write('POINTS %d %s' % (len(self), self.data_type))
+        fd.write('\n')
+
+    def dump_body(self, fd):
+        _dump_array(self.point_array, fd)
+        fd.write('\n')
+
+    def dump_tail(self, fd):
+        pass
+
+
+class CellSetList(list):
+
+    data_type = 'int'
+    npy_dtype = _npy.int32
+
+    def __init__(self, sequence):
+        for item in sequence:
+            assert isinstance(item, CellSet)
+        self.extend(sequence)
+
+    def dump(self, fd):
+        if not self: return
+        self.dump_head(fd)
+        self.dump_body(fd)
+        self.dump_tail(fd)
+
+    def dump_head(self, fd):
+        pass
+
+    def dump_body(self, fd):
+        nc = sc = 0
+        for item in self:
+            nn = len(item)
+            nc += nn
+            sc += item.size + nn
+        fd.write('CELLS %d %s' % (nc, sc))
+        fd.write('\n')
+        for item in self:
+            item.dump_data(fd)
+        fd.write('CELL_TYPES %d' % nc)
+        fd.write('\n')
+        for item in self:
+            item.dump_type(fd)
+
+    def dump_tail(self, fd):
+        pass
+
+# --------------------------------------------------------------------
+
+class CellSet(object):
+
+    data_type = 'int'
+    npy_dtype = _npy.int32
+
+    cell_type = None
+    cell_size = None
+
+    def __init__(self, data):
+        cell_array = _npy.asarray(data, dtype=self.npy_dtype)
+        cell_array = cell_array.reshape(-1, self.cell_size)
+        self.cell_array = cell_array
+
+    def __len__(self):
+        return len(self.cell_array)
+
+    @property
+    def size(self):
+        return self.cell_array.size
+
+    def dump_data(self, fd):
+        data = self.cell_array
+        m, n = data.shape
+        tmp = _npy.empty((m, n+1), data.dtype)
+        tmp[:, 0] = self.cell_size
+        tmp[:, 1:] = data
+        _dump_array(tmp, fd)
+        fd.write('\n')
+
+    def dump_type(self, fd):
+        data = self.cell_array
+        cell_type = _npy.asarray(self.cell_type, dtype='i')
+        tmp = _npy.repeat(cell_type, data.shape[0])
+        _dump_array(tmp, fd)
+        fd.write('\n')
+
+# ----------------------------------
+
+class Vertex(CellSet):
+    cell_type = 1
+    cell_size = 1
+
+class Line(CellSet):
+    cell_type = 3
+    cell_size = 2
+
+class Triangle(CellSet):
+    cell_type = 5
+    cell_size = 3
+
+class Quad(CellSet):
+    cell_type = 9
+    cell_size = 4
+
+class Tetra(CellSet):
+    cell_type = 10
+    cell_size = 4
+
+Tetrahedron = Tetra
+
+class Hexahedron(CellSet):
+    cell_type = 12
+    cell_size = 8
+
+Hexa = Hexahedron
+
+class Wedge(CellSet):
+    cell_type = 13
+    cell_size = 6
+
+class Pyramid(CellSet):
+    cell_type = 14
+    cell_size = 5
+
+# ----------------------------------
+
+class QuadraticEdge(CellSet):
+    cell_type = 21
+    cell_size = 3
+
+class QuadraticTriangle(CellSet):
+    cell_type = 22
+    cell_size = 6
+
+class QuadraticQuad(CellSet):
+    cell_type = 23
+    cell_size = 8
+
+class QuadraticTetra(CellSet):
+    cell_type = 24
+    cell_size = 10
+
+QuadraticTetrahedron = QuadraticTetra
+
+class QuadraticHexahedron(CellSet):
+    cell_type = 25
+    cell_size = 20
+
+QuadraticHexa = QuadraticHexahedron
+
+# ----------------------------------
+
+class PolyCellSet(CellSet):
+
+    def __init__(self, cell_array):
+        raise NotImplementedError
+
+    def __len__(self):
+        raise NotImplementedError
+
+    @property
+    def size(self):
+        raise NotImplementedError
+
+    def dump_data(self, fd):
+        raise NotImplementedError
+
+    def dump_type(self, fd):
+        raise NotImplementedError
+
+class PolyVertex(PolyCellSet):
+    cell_type = 2
+
+class PolyLine(PolyCellSet):
+    cell_type = 4
+
+class Polygon(PolyCellSet):
+    cell_type = 7
+
+# --------------------------------------------------------------------
+
+__all__ =   ['UnstructuredGrid'] \
+          + [cls.__name__ for cls in CellSet.__subclasses__()] \
+          + [cls.__name__ for cls in PolyCellSet.__subclasses__()] \
+          + ['Tetrahedron', 'Hexa']
+
+# --------------------------------------------------------------------
+# --------------------------------------------------------------------
+
+from DataSet \
+     import DataSet, DataSetAttr, PointData, CellData
+
+# --------------------------------------------------------------------
+
+class VtkData(object):
+
+    version = (2, 0)
+    title = 'VTK Data'
+
+    def __init__(self, structure, point_data=None, cell_data=None):
+        assert isinstance(structure, DataSet)
+        if point_data is None:
+            point_data = PointData()
+        if cell_data is None:
+            cell_data = CellData()
+        assert isinstance(point_data, PointData)
+        assert isinstance(cell_data,  CellData)
+        self.structure  = structure
+        self.point_data = point_data
+        self.cell_data  = cell_data
+
+    def tofile(self, filename, format='ascii'):
+        assert isinstance(filename, str)
+        assert format in ['ascii','binary']
+        filename = filename.strip()
+        if filename[-4:] != '.vtk':
+            filename += '.vtk'
+        filemode = {'ascii': 'w', 'binary': 'wb'}
+        fd = open(filename, filemode[format])
+        self.dump(fd)
+        fd.close()
+
+    def dump(self, fd):
+        assert isinstance(fd, file)
+        self.dump_head(fd)
+        self.dump_body(fd)
+        self.dump_tail(fd)
+
+    def dump_head(self, fd):
+        assert len(self.version) == 2
+        assert isinstance(self.title, str)
+        assert len(self.title) <= 255
+        header  = '# vtk DataFile Version %d.%d'
+        fd.write(header % self.version)
+        fd.write('\n')
+        fd.write(self.title[:255])
+        fd.write('\n')
+        if 'b' in fd.mode:
+            format = 'binary'
+        else:
+            format = 'ascii'
+        fd.write(format.upper())
+        fd.write('\n')
+
+    def dump_body(self, fd):
+        self.structure.dump(fd)
+        self.point_data.dump(fd)
+        self.cell_data.dump(fd)
+
+    def dump_tail(self, fd):
+        pass
+
+# --------------------------------------------------------------------
+
+__all__ = ['VtkData']
+
+# --------------------------------------------------------------------
+"""
+PyVTK2 - tools for writing VTK files in Python
+"""
+
+__author__   = 'Lisandro Dalcin <dalcinl@gmail.com>'
+__credits__  = 'Pearu Peterson <pearu@cens.ioc.ee>'
+__license__  = 'Public Domain'
+__version__  = '0.0.1'
+
+
+# --------------------------------------------------------------------
+
+from pyvtk2.VtkData \
+     import *
+
+from pyvtk2.DataSet \
+     import *
+
+from pyvtk2.StructuredPoints \
+     import *
+from pyvtk2.StructuredGrid \
+     import *
+from pyvtk2.RectilinearGrid \
+     import *
+from pyvtk2.UnstructuredGrid \
+     import *
+
+# --------------------------------------------------------------------
+
+if __name__ == '__main__':
+
+    points = [[0., 0., 0.],
+              [0., 0., 1.],
+              [0., 1., 0.],
+              [0., 1., 1.],
+              [1., 0., 0.],
+              [1., 0., 1.],
+              [1., 1., 0.],
+              [1., 1., 1.]]
+
+    tetras = [[0, 2, 1, 5],
+              [0, 2, 5, 4],
+              [2, 3, 1, 5],
+              [2, 3, 5, 7],
+              [2, 4, 6, 5],
+              [2, 6, 7, 5]]
+
+    vtk = VtkData(UnstructuredGrid(points, Tetra(tetras)),
+                  PointData(Scalars(range(8), 'pointdata')),
+                  CellData(Scalars(range(6), 'celldata')))
+    vtk.tofile('pyvtk2')
+
+# --------------------------------------------------------------------
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.