Example #1
0
    def fromfile(self,filename, only_structure = 0):
        filename = filename.strip()
        if filename[-4:]!='.vtk':
            filename += '.vtk'
        f = open(filename,'rb')
        l = f.readline()
        fileversion = l.strip().replace(b' ',b'').lower()
        if not fileversion == b'#vtkdatafileversion2.0':
            print('File %s is not in VTK 2.0 format, got %s but continuing anyway..' % (filename, fileversion))
        self.header = f.readline().rstrip().decode('ascii', 'replace')
        format = f.readline().strip().lower()
        if format not in [b'ascii', b'binary']:
            raise ValueError('Expected ascii|binary but got %s'%(repr(format)))
        if format == b'binary':
            raise NotImplementedError('reading vtk binary format')
        l = common._getline(f).decode('ascii').lower().split(' ')
        if l[0].strip() != 'dataset':
            raise ValueError('expected dataset but got %s'%(l[0]))
        try:
            ff = parsers[l[1]]
        except KeyError:
            raise NotImplementedError('%s_fromfile'%(l[1]))
        self.structure, l = ff(f,self)

        for i in range(2):
            if only_structure: break
            if not l:
                break
            l = [s.strip() for s in l.decode('ascii').lower().split(' ')]
            assert len(l)==2 and l[0] in ['cell_data','point_data'], l[0]
            data = l[0]
            n = int(l[1])
            lst = []
            while 1:
                l = common._getline(f)
                if not l:
                    break
                sl = [s.strip() for s in l.decode('ascii').split()]
                k = sl[0].lower()
                if k not in ['scalars','color_scalars','lookup_table','vectors',
                             'normals','texture_coordinates','tensors','field']:
                    break
                try:
                    ff = parsers[k]
                except KeyError:
                    raise NotImplementedError('%s_fromfile'%(k))
                lst.append(ff(f,n,sl[1:]))
            if data == 'point_data':
                self.point_data = PointData(*lst)
            if data == 'cell_data':
                self.cell_data = CellData(*lst)
        if self.point_data is None:
            self.point_data = PointData()
        if self.cell_data is None:
            self.cell_data = CellData()
        f.close()
Example #2
0
def structured_points_fromfile(f,self):
    l = common._getline(f).decode('ascii').split(' ')
    assert l[0].strip().lower() == 'dimensions'
    dims = list(map(int, l[1:]))
    assert len(dims)==3
    l = common._getline(f).decode('ascii').split(' ')
    assert l[0].strip().lower() == 'origin'
    origin = list(map(eval,l[1:]))
    assert len(origin)==3
    l = common._getline(f).decode('ascii').split(' ')
    assert l[0].strip().lower() == 'spacing'
    spacing = list(map(eval,l[1:]))
    assert len(spacing)==3
    return StructuredPoints(dims,origin,spacing),common._getline(f)
Example #3
0
def patched_scalars_fromfile(f, n, sl):
    dataname = sl[0]
    datatype = sl[1].lower()
    assert datatype in ['bit', 'unsigned_char', 'char', 'unsigned_short', 'short', 'unsigned_int', 'int', 'unsigned_long', 'long', 'float', 'double'], repr(datatype)
    if len(sl) > 2:
        numcomp = eval(sl[2])
    else:
        numcomp = 1
    l = common._getline(f)
    l = l.split()
    assert len(l) == 2 and l[0].lower().decode('UTF-8') == 'lookup_table'
    tablename = l[1].decode('UTF-8')
    scalars = []
    while len(scalars) < n:
        scalars += list(map(eval, common._getline(f).split()))
    assert len(scalars) == n
    return Scalars(scalars, dataname, tablename)
Example #4
0
def patched_scalars_fromfile(f,n,sl):
    dataname = sl[0]
    datatype = sl[1].lower()
    assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],repr(datatype)
    if len(sl)>2:
        numcomp = eval(sl[2])
    else:
        numcomp = 1
    l = common._getline(f)
    l = l.split()
    assert len(l)==2 and l[0].lower() == 'lookup_table'
    tablename = l[1]
    scalars = []
    while len(scalars) < n:
        scalars += list(map(eval,common._getline(f).split()))
    assert len(scalars)==n
    return Scalars(scalars,dataname,tablename)
