コード例 #1
0
def array_to_vtk(array_in, dtype=None):
    """Get vtkFloatArray/vtkDoubleArray from the input numpy array."""
    if dtype is None:
        dtype = _numpy.dtype(array_in.dtype)
    else:
        dtype = _numpy.dtype(dtype)
    if dtype == _numpy.float32:
        float_array = _vtk.vtkFloatArray()
    elif dtype == _numpy.float64:
        float_array = _vtk.vtkDoubleArray()
    elif dtype == _numpy.uint8:
        float_array = _vtk.vtkUnsignedCharArray()
    elif dtype == _numpy.int8:
        float_array = _vtk.vtkCharArray()
    else:
        raise ValueError("Wrong format of input array, must be one of "
                         "float32, float64, uint8, int8")
    if len(array_in.shape) != 1 and len(array_in.shape) != 2:
        raise ValueError("Wrong shape: array must be 1D or 2D.")
    float_array.SetNumberOfComponents(1)
    array_contiguous = _numpy.ascontiguousarray(array_in, dtype)
    float_array.SetVoidArray(array_contiguous,
                             _numpy.product(array_in.shape),
                             1)
    # Hack to keep the array of being garbage collected
    float_array._contiguous_array = array_contiguous
    return float_array
コード例 #2
0
ファイル: vtk_tools.py プロジェクト: ekeberg/Python-tools
def array_to_vtk(array_in, dtype=None):
    """Get vtkFloatArray/vtkDoubleArray from the input numpy array."""
    if dtype == None:
        dtype = _numpy.dtype(array_in.dtype)
    else:
        dtype = _numpy.dtype(dtype)
    if dtype == _numpy.float32:
        float_array = _vtk.vtkFloatArray()
    elif dtype == _numpy.float64:
        float_array = _vtk.vtkDoubleArray()
    elif dtype == _numpy.uint8:
        float_array = _vtk.vtkUnsignedCharArray()
    elif dtype == _numpy.int8:
        float_array = _vtk.vtkCharArray()
    else:
        raise ValueError("Wrong format of input array, must be float32 or float64")
    if len(array_in.shape) != 1 and len(array_in.shape) != 2:
        raise ValueError("Wrong shape: array must be 1D or 2D.")
    #float_array.SetNumberOfComponents(_numpy.product(array_in.shape))
    # if len(array_in.shape) == 2:
    #     float_array.SetNumberOfComponents(array_in.shape[1])
    # elif len(array_in.shape) == 1:
    #     float_array.SetNumberOfComponents(1)
    float_array.SetNumberOfComponents(1)
    array_contiguous = _numpy.ascontiguousarray(array_in, dtype)
    float_array.SetVoidArray(array_contiguous, _numpy.product(array_in.shape), 1)
    float_array._contiguous_array = array_contiguous  # Hack to keep the array of being garbage collected
    # if len(array_in.shape) == 2:
    #     print "set tuple to {0}".format(array_in.shape[1])
    #     #float_array.SetNumberOfTuples(array_in.shape[1])
    #     float_array.Resize(array_in.shape[1])
    #     float_array.Squeeze()
    return float_array
コード例 #3
0
ファイル: t2grids.py プロジェクト: neerja007/PyTOUGH
 def get_vtk_data(self,geo):
     """Returns dictionary of VTK data arrays from rock types.  The geometry object geo must be passed in."""
     from vtk import vtkIntArray,vtkFloatArray,vtkCharArray
     arrays={'Block':{'Rock type index':vtkIntArray(),'Porosity':vtkFloatArray(),
                      'Permeability':vtkFloatArray(),'Name':vtkCharArray()},'Node':{}}
     vector_properties=['Permeability']
     string_properties=['Name']
     string_length=5
     nele=geo.num_underground_blocks
     array_length={'Block':nele,'Node':0}
     for array_type,array_dict in arrays.items():
         for name,array in array_dict.items():
             array.SetName(name)
             if name in vector_properties:
                 array.SetNumberOfComponents(3)
                 array.SetNumberOfTuples(array_length[array_type])
             elif name in string_properties:
                 array.SetNumberOfComponents(string_length)
                 array.SetNumberOfTuples(array_length[array_type])
             else: 
                 array.SetNumberOfComponents(1)
                 array.SetNumberOfValues(array_length[array_type])
     natm=geo.num_atmosphere_blocks
     rindex=self.rocktype_indices[natm:]
     for i,ri in enumerate(rindex):
         arrays['Block']['Rock type index'].SetValue(i,ri)
         rt=self.rocktypelist[ri]
         arrays['Block']['Porosity'].SetValue(i,rt.porosity)
         k=rt.permeability
         arrays['Block']['Permeability'].SetTuple3(i,k[0],k[1],k[2])
     for i,blk in enumerate(self.blocklist[natm:]):
         arrays['Block']['Name'].SetTupleValue(i,blk.name)
     return arrays
コード例 #4
0
 def testCharArrayArguments(self):
     a = vtk.vtkCharArray()
     a.SetNumberOfComponents(3)
     a.SetNumberOfTuples(1)
     ti = "opn"
     a.SetTupleValue(0, ti)
     # python strings are immutable, so this should NOT work
     #to = "***"
     #a.GetTupleValue(0, to);
     d1 = list(a.GetTuple(0))
     d2 = [ord(x) for x in ti]
     self.assertEqual(d1, d2)
コード例 #5
0
 def testCharArrayArguments(self):
     a = vtk.vtkCharArray()
     a.SetNumberOfComponents(3)
     a.SetNumberOfTuples(1)
     ti = "opn"
     a.SetTupleValue(0, ti)
     # python strings are immutable, so this should NOT work
     #to = "***"
     #a.GetTupleValue(0, to);
     d1 = list(a.GetTuple(0))
     d2 = map(float, map(ord, ti))
     self.assertEqual(d1, d2)
コード例 #6
0
 def RequestInformation(self, request, inInfo, outInfo):
     print("MyFilter RequestInformation:")
     print(outInfo.GetInformationObject(0))
     metaData = inInfo[0].GetInformationObject(0).Get(
         metaDataKey)
     newMetaData = metaData.NewInstance()
     newMetaData.ShallowCopy(metaData)
     someArray = vtk.vtkCharArray()
     someArray.SetName("someArray")
     newMetaData.GetFieldData().AddArray(someArray)
     outInfo.GetInformationObject(0).Set(metaDataKey, newMetaData)
     print(outInfo.GetInformationObject(0))
     return 1
コード例 #7
0
def createCharArray(name,
                    n_components=1,
                    n_tuples=0,
                    init_to_zero=0,
                    verbose=0):

    carray = vtk.vtkCharArray()
    carray.SetName(name)
    carray.SetNumberOfComponents(n_components)
    carray.SetNumberOfTuples(n_tuples)

    if (init_to_zero):
        for k_tuple in xrange(n_tuples):
            iarray.SetTuple(k_tuple, [0] * n_components)

    return carray
コード例 #8
0
def createCharArray(name,
                    n_components=1,
                    n_tuples=0,
                    init_to_zero=0,
                    verbose=0):

    array = vtk.vtkCharArray()
    array.SetName(name)
    array.SetNumberOfComponents(n_components)
    array.SetNumberOfTuples(n_tuples)

    if (init_to_zero):
        for k_component in range(n_components):
            array.FillComponent(k_component, 0)

    return array
コード例 #9
0
ファイル: TestBuffer.py プロジェクト: EricAlex/ThirdParty-dev
 def testCharArray(self):
     """Test the special case of the char array."""
     if sys.hexversion < 0x02070000:
         return
     # bit array is actually stored as a byte array
     a = vtk.vtkCharArray()
     a.SetNumberOfComponents(5)
     a.InsertNextTupleValue("hello")
     a.InsertNextTupleValue("world")
     m = memoryview(a)
     self.assertEqual(m.format, 'c')
     self.assertEqual(m.itemsize, 1)
     self.assertEqual(m.shape, (2, 5))
     self.assertEqual(m.strides, (5, 1))
     self.assertEqual(m.ndim, 2)
     # test the contents of the memoryview
     self.assertEqual(m.tobytes(), b"helloworld")
コード例 #10
0
def probe_vtk_kilobyte(default=None):
    if not hasvtk:
        return default

    from vtk import vtkCharArray
    vtk_da = vtkCharArray()
    vtk_da.SetNumberOfComponents(1)
    vtk_da.SetNumberOfTuples(1024**2)

    # Size of 1 MB = 1024**2 bytes in "VTK kilobytes"
    size = vtk_da.GetActualMemorySize()
    if size == 1024:
        return 1024
    elif round(abs(size - 1024**2 / 1e3)) == 0:
        return 1e3
    else:
        return default
コード例 #11
0
def createCharArray(
        name,
        n_components=1,
        n_tuples=0,
        init_to_zero=0,
        verbose=0):

    carray = vtk.vtkCharArray()
    carray.SetName(name)
    carray.SetNumberOfComponents(n_components)
    carray.SetNumberOfTuples(n_tuples)

    if (init_to_zero):
        for k_tuple in xrange(n_tuples):
            iarray.SetTuple(k_tuple, [0]*n_components)

    return carray
コード例 #12
0
 def testCharArray(self):
     """Test the special case of the char array."""
     if sys.hexversion < 0x02070000:
         return
     # bit array is actually stored as a byte array
     a = vtk.vtkCharArray()
     a.SetNumberOfComponents(5)
     a.InsertNextTypedTuple("hello")
     a.InsertNextTypedTuple("world")
     m = memoryview(a)
     self.assertEqual(m.format, 'c')
     self.assertEqual(m.itemsize, 1)
     self.assertEqual(m.shape, (2, 5))
     self.assertEqual(m.strides, (5, 1))
     self.assertEqual(m.ndim, 2)
     # test the contents of the memoryview
     self.assertEqual(m.tobytes(), b"helloworld")
コード例 #13
0
ファイル: __init__.py プロジェクト: JConwayAWT/PGSS14CC
def probe_vtk_kilobyte(default=None):
    if not hasvtk:
        return default

    from vtk import vtkCharArray
    vtk_da = vtkCharArray()
    vtk_da.SetNumberOfComponents(1)
    vtk_da.SetNumberOfTuples(1024**2)

    # Size of 1 MB = 1024**2 bytes in "VTK kilobytes"
    size = vtk_da.GetActualMemorySize()
    if size == 1024:
        return 1024
    elif round(abs(size-1024**2/1e3)) == 0:
        return 1e3
    else:
        return default
コード例 #14
0
 def get_vtk_data(self, geo, blockmap={}):
     """Returns dictionary of VTK data arrays from rock types.  The geometry object geo must be passed in."""
     from vtk import vtkIntArray, vtkFloatArray, vtkCharArray
     arrays = {
         'Block': {
             'Rock type index': vtkIntArray(),
             'Porosity': vtkFloatArray(),
             'Permeability': vtkFloatArray(),
             'Name': vtkCharArray()
         },
         'Node': {}
     }
     vector_properties = ['Permeability']
     string_properties = ['Name']
     string_length = 5
     nele = geo.num_underground_blocks
     array_length = {'Block': nele, 'Node': 0}
     for array_type, array_dict in arrays.items():
         for name, array in array_dict.items():
             array.SetName(name)
             if name in vector_properties:
                 array.SetNumberOfComponents(3)
                 array.SetNumberOfTuples(array_length[array_type])
             elif name in string_properties:
                 array.SetNumberOfComponents(string_length)
                 array.SetNumberOfTuples(array_length[array_type])
             else:
                 array.SetNumberOfComponents(1)
                 array.SetNumberOfValues(array_length[array_type])
     natm = geo.num_atmosphere_blocks
     rindex = self.rocktype_indices
     rockdict = dict(zip([blk.name for blk in self.blocklist], rindex))
     for i, blkname in enumerate(geo.block_name_list[natm:]):
         mapped_name = blockmap[blkname] if blkname in blockmap else blkname
         arrays['Block']['Name'].SetTupleValue(i, mapped_name)
         ri = rockdict[mapped_name]
         arrays['Block']['Rock type index'].SetValue(i, ri)
         rt = self.rocktypelist[ri]
         arrays['Block']['Porosity'].SetValue(i, rt.porosity)
         k = rt.permeability
         arrays['Block']['Permeability'].SetTuple3(i, k[0], k[1], k[2])
     return arrays
コード例 #15
0
ファイル: helpers.py プロジェクト: yngvem/pyvista
def vtk_bit_array_to_char(vtkarr_bint):
    """Cast vtk bit array to a char array."""
    vtkarr = vtk.vtkCharArray()
    vtkarr.DeepCopy(vtkarr_bint)
    return vtkarr
コード例 #16
0
ファイル: mesh_io.py プロジェクト: nschloe/nosh
def _create_vtkarray(X, name):
    import numpy as np
    from vtk import vtkBitArray, vtkIntArray, vtkDoubleArray, vtkCharArray

    # If something isn't a Numpy array already, try to make it one.
    if not isinstance(X, np.ndarray) and not isinstance(X, str):
        X = np.array(X)

    # This could be a lot more fine-grained:
    # vtkLongLongArray, vtkFloatArray,...
    if isinstance(X, str) or X.dtype.kind == 'S':
        array = vtkCharArray()
    elif X.dtype == bool:
        array = vtkBitArray()
    elif X.dtype == int:
        array = vtkIntArray()
    elif X.dtype == float:
        array = vtkDoubleArray()
    elif X.dtype == complex:
        # Convert complex arrays to double.
        Y = np.empty((len(X),2), dtype=float)
        if len(X.shape) == 1:
            Y[:,0] = X.real
            Y[:,1] = X.imag
        elif len(X.shape) == 2:
            Y[:,0] = X[:,0].real
            Y[:,1] = X[:,0].imag
        else:
            raise RuntimeError()
        X = Y
        array = vtkDoubleArray()
    else:
        raise TypeError('Unknown VTK data type', X.dtype, '.')

    # For some reason, setting the number of tuples and then using
    # SetNextTuple() or similar doesn't seem to work:
    # The application segfaults or, worse, yields an irrecoverable
    # glibc memory corruption.
    # Most likely the cause: You have to call SetNumberOfTuples()
    # AFTER SetNumberOfComponents().
    #array.SetNumberOfTuples(X.shape[0])
    # Special treatment for strings:
    if isinstance(X, str):
        array.SetNumberOfComponents(len(X))
        array.SetNumberOfTuples(1)
        array.SetTupleValue(0, X)
    elif len(X.shape) == 0:
        array.SetNumberOfComponents(1)
        # Set values.
        array.InsertNextValue(X)
    elif len(X.shape) == 1:
        array.SetNumberOfComponents(1)
        # Set values.
        for k in xrange(X.shape[0]):
            array.InsertNextValue(X[k])
    elif len(X.shape) == 2:
        array.SetNumberOfComponents(X.shape[1])
        # Set values.
        for k in xrange(X.shape[0]):
            for k2 in xrange(X.shape[1]):
                array.InsertNextValue(X[k][k2])
    else:
        raise ValueError('Don''t know what to do with many-dimensional array ''%s''.' % name)

    array.SetName(name)

    return array
コード例 #17
0
def vtk2array(vtk_array):
    """Converts a VTK data array to a numpy array.

    Given a subclass of vtkDataArray, this function returns an
    appropriate numpy array containing the same data.  The function
    is very efficient since it uses the VTK imaging pipeline to
    convert the data.  If a sufficiently new version of VTK (5.2) is
    installed then it actually uses the buffer interface to return a
    view of the VTK array in the returned numpy array.

    Parameters
    ----------

    - vtk_array : `vtkDataArray`

      The VTK data array to be converted.

    """
    typ = vtk_array.GetDataType()
    assert typ in get_vtk_to_numeric_typemap().keys(), \
           "Unsupported array type %s"%typ

    shape = vtk_array.GetNumberOfTuples(), \
            vtk_array.GetNumberOfComponents()
    if shape[0] == 0:
        dtype = get_numeric_array_type(typ)
        return numpy.array([], dtype)

    # First check if this array already has a numpy array cached,
    # if it does and the array size has not been changed, reshape
    # that and return it.
    if vtk_array in _array_cache:
        arr = _array_cache.get(vtk_array)
        if shape[1] == 1:
            shape = (shape[0], )
        if arr.size == numpy.prod(shape):
            arr = numpy.reshape(arr, shape)
            return arr

    # If VTK's new numpy support is available, use the buffer interface.
    if numpy_support is not None and typ != vtkConstants.VTK_BIT:
        dtype = get_numeric_array_type(typ)
        result = numpy.frombuffer(vtk_array, dtype=dtype)
        if shape[1] == 1:
            shape = (shape[0], )
        result.shape = shape
        return result

    # Setup an imaging pipeline to export the array.
    img_data = vtk.vtkImageData()
    img_data.SetDimensions(shape[0], 1, 1)
    if typ == vtkConstants.VTK_BIT:
        iarr = vtk.vtkCharArray()
        iarr.DeepCopy(vtk_array)
        img_data.GetPointData().SetScalars(iarr)
    elif typ == vtkConstants.VTK_ID_TYPE:
        # Needed since VTK_ID_TYPE does not work with VTK 4.5.
        iarr = vtk.vtkLongArray()
        iarr.SetNumberOfTuples(vtk_array.GetNumberOfTuples())
        nc = vtk_array.GetNumberOfComponents()
        iarr.SetNumberOfComponents(nc)
        for i in range(nc):
            iarr.CopyComponent(i, vtk_array, i)
        img_data.GetPointData().SetScalars(iarr)
    else:
        img_data.GetPointData().SetScalars(vtk_array)

    if is_old_pipeline():
        img_data.SetNumberOfScalarComponents(shape[1])
        if typ == vtkConstants.VTK_ID_TYPE:
            # Hack necessary because vtkImageData can't handle VTK_ID_TYPE.
            img_data.SetScalarType(vtkConstants.VTK_LONG)
            r_dtype = get_numeric_array_type(vtkConstants.VTK_LONG)
        elif typ == vtkConstants.VTK_BIT:
            img_data.SetScalarType(vtkConstants.VTK_CHAR)
            r_dtype = get_numeric_array_type(vtkConstants.VTK_CHAR)
        else:
            img_data.SetScalarType(typ)
            r_dtype = get_numeric_array_type(typ)
        img_data.Update()
    else:
        if typ == vtkConstants.VTK_ID_TYPE:
            r_dtype = get_numeric_array_type(vtkConstants.VTK_LONG)
        elif typ == vtkConstants.VTK_BIT:
            r_dtype = get_numeric_array_type(vtkConstants.VTK_CHAR)
        else:
            r_dtype = get_numeric_array_type(typ)
        img_data.Modified()

    exp = vtk.vtkImageExport()
    if is_old_pipeline():
        exp.SetInput(img_data)
    else:
        exp.SetInputData(img_data)

    # Create an array of the right size and export the image into it.
    im_arr = numpy.empty((shape[0]*shape[1],), r_dtype)
    exp.Export(im_arr)

    # Now reshape it.
    if shape[1] == 1:
        shape = (shape[0], )
    im_arr = numpy.reshape(im_arr, shape)
    return im_arr
コード例 #18
0
from pytestvtk.assert_vtk import assert_vtk


@pytest.fixture(params=[
    vtk.vtkDoubleArray(),
    vtk.vtkFloatArray(),
    vtk.vtkIntArray(),
    vtk.vtkIdTypeArray(),
    vtk.vtkLongArray(),
    vtk.vtkShortArray(),
    vtk.vtkUnsignedCharArray(),
    vtk.vtkUnsignedIntArray(),
    vtk.vtkUnsignedLongArray(),
    vtk.vtkUnsignedLongLongArray(),
    vtk.vtkUnsignedShortArray(),
    vtk.vtkCharArray(),
])
def vtk_array(request):
    array = request.param
    array.SetName('testing_array')
    array.SetNumberOfTuples(3)
    array.SetNumberOfComponents(3)
    array.InsertTuple3(0, 1, 2, 3)
    array.InsertTuple3(1, 4, 5, 6)
    array.InsertTuple3(2, 7, 8, 9)
    return array


@pytest.fixture(params=[
    vtk.vtkDoubleArray(),
    vtk.vtkFloatArray(),