Annotation of python/pyvtk/lib/__init__.py, revision 1.12

1.1       pearu       1: #!/usr/bin/env python
                      2: """
                      3: PyVTK provides tools for manipulating VTK files in Python.
1.3       pearu       4: 
1.7       pearu       5: VtkData - create VTK files from Python / read VTK files to Python
1.3       pearu       6: 
1.1       pearu       7: """
                      8: """
                      9: Copyright 2001 Pearu Peterson all rights reserved,
                     10: Pearu Peterson <pearu@ioc.ee>          
                     11: Permission to use, modify, and distribute this software is given under the
                     12: terms of the LGPL.  See http://www.fsf.org
                     13: 
                     14: NO WARRANTY IS EXPRESSED OR IMPLIED.  USE AT YOUR OWN RISK.
1.12    ! pearu      15: $Revision: 1.11 $
        !            16: $Date: 2003/04/07 14:56:08 $
1.1       pearu      17: Pearu Peterson
                     18: """
                     19: 
                     20: __author__ = "Pearu Peterson <pearu@cens.ioc.ee>"
                     21: __license__ = "LGPL (see http://www.fsf.org)"
1.3       pearu      22: from __version__ import __version__
1.1       pearu      23: 
1.10      pearu      24: __all__ = ['StructuredPoints','StructuredGrid','UnstructuredGrid',
1.1       pearu      25:            'RectilinearGrid','PolyData',
                     26:            'Scalars','ColorScalars','LookupTable','Vectors','Normals',
                     27:            'TextureCoordinates','Tensors','Field',
                     28:            'PointData','CellData',
                     29:            'VtkData']
                     30: 
1.6       pearu      31: import types
                     32: import os
1.1       pearu      33: import common
                     34: 
1.7       pearu      35: from StructuredPoints import StructuredPoints, structured_points_fromfile
                     36: from StructuredGrid import StructuredGrid, structured_grid_fromfile
                     37: from UnstructuredGrid import UnstructuredGrid, unstructured_grid_fromfile
                     38: from RectilinearGrid import RectilinearGrid, rectilinear_grid_fromfile
                     39: from PolyData import PolyData, polydata_fromfile
                     40: 
                     41: from Scalars import Scalars,scalars_fromfile
                     42: from ColorScalars import ColorScalars, color_scalars_fromfile
                     43: from LookupTable import LookupTable, lookup_table_fromfile
                     44: from Vectors import Vectors, vectors_fromfile
                     45: from Normals import Normals, normals_fromfile
                     46: from TextureCoordinates import TextureCoordinates, texture_coordinates_fromfile
                     47: from Tensors import Tensors, tensors_fromfile
                     48: from Field import Field, field_fromfile
1.1       pearu      49: 
                     50: from Data import PointData,CellData
                     51: 
                     52: class VtkData(common.Common):
                     53:     """
                     54:     VtkData
                     55:     =======
                     56: 
                     57:     Represents VTK file that has four relevant parts:
1.9       pearu      58:       header    - string up to length 255
1.1       pearu      59:       format    - string: ascii | binary
                     60:       DataSet   - StructuredPoints | StructuredGrid | UnstructuredGrid
                     61:                   | RectilinearGrid | PolyData
                     62:       Data      - PointData | CellData
                     63:       
                     64:     Usage:
                     65:     ------
                     66:       v = VtkData(<DataSet instance> [,<header string>,<Data instances>,..])
1.7       pearu      67:       v = VtkData(<filename>, only_structure = 0) - read VTK data from file.
1.1       pearu      68:       v.tofile(filename, format = 'ascii') - save VTK data to file.
1.7       pearu      69:     Attributes:
                     70:       header
                     71:       structure
                     72:       point_data
                     73:       cell_data
                     74:     Public methods:
                     75:       to_string(format = 'ascii')
                     76:       tofile(filename, format = 'ascii')
1.1       pearu      77: 
                     78:     DataSet
                     79:     =======
                     80:     
                     81:       StructuredPoints(<3-sequence of dimensions>
                     82:                        [,<3-sequence of origin> [, <3-sequence of spacing>]])
                     83:       StructuredGrid(<3-sequence of dimensions>,
                     84:                      <sequence of 3-sequences of points>)
                     85:       UnstructuredGrid(<sequence of 3-sequences of points>
                     86:                        [,<cell> = <sequence of (sequences of) integers>])
                     87:         cell - vertex | poly_vertex | line | poly_line | triangle
                     88:                | triangle_strip | polygon | pixel | quad | tetra
                     89:                | voxel | hexahedron | wedge | pyramid
                     90:       RectilinearGrid([x = <sequence of x-coordinates>],
                     91:                       [y = <sequence of y-coordinates>],
                     92:                       [z = <sequence of z-coordinates>])
                     93:       PolyData(<sequence of 3-sequences of points>,
                     94:                [vertices = <sequence of (sequences of) integers>],
                     95:                [lines = <sequence of (sequences of) integers>],
                     96:                [polygons = <sequence of (sequences of) integers>],
                     97:                [triangle_strips = <sequence of (sequences of) integers>])
                     98: 
                     99:     Data
                    100:     ====
                    101: 
                    102:       PointData | CellData ([<DataSetAttr instances>]) - construct Data instance
                    103: 
                    104:     DataSetAttr
                    105:     ===========
                    106: 
                    107:       DataSetAttr - Scalars | ColorScalars | LookupTable | Vectors
                    108:                     | Normals | TextureCoordinates | Tensors | Field
                    109:       Scalars(<sequence of scalars> [,name[, lookup_table]])
                    110:       ColorScalars(<sequence of scalar sequences> [,name])
                    111:       LookupTable(<sequence of 4-sequences> [,name])
                    112:       Vectors(<sequence of 3-sequences> [,name])
                    113:       Normals(<sequence of 3-sequences> [,name])
                    114:       TextureCoordinates(<sequence of (1,2, or 3)-sequences> [,name])
                    115:       Tensors(<sequence of (3x3)-sequences> [,name])
                    116:       Field([name,] [arrayname_1 = sequence of n_1-sequences, ...
                    117:                      arrayname_m = sequence of n_m-sequences,])
                    118:         where len(array_1) == .. == len(array_m) must hold.
                    119:     """
                    120:     header = None
                    121:     point_data = None
                    122:     cell_data = None
1.7       pearu     123:     def __init__(self,*args,**kws):
1.6       pearu     124:         assert args,'expected at least one argument'
                    125:         if type(args[0]) is types.StringType:
1.7       pearu     126:             if kws.has_key('only_structure') and kws['only_structure']:
                    127:                 self.fromfile(args[0],1)
                    128:             else:
                    129:                 self.fromfile(args[0])
1.6       pearu     130:             return
                    131:         else:
                    132:             structure = args[0]
                    133:             args = list(args)[1:]
1.1       pearu     134:         if not common.is_dataset(structure):
                    135:             raise TypeError,'argument structure must be StructuredPoints|StructuredGrid|UnstructuredGrid|RectilinearGrid|PolyData but got %s'%(type(structure))
                    136:         self.structure = structure
                    137:         for a in args:
                    138:             if common.is_string(a):
                    139:                 if len(a)>255:
1.9       pearu     140:                     self.skipping('striping header string to a length =255')
                    141:                 self.header = a[:255]
1.1       pearu     142:             elif common.is_pointdata(a):
                    143:                 self.point_data = a
                    144:             elif common.is_celldata(a):
                    145:                 self.cell_data = a
                    146:             else:
                    147:                 self.skipping('unexpexted argument %s'%(type(a)))
                    148:         if self.header is None:
                    149:             self.header = 'Really cool data'
                    150:             self.warning('Using header=%s'%(`self.header`))
                    151:         if self.point_data is None and self.cell_data is None:
                    152:             self.warning('No data defined')
1.2       pearu     153: 
1.1       pearu     154:         if self.point_data is not None:
1.2       pearu     155:             s = self.structure.get_size()
1.1       pearu     156:             s1 = self.point_data.get_size()
                    157:             if s1 != s:
                    158:                 raise ValueError,'DataSet (size=%s) and PointData (size=%s) have different sizes'%(s,s1)
1.7       pearu     159:         else:
                    160:             self.point_data = PointData()
1.1       pearu     161:         if self.cell_data is not None:
1.2       pearu     162:             s = self.structure.get_cell_size()
1.1       pearu     163:             s1 = self.cell_data.get_size()
                    164:             if s1 != s:
1.2       pearu     165:                 raise ValueError,'DataSet (cell_size=%s) and CellData (size=%s) have different sizes'%(s,s1)
1.7       pearu     166:         else:
                    167:             self.cell_data = CellData()
1.6       pearu     168:     def to_string(self, format = 'ascii'):
                    169:         ret = ['# vtk DataFile Version 2.0',
                    170:                self.header,
                    171:                format.upper(),
                    172:                self.structure.to_string(format)
                    173:                ]
1.7       pearu     174:         if self.cell_data.data:
1.6       pearu     175:             ret.append(self.cell_data.to_string(format))
1.7       pearu     176:         if self.point_data.data:
1.6       pearu     177:             ret.append(self.point_data.to_string(format))
1.10      pearu     178:         #print `ret`
1.6       pearu     179:         return '\n'.join(ret)
1.7       pearu     180: 
1.1       pearu     181:     def tofile(self, filename, format = 'ascii'):
1.7       pearu     182:         """Save VTK data to file.
                    183:         """
1.1       pearu     184:         if not common.is_string(filename):
                    185:             raise TypeError,'argument filename must be string but got %s'%(type(filename))
                    186:         if format not in ['ascii','binary']:
                    187:             raise TypeError,'argument format must be ascii | binary'
                    188:         filename = filename.strip()
                    189:         if not filename:
                    190:             raise ValueError,'filename must be non-empty string'
                    191:         if filename[-4:]!='.vtk':
                    192:             filename += '.vtk'
1.11      pearu     193:         #print 'Creating file',`filename`
1.1       pearu     194:         f = open(filename,'wb')
1.6       pearu     195:         f.write(self.to_string(format))
                    196:         f.close()
                    197: 
1.7       pearu     198:     def fromfile(self,filename, only_structure = 0):
1.6       pearu     199:         filename = filename.strip()
                    200:         if filename[-4:]!='.vtk':
                    201:             filename += '.vtk'
1.11      pearu     202:         #print 'Reading file',`filename`
1.6       pearu     203:         f = open(filename,'rb')
                    204:         l = f.readline()
1.12    ! pearu     205:         fileversion = l.strip().replace(' ','').lower()
        !           206:         if not fileversion == '#vtkdatafileversion2.0':
        !           207:             print 'File %s is not in VTK 2.0 format, got %s' % (filename, fileversion),
        !           208:             print ' but continuing anyway..'
1.6       pearu     209:         self.header = f.readline().rstrip()
                    210:         format = f.readline().strip().lower()
                    211:         if format not in ['ascii','binary']:
                    212:             raise ValueError,'Expected ascii|binary but got %s'%(`format`)
                    213:         if format == 'binary':
                    214:             raise NotImplementedError,'reading vtk binary format'
                    215:         l = common._getline(f).lower().split(' ')
                    216:         if l[0].strip() != 'dataset':
                    217:             raise ValueError,'expected dataset but got %s'%(l[0])
                    218:         try:
                    219:             ff = eval(l[1]+'_fromfile')
                    220:         except NameError:
                    221:             raise NotImplementedError,'%s_fromfile'%(l[1])
1.7       pearu     222:         self.structure,l = ff(f,self)
                    223: 
                    224:         for i in range(2):
                    225:             if only_structure: break
                    226:             if not l: break
                    227:             l = [s.strip() for s in l.lower().split(' ')]
                    228:             assert len(l)==2 and l[0] in ['cell_data','point_data'], l[0]
                    229:             data = l[0]
                    230:             n = eval(l[1])
                    231:             lst = []
                    232:             while 1:
                    233:                 l = common._getline(f)
                    234:                 if not l: break
                    235:                 sl = [s.strip() for s in l.split()]
                    236:                 k = sl[0].lower()
                    237:                 if k not in ['scalars','color_scalars','lookup_table','vectors',
                    238:                              'normals','texture_coordinates','tensors','field']:
                    239:                     break
                    240:                 try:
                    241:                     ff = eval(k+'_fromfile')
                    242:                 except NameError:
                    243:                     raise NotImplementedError,'%s_fromfile'%(k)
                    244:                 lst.append(ff(f,n,sl[1:]))
                    245:             if data == 'point_data':
                    246:                 self.point_data = PointData(*lst)
                    247:             if data == 'cell_data':
                    248:                 self.cell_data = CellData(*lst)
                    249:         if self.point_data is None:
                    250:             self.point_data = PointData()
                    251:         if self.cell_data is None:
                    252:             self.cell_data = CellData()
1.1       pearu     253:         f.close()
                    254: 
                    255: if __name__ == "__main__":
                    256:     vtk = VtkData(StructuredPoints((3,1,1)),
                    257:                   'This is title',
                    258:                   PointData(Scalars([3,4,5]))
                    259:                   )
                    260:     vtk.tofile('test')

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>