Example #5
0
def polydata_fromfile(f, self):
    """Use VtkData(<filename>)."""
    points = []
    data = dict(vertices=[], lines=[], polygons=[], triangle_strips=[])
    l = common._getline(f).decode('ascii')
    k, n, datatype = [s.strip().lower() for s in l.split(' ')]
    if k != 'points':
        raise ValueError('expected points but got %s' % (repr(k)))
    n = int(n)
    assert datatype in [
        'bit', 'unsigned_char', 'char', 'unsigned_short', 'short',
        'unsigned_int', 'int', 'unsigned_long', 'long', 'float', 'double'
    ], repr(datatype)

    log.debug('\tgetting %s points' % n)
    while len(points) < 3 * n:
        l = common._getline(f).decode('ascii')
        points += map(eval, l.split(' '))
    assert len(points) == 3 * n
    while 1:
        l = common._getline(f)
        if l is None:
            break
        l = l.decode('ascii')
        sl = l.split(' ')
        k = sl[0].strip().lower()
        if k not in ['vertices', 'lines', 'polygons', 'triangle_strips']:
            break
        assert len(sl) == 3
        n = int(sl[1])
        size = int(sl[2])
        lst = []
        while len(lst) < size:
            l = common._getline(f).decode('ascii')
            lst += map(eval, l.split(' '))
        assert len(lst) == size
        lst2 = []
        j = 0
        for i in range(n):
            lst2.append(lst[j + 1:j + lst[j] + 1])
            j += lst[j] + 1
        data[k] = lst2

    return PolyData(points, data['vertices'], data['lines'], data['polygons'],
                    data['triangle_strips']), l.encode()
Example #6
0
def normals_fromfile(f,n,sl):
    dataname = sl[0]
    datatype = sl[1].lower()
    assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],repr(datatype)
    normals = []
    while len(normals) < 3*n:
        normals += map(eval,common._getline(f).decode('ascii').split(' '))
    assert len(normals) == 3*n
    return Normals(normals,dataname)
Example #7
0
def vectors_fromfile(f,n,sl):
    dataname = sl[0]
    datatype = sl[1].lower()
    assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],repr(datatype)
    vectors = []
    while len(vectors) < 3*n:
        vectors += map(eval,common._getline(f).split(' '))
    assert len(vectors) == 3*n
    return Vectors(vectors,dataname)
Example #8
0
def structured_grid_fromfile(f,self):
    l = common._getline(f).split(' ')
    assert l[0].strip().lower() == 'dimensions'
    dims = list(map(int, l[1:]))
    assert len(dims)==3
    l = common._getline(f)
    k,n,datatype = [s.strip().lower() for s in l.split(' ')]
    if k!='points':
        raise ValueError( 'expected points but got %s'%(repr(k)))
    n = int(n)
    assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],repr(datatype)
    points = []
    log.debug('\tgetting %s points'%n)
    while len(points) < 3*n:
        l = common._getline(f)
        points += map(eval,l.split(' '))
    assert len(points)==3*n
    return StructuredGrid(dims,points),common._getline(f)
Example #9
0
def patched_polydata_fromfile(f, self):
    """Use VtkData(<filename>)."""
    points = []
    vertices = []
    lines = []
    polygons = []
    triangle_strips = []
    l = common._getline(f)
    k, n, datatype = [s.strip().lower() for s in l.split()]
    if k != 'points':
        raise ValueError('expected points but got %s' % (repr(k)))
    n = eval(n)
    assert datatype in [
        'bit', 'unsigned_char', 'char', 'unsigned_short', 'short',
        'unsigned_int', 'int', 'unsigned_long', 'long', 'float', 'double'
    ], repr(datatype)

    self.message('\tgetting %s points' % n)
    while len(points) < 3 * n:
        l = common._getline(f)
        points += list(map(eval, l.split()))
    assert len(points) == 3 * n
    while 1:
        l = common._getline(f)
        if l is None:
            break
        sl = l.split()
        k = sl[0].strip().lower()
        if k not in ['vertices', 'lines', 'polygons', 'triangle_strips']:
            break
        assert len(sl) == 3
        n, size = list(map(eval, [sl[1], sl[2]]))
        lst = []
        while len(lst) < size:
            l = common._getline(f)
            lst += list(map(eval, l.split()))
        assert len(lst) == size
        lst2 = []
        j = 0
        for i in range(n):
            lst2.append(lst[j + 1:j + lst[j] + 1])
            j += lst[j] + 1
        exec('%s = lst2' % k)
    return PolyData(points, vertices, lines, polygons, triangle_strips), l
Example #10
0
def lookup_table_fromfile(f, n, sl):
    tablename = sl[0]
    size = int(sl[1])
    table = []
    while len(table) < 4 * size:
        table += map(eval, common._getline(f).decode("ascii").split(" "))
    assert len(table) == 4 * size
    table2 = []
    for i in range(0, len(table), 4):
        table2.append(table[i : i + 4])
    return LookupTable(table2, tablename)
Example #11
0
def lookup_table_fromfile(f, n, sl):
    tablename = sl[0]
    size = int(sl[1])
    table = []
    while len(table) < 4 * size:
        table += map(eval, common._getline(f).decode('ascii').split(' '))
    assert len(table) == 4 * size
    table2 = []
    for i in range(0, len(table), 4):
        table2.append(table[i:i + 4])
    return LookupTable(table2, tablename)
Example #12
0
def rectilinear_grid_fromfile(f,self):
    l = common._getline(f).decode('ascii').split(' ')
    assert l[0].strip().lower() == 'dimensions'
    dims = list(map(int, l[1:]))
    assert len(dims)==3
    coords = {}
    for c in 'xyz':
        l = common._getline(f).decode('ascii')
        k,n,datatype = [s.strip().lower() for s in l.split(' ')]
        if k!=c+'_coordinates':
            raise ValueError('expected %s_coordinates but got %s'%(c, repr(k)))
        n = int(n)
        assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],repr(datatype)
        points = []
        while len(points) < n:
            points += map(eval, common._getline(f).decode('ascii').split(' '))
        assert len(points)==n
        coords[c] = points
    assert list(map(len, [coords['x'], coords['y'], coords['z']])) == dims
    return RectilinearGrid(coords['x'], coords['y'], coords['z']),common._getline(f)
Example #13
0
def polydata_fromfile(f, self):
    """Use VtkData(<filename>)."""
    points = []
    data = dict(vertices=[], lines=[], polygons=[], triangle_strips=[])
    l = common._getline(f).decode('ascii')
    k,n,datatype = [s.strip().lower() for s in l.split(' ')]
    if k!='points':
        raise ValueError('expected points but got %s'%(repr(k)))
    n = int(n)
    assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],repr(datatype)

    log.debug('\tgetting %s points'%n)
    while len(points) < 3*n:
        l = common._getline(f).decode('ascii')
        points += map(eval,l.split(' '))
    assert len(points)==3*n
    while 1:
        l = common._getline(f)
        if l is None:
            break
        l = l.decode('ascii')
        sl = l.split(' ')
        k = sl[0].strip().lower()
        if k not in ['vertices','lines','polygons','triangle_strips']:
            break
        assert len(sl)==3
        n = int(sl[1])
        size = int(sl[2])
        lst = []
        while len(lst) < size:
            l = common._getline(f).decode('ascii')
            lst += map(eval, l.split(' '))
        assert len(lst)==size
        lst2 = []
        j = 0
        for i in range(n):
            lst2.append(lst[j+1:j+lst[j]+1])
            j += lst[j]+1
        data[k] = lst2

    return PolyData(points,data['vertices'], data['lines'], data['polygons'], data['triangle_strips']), l.encode()
Example #14
0
def patched_polydata_fromfile(f,self):
    """Use VtkData(<filename>)."""
    points = []
    vertices = []
    lines = []
    polygons = []
    triangle_strips = []
    l = common._getline(f)
    k,n,datatype = [s.strip().lower() for s in l.split()]
    if k!='points':
        raise ValueError('expected points but got %s'%(repr(k)))
    n = eval(n)
    assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],repr(datatype)

    self.message('\tgetting %s points'%n)
    while len(points) < 3*n:
        l = common._getline(f)
        points += list(map(eval,l.split()))
    assert len(points)==3*n
    while 1:
        l = common._getline(f)
        if l is None:
            break
        sl = l.split()
        k = sl[0].strip().lower()
        if k not in ['vertices','lines','polygons','triangle_strips']:
            break
        assert len(sl)==3
        n,size = list(map(eval,[sl[1],sl[2]]))
        lst = []
        while len(lst) < size:
            l = common._getline(f)
            lst += list(map(eval,l.split()))
        assert len(lst)==size
        lst2 = []
        j = 0
        for i in range(n):
            lst2.append(lst[j+1:j+lst[j]+1])
            j += lst[j]+1
        exec('%s = lst2'%k)
    return PolyData(points,vertices,lines,polygons,triangle_strips),l
Example #15
0
def vectors_fromfile(f, n, sl):
    dataname = sl[0]
    datatype = sl[1].lower()
    assert datatype in [
        'bit', 'unsigned_char', 'char', 'unsigned_short', 'short',
        'unsigned_int', 'int', 'unsigned_long', 'long', 'float', 'double'
    ], repr(datatype)
    vectors = []
    while len(vectors) < 3 * n:
        vectors += map(eval, common._getline(f).split(' '))
    assert len(vectors) == 3 * n
    return Vectors(vectors, dataname)
Example #16
0
def color_scalars_fromfile(f,n,sl):
    assert len(sl)==2
    dataname = sl[0].strip()
    nvals = int(sl[1])
    scalars = []
    while len(scalars)<nvals*n:
        scalars += map(float, common._getline(f).decode('ascii').split(' '))
    assert len(scalars)==nvals*n
    scalars2 = []
    for i in range(0,len(scalars),nvals):
        scalars2.append(scalars[i:i+nvals])
    return ColorScalars(scalars2,dataname)
Example #17
0
def structured_grid_fromfile(f, self):
    l = common._getline(f).split(' ')
    assert l[0].strip().lower() == 'dimensions'
    dims = list(map(int, l[1:]))
    assert len(dims) == 3
    l = common._getline(f)
    k, n, datatype = [s.strip().lower() for s in l.split(' ')]
    if k != 'points':
        raise ValueError('expected points but got %s' % (repr(k)))
    n = int(n)
    assert datatype in [
        'bit', 'unsigned_char', 'char', 'unsigned_short', 'short',
        'unsigned_int', 'int', 'unsigned_long', 'long', 'float', 'double'
    ], repr(datatype)
    points = []
    log.debug('\tgetting %s points' % n)
    while len(points) < 3 * n:
        l = common._getline(f)
        points += map(eval, l.split(' '))
    assert len(points) == 3 * n
    return StructuredGrid(dims, points), common._getline(f)
Example #18
0
def unstructured_grid_fromfile(f, self):
    l = common._getline(f).decode("ascii")
    k, n, datatype = [s.strip().lower() for s in l.split()]
    if k != "points":
        raise ValueError("expected points but got %s" % (repr(k)))
    n = int(n)
    assert datatype in [
        "bit",
        "unsigned_char",
        "char",
        "unsigned_short",
        "short",
        "unsigned_int",
        "int",
        "unsigned_long",
        "long",
        "float",
        "double",
    ], repr(datatype)
    points = []
    log.debug("\tgetting %s points" % n)
    while len(points) < 3 * n:
        points += list(map(eval, common._getline(f).split()))
    assert len(points) == 3 * n

    l = common._getline(f).decode("ascii").split()
    assert len(l) == 3 and l[0].strip().lower() == "cells", repr(l)
    n = int(l[1])
    size = int(l[2])
    lst = []
    log.debug("\tgetting %s cell indexes" % size)
    while len(lst) < size:
        line = common._getline(f).decode("ascii")
        lst += list(map(eval, line.split()))
    assert len(lst) == size
    lst2 = []
    j = 0
    for i in range(n):
        lst2.append(lst[j + 1 : j + lst[j] + 1])
        j += lst[j] + 1
    l = common._getline(f).decode("ascii").split()
    assert len(l) == 2 and l[0].strip().lower() == "cell_types" and int(l[1]) == n, repr(l)
    tps = []
    log.debug("\tgetting %s cell types" % n)
    while len(tps) < n:
        tps += list(map(int, common._getline(f).decode("ascii").split()))
    assert len(tps) == n
    dictionary = {}
    for i, t in zip(lst2, tps):
        k = UnstructuredGrid._vtk_cell_types_imap[t]
        if k not in dictionary:
            dictionary[k] = []
        dictionary[k].append(i)
    log.debug("unstructured_grid_fromfile done")
    return UnstructuredGrid(points, **dictionary), common._getline(f)
Example #19
0
def tensors_fromfile(f,n,sl):
    assert len(sl)==2
    dataname = sl[0].strip()
    datatype = sl[1].strip().lower()
    assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],repr(datatype)
    arr = []
    while len(arr)<9*n:
        arr += map(eval,common._getline(f).split(' '))
    assert len(arr)==9*n
    arr2 = []
    for i in range(0,len(arr),9):
        arr2.append(tuple(map(tuple,[arr[i:i+3],arr[i+3:i+6],arr[i+6:i+9]])))
    return Tensors(arr2,dataname)
Example #20
0
def field_fromfile(f, n, sl):
    dataname = sl[0]
    numarrays = int(sl[1])
    dict = {}
    for i in range(numarrays):
        l = common._getline(f).decode('ascii').split(' ')
        assert len(l) == 4, repr(l)
        name = l[0].strip()
        numcomps = int(l[1])
        numtuples = int(l[2])
        datatype = l[3].lower()
        assert datatype in [
            'bit', 'unsigned_char', 'char', 'unsigned_short', 'short',
            'unsigned_int', 'int', 'unsigned_long', 'long', 'float', 'double'
        ], repr(datatype)
        arr = []
        while len(arr) < numcomps * numtuples:
            arr += map(eval, common._getline(f).decode('ascii').split(' '))
        assert len(arr) == numcomps * numtuples
        arr2 = []
        for j in range(0, numtuples * numcomps, numcomps):
            arr2.append(arr[j:j + numcomps])
        dict[name] = arr2
    return Field(dataname, **dict)
Example #21
0
def tensors_fromfile(f, n, sl):
    assert len(sl) == 2
    dataname = sl[0].strip()
    datatype = sl[1].strip().lower()
    assert datatype in [
        'bit', 'unsigned_char', 'char', 'unsigned_short', 'short',
        'unsigned_int', 'int', 'unsigned_long', 'long', 'float', 'double'
    ], repr(datatype)
    arr = []
    while len(arr) < 9 * n:
        arr += map(eval, common._getline(f).split(' '))
    assert len(arr) == 9 * n
    arr2 = []
    for i in range(0, len(arr), 9):
        arr2.append(
            tuple(
                map(tuple,
                    [arr[i:i + 3], arr[i + 3:i + 6], arr[i + 6:i + 9]])))
    return Tensors(arr2, dataname)
Example #22
0
def unstructured_grid_fromfile(f, self):
    l = common._getline(f).decode('ascii')
    k,n,datatype = [s.strip().lower() for s in l.split()]
    if k != 'points':
        raise ValueError( 'expected points but got %s'%(repr(k)))
    n = int(n)
    assert datatype in ['bit','unsigned_char','char','unsigned_short','short','unsigned_int','int','unsigned_long','long','float','double'],repr(datatype)
    points = []
    log.debug('\tgetting %s points'%n)
    while len(points) < 3*n:
        points += list(map(eval, common._getline(f).split()))
    assert len(points)==3*n

    l = common._getline(f).decode('ascii').split()
    assert len(l)==3 and l[0].strip().lower() == 'cells',repr(l)
    n = int(l[1])
    size = int(l[2])
    lst = []
    log.debug('\tgetting %s cell indexes'%size)
    while len(lst) < size:
        line = common._getline(f).decode('ascii')
        lst += list(map(eval, line.split()))
    assert len(lst)==size
    lst2 = []
    j = 0
    for i in range(n):
        lst2.append(lst[j+1:j+lst[j]+1])
        j += lst[j]+1
    l = common._getline(f).decode('ascii').split()
    assert len(l)==2 and l[0].strip().lower() == 'cell_types' and int(l[1])==n, repr(l)
    tps = []
    log.debug('\tgetting %s cell types'%n)
    while len(tps) < n:
        tps += list(map(int, common._getline(f).decode('ascii').split()))
    assert len(tps)==n
    dictionary = {}
    for i,t in zip(lst2,tps):
        k = UnstructuredGrid._vtk_cell_types_imap[t]
        if k not in dictionary:
            dictionary[k] = []
        dictionary[k].append(i)
    log.debug('unstructured_grid_fromfile done')
    return UnstructuredGrid(points,**dictionary), common._getline(f)
Example #23
0
    def fromfile(self, filename, only_structure=0):
        filename = filename.strip()
        if filename[-4:] != '.vtk':
            filename += '.vtk'
        f = open(filename, 'rb')
        l = f.readline()
        fileversion = l.strip().replace(b' ', b'').lower()
        if not fileversion == b'#vtkdatafileversion2.0':
            print(
                'File %s is not in VTK 2.0 format, got %s but continuing anyway..'
                % (filename, fileversion))
        self.header = f.readline().rstrip().decode('ascii', 'replace')
        format = f.readline().strip().lower()
        if format not in [b'ascii', b'binary']:
            raise ValueError('Expected ascii|binary but got %s' %
                             (repr(format)))
        if format == b'binary':
            raise NotImplementedError('reading vtk binary format')
        l = common._getline(f).decode('ascii').lower().split(' ')
        if l[0].strip() != 'dataset':
            raise ValueError('expected dataset but got %s' % (l[0]))
        try:
            ff = parsers[l[1]]
        except KeyError:
            raise NotImplementedError('%s_fromfile' % (l[1]))
        self.structure, l = ff(f, self)

        for i in range(2):
            if only_structure: break
            if not l:
                break
            l = [s.strip() for s in l.decode('ascii').lower().split(' ')]
            assert len(l) == 2 and l[0] in ['cell_data', 'point_data'], l[0]
            data = l[0]
            n = int(l[1])
            lst = []
            while 1:
                l = common._getline(f)
                if not l:
                    break
                sl = [s.strip() for s in l.decode('ascii').split()]
                k = sl[0].lower()
                if k not in [
                        'scalars', 'color_scalars', 'lookup_table', 'vectors',
                        'normals', 'texture_coordinates', 'tensors', 'field'
                ]:
                    break
                try:
                    ff = parsers[k]
                except KeyError:
                    raise NotImplementedError('%s_fromfile' % (k))
                lst.append(ff(f, n, sl[1:]))
            if data == 'point_data':
                self.point_data = PointData(*lst)
            if data == 'cell_data':
                self.cell_data = CellData(*lst)
        if self.point_data is None:
            self.point_data = PointData()
        if self.cell_data is None:
            self.cell_data = CellData()
        f.close()