Ejemplo n.º 1
0
    def StructuredPointProbe(self, nx, ny, nz, bounding_box=None):
        """ Probe the unstructured grid dataset using a structured points dataset. """

        probe = vtk.vtkProbeFilter()
        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            probe.SetSource(self.ugrid)
        else:
            probe.SetSourceData(self.ugrid)

        sgrid = vtk.vtkStructuredPoints()

        bbox = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        if bounding_box == None:
            bbox = self.ugrid.GetBounds()
        else:
            bbox = bounding_box

        sgrid.SetOrigin([bbox[0], bbox[2], bbox[4]])

        sgrid.SetDimensions(nx, ny, nz)

        spacing = [0.0, 0.0, 0.0]
        if nx > 1: spacing[0] = (bbox[1] - bbox[0]) / (nx - 1.0)
        if ny > 1: spacing[1] = (bbox[3] - bbox[2]) / (ny - 1.0)
        if nz > 1: spacing[2] = (bbox[5] - bbox[4]) / (nz - 1.0)

        sgrid.SetSpacing(spacing)

        if vtk.vtkVersion.GetVTKMajorVersion() <= 5:
            probe.SetInput(sgrid)
        else:
            probe.SetInputData(sgrid)
        probe.Update()

        return probe.GetOutput()
Ejemplo n.º 2
0
def create_structured_points3D(x, y, z, s):
    """Creates a vtkStructuredPoints object given input data in the
    form of numpy arrays.

    Input Arguments:
       x -- Array of x-coordinates.  These should be regularly spaced.

       y -- Array of y-coordinates.  These should be regularly spaced.

       z -- Array of y-coordinates.  These should be regularly spaced.

       s -- Array of scalar values for the x, y, z values given.  
    """
    nx = len(x)
    ny = len(y)
    nz = len(z)
    ns = N.size(s)
    assert nx*ny*nz == ns, "len(x)*len(y)*len(z) != len(s)"\
               "You passed nx=%d, ny=%d,  nz=%d,  ns=%d"%(nx, ny, nz, ns)
    xmin, ymin, zmin = x[0], y[0], z[0]
    dx, dy, dz= (x[1] - x[0]), (y[1] - y[0]), (z[1] - z[0])
    sp = vtk.vtkStructuredPoints()
    sp.SetDimensions(nx, ny, nz)
    sp.SetOrigin(xmin, ymin, zmin)
    sp.SetSpacing(dx, dy, dz)
    sc = array2vtk(s)
    sp.GetPointData().SetScalars(sc)
    return sp
Ejemplo n.º 3
0
def create_probe(filename):
    if(verbose):
        print "Creating probe from ", filename

    pd = vtk.vtkStructuredPoints()

    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(filename)
    ugrid = reader.GetOutput()
    ugrid.Update()

    b = ugrid.GetBounds()
    pd.SetOrigin(b[0], b[2], b[4])
    l = [b[1] - b[0], b[3] - b[2], b[5] - b[4]]
    tot_len = float(l[0] + l[1] + l[2])
    dims = intervals
    pd.SetExtent(0, dims[0]-1, 0, dims[1] -1, 0, dims[2] -1)
    pd.SetUpdateExtent(0, dims[0]-1, 0, dims[1] -1, 0, dims[2] -1)
    pd.SetWholeExtent(0, dims[0]-1, 0, dims[1] -1, 0, dims[2] -1)
    pd.SetDimensions(dims)
    dims = [max(1, x-1) for x in dims]
    l = [max(1e-3, x) for x in l]
    sp = [l[0]/dims[0], l[1]/dims[1], l[2]/dims[2]]
    pd.SetSpacing(sp)

    return pd
Ejemplo n.º 4
0
def probe_grid(data, resolution=(250, 250, 250)):
    x0, x1, y0, y1, z0, z1 = data.GetBounds()

    if hasattr(data, "GetDimensions"):
        nx, ny, nz = data.GetDimensions()
        log.warning(
            "The data has specific dimensions ({}, {}, {}): ignoring the provided resolution."
            .format(nx, ny, nz))
    else:
        nx, ny, nz = resolution

    struct_p = vtk.vtkStructuredPoints()
    struct_p.SetOrigin(x0, y0, z0)

    struct_p.SetDimensions(nx, ny, nz)
    struct_p.SetSpacing((x1 - x0) / nx, (y1 - y0) / ny, (z1 - z0) / nz)

    probe = vtk.vtkProbeFilter()
    probe.SetInputData(struct_p)
    probe.SetSourceData(data)
    log.warning("Starting probe. The process may take a long time.",
                draw_win=False)
    probe.Update()
    log.warning("Probe complete.", draw_win=False)

    probe_out = probe.GetOutput()

    return probe_out
Ejemplo n.º 5
0
def create_probe(filename):
    if (verbose):
        print "Creating probe from ", filename

    pd = vtk.vtkStructuredPoints()

    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(filename)
    ugrid = reader.GetOutput()
    ugrid.Update()

    b = ugrid.GetBounds()
    pd.SetOrigin(b[0], b[2], b[4])
    l = [b[1] - b[0], b[3] - b[2], b[5] - b[4]]
    tot_len = float(l[0] + l[1] + l[2])
    dims = intervals
    pd.SetExtent(0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1)
    pd.SetUpdateExtent(0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1)
    pd.SetWholeExtent(0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1)
    pd.SetDimensions(dims)
    dims = [max(1, x - 1) for x in dims]
    l = [max(1e-3, x) for x in l]
    sp = [l[0] / dims[0], l[1] / dims[1], l[2] / dims[2]]
    pd.SetSpacing(sp)

    return pd
Ejemplo n.º 6
0
def writePicture(filename,image):
  #image reshape
    imageLength=image.shape[0]
    imageWidth=image.shape[1]
    image=image.reshape(imageLength*imageWidth,1)
  #create a data array to stock these values 
    data_array=vtk.vtkFloatArray()
    data_array.SetNumberOfValues(len(image))
    for i in range(0,len(image)):
      data_array.SetValue(i,image[i][0])

  #create an ImageData called vtkStructuredPoints which stocks the pixel/voxel value of the image 
    strPts=vtk.vtkStructuredPoints()
    strPts.SetDimensions(imageWidth,imageLength,1)
    strPts.SetOrigin(0.,0.,0.)
    strPts.SetExtent(0,imageWidth-1,0,imageLength-1,0,0)
    strPts.SetNumberOfScalarComponents(1)
    strPts.SetScalarTypeToFloat()
    strPts.AllocateScalars()

    strPts.GetPointData().SetScalars(data_array)
    strPts.Update()
  #print the image to an output file 
    writer=vtk.vtkStructuredPointsWriter()
    writer.SetFileName(filename)
    writer.SetInput(strPts)
    writer.Update()
    writer.Write()
Ejemplo n.º 7
0
Archivo: imv.py Proyecto: sldion/DNACC
def _create_structured_points_direct(x, y, z=None):
    """Creates a vtkStructuredPoints object given input data in the
    form of Numeric arrays.

    Input Arguments:
       x -- Array of x-coordinates.  These should be regularly spaced.

       y -- Array of y-coordinates.  These should be regularly spaced.

       z -- Array of z values for the x, y values given.  The values
       should be computed such that the z values are computed as x
       varies fastest and y next.  If z is None then no scalars are
       associated with the structured points.  Only the structured
       points data set is created.
    """

    nx = len(x)
    ny = len(y)
    if z:
        nz = Numeric.size(z)
        assert nx*ny == nz, "len(x)*len(y) != len(z)"\
               "You passed nx=%d, ny=%d,  nz=%d"%(nx, ny, nz)

    xmin, ymin = x[0], y[0]
    dx, dy= (x[1] - x[0]), (y[1] - y[0])

    sp = vtk.vtkStructuredPoints()
    sp.SetDimensions(nx, ny, 1)
    sp.SetOrigin(xmin, ymin, 0)
    sp.SetSpacing(dx, dy, 1)
    if z:
        sc = array2vtk(z)
        sp.GetPointData().SetScalars(sc)
    return sp
Ejemplo n.º 8
0
  def StructuredPointProbe(self, nx, ny, nz, bounding_box=None):
    """ Probe the unstructured grid dataset using a structured points dataset. """

    probe = vtk.vtkProbeFilter ()
    probe.SetSource (self.ugrid)

    sgrid = vtk.vtkStructuredPoints()

    bbox = [0.0,0.0, 0.0,0.0, 0.0,0.0]
    if bounding_box==None:
      bbox = self.ugrid.GetBounds()
    else:
      bbox = bounding_box

    sgrid.SetOrigin([bbox[0], bbox[2], bbox[4]])

    sgrid.SetDimensions(nx, ny, nz)

    spacing = [0.0, 0.0, 0.0]
    if nx>1: spacing[0] = (bbox[1]-bbox[0])/(nx-1.0)
    if ny>1: spacing[1] = (bbox[3]-bbox[2])/(ny-1.0)
    if nz>1: spacing[2] = (bbox[5]-bbox[4])/(nz-1.0)

    sgrid.SetSpacing(spacing)

    probe.SetInput (sgrid)
    probe.Update ()

    return probe.GetOutput()
Ejemplo n.º 9
0
def writePicture(filename, image):
    #image reshape
    imageLength = image.shape[0]
    imageWidth = image.shape[1]
    image = image.reshape(imageLength * imageWidth, 1)
    #create a data array to stock these values
    data_array = vtk.vtkFloatArray()
    data_array.SetNumberOfValues(len(image))
    for i in range(0, len(image)):
        data_array.SetValue(i, image[i][0])

#create an ImageData called vtkStructuredPoints which stocks the pixel/voxel value of the image
    strPts = vtk.vtkStructuredPoints()
    strPts.SetDimensions(imageWidth, imageLength, 1)
    strPts.SetOrigin(0., 0., 0.)
    strPts.SetExtent(0, imageWidth - 1, 0, imageLength - 1, 0, 0)
    strPts.SetNumberOfScalarComponents(1)
    strPts.SetScalarTypeToFloat()
    strPts.AllocateScalars()

    strPts.GetPointData().SetScalars(data_array)
    strPts.Update()
    #print the image to an output file
    writer = vtk.vtkStructuredPointsWriter()
    writer.SetFileName(filename)
    writer.SetInput(strPts)
    writer.Update()
    writer.Write()
Ejemplo n.º 10
0
def main():
    colors = vtk.vtkNamedColors()

    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    vol = vtk.vtkStructuredPoints()
    vol.SetDimensions(26, 26, 26)
    vol.SetOrigin(-0.5, -0.5, -0.5)
    sp = 1.0 / 25.0
    vol.SetSpacing(sp, sp, sp)

    scalars = vtk.vtkDoubleArray()
    scalars.SetNumberOfComponents(1)
    scalars.SetNumberOfTuples(26 * 26 * 26)
    for k in range(0, 26):
        z = -0.5 + k * sp
        kOffset = k * 26 * 26
        for j in range(0, 26):
            y = -0.5 + j * sp
            jOffset = j * 26
            for i in range(0, 26):
                x = -0.5 + i * sp
                s = x * x + y * y + z * z - (0.4 * 0.4)
                offset = i + jOffset + kOffset
                scalars.InsertTuple1(offset, s)
    vol.GetPointData().SetScalars(scalars)

    contour = vtk.vtkContourFilter()
    contour.SetInputData(vol)
    contour.SetValue(0, 0.0)

    volMapper = vtk.vtkPolyDataMapper()
    volMapper.SetInputConnection(contour.GetOutputPort())
    volMapper.ScalarVisibilityOff()
    volActor = vtk.vtkActor()
    volActor.SetMapper(volMapper)
    volActor.GetProperty().EdgeVisibilityOn()
    volActor.GetProperty().SetColor(colors.GetColor3d('Salmon'))
    renderer.AddActor(volActor)
    renderer.SetBackground(colors.GetColor3d('SlateGray'))
    renWin.SetSize(512, 512)
    renWin.SetWindowName('Vol')

    # Interact with the data.
    renWin.Render()

    iren.Start()
Ejemplo n.º 11
0
def VTKNumpytoSP(img_):
    img = img_.T

    H, W = img.shape

    sp = vtk.vtkStructuredPoints()
    sp.SetDimensions(H, W, 1)
    sp.AllocateScalars(10, 1)
    for i in range(H):
        for j in range(W):
            v = img[i, j]
            sp.SetScalarComponentFromFloat(i, j, 0, 0, v)

    return sp
Ejemplo n.º 12
0
 def initialize (self):
     debug ("In StructuredPointsProbe::__init__ ()")
     self.spacing_var = Tkinter.StringVar()
     self.dimension_var = Tkinter.StringVar()
     self.conv_scalar_var = Tkinter.IntVar()
     self.conv_scalar_var.set(1)
     self.p_data = vtk.vtkStructuredPoints()
     self.p_data_gui = None        
     self.init_p_data()
     self.fil = vtk.vtkProbeFilter ()
     self.fil.SetSource (self.prev_fil.GetOutput ())
     self.fil.SetInput(self.p_data)
     self.fil.Update ()
     self.set_scaled_scalars()
     self.pipe_objs = self.fil
Ejemplo n.º 13
0
def simple_test():
    """A simple example of how you can access the methods of a VTK
    object created from Python in C++ using weave.inline.

    """

    a = vtk.vtkStructuredPoints()
    a.SetOrigin(1.0, 1.0, 1.0)
    print("sys.getrefcount(a) = ", sys.getrefcount(a))

    code = r"""
    printf("a->ClassName() == %s\n", a->GetClassName());
    printf("a->GetReferenceCount() == %d\n", a->GetReferenceCount());
    double *origin = a->GetOrigin();
    printf("Origin = %f, %f, %f\n", origin[0], origin[1], origin[2]);
    """
    weave.inline(code, ['a'], include_dirs=inc_dirs, library_dirs=lib_dirs)

    print("sys.getrefcount(a) = ", sys.getrefcount(a))
Ejemplo n.º 14
0
def simple_test():
    """A simple example of how you can access the methods of a VTK
    object created from Python in C++ using weave.inline.

    """

    a = vtk.vtkStructuredPoints()
    a.SetOrigin(1.0, 1.0, 1.0)
    print("sys.getrefcount(a) = ", sys.getrefcount(a))

    code = r"""
    printf("a->ClassName() == %s\n", a->GetClassName());
    printf("a->GetReferenceCount() == %d\n", a->GetReferenceCount());
    double *origin = a->GetOrigin();
    printf("Origin = %f, %f, %f\n", origin[0], origin[1], origin[2]);
    """
    weave.inline(code, ['a'], include_dirs=inc_dirs, library_dirs=lib_dirs)

    print("sys.getrefcount(a) = ", sys.getrefcount(a))
Ejemplo n.º 15
0
    def __init__(self, elements, cell):

        # Make sure element argument is a valid array
        if not isinstance(elements, np.ndarray):
            elements = np.array(elements)

        assert elements.dtype == int and elements.shape == (3,)
        self.elements = elements

        vtkBaseGrid.__init__(self, np.prod(self.elements), cell)

        # Create a VTK grid of structured points
        self.vtk_spts = vtkStructuredPoints()
        self.vtk_spts.SetWholeBoundingBox(self.cell.get_bounding_box())
        self.vtk_spts.SetDimensions(self.elements)
        self.vtk_spts.SetSpacing(self.get_grid_spacing())

        # Extract the VTK point data set
        self.set_point_data(self.vtk_spts.GetPointData())
Ejemplo n.º 16
0
def write(matrix, filename):

    dims = matrix.shape

    flat = matrix.ravel(order='F')

    vtkarray = numpy_support.numpy_to_vtk(flat,
                                          deep=True,
                                          array_type=vtk.VTK_FLOAT)
    vtkarray.SetName("curvatures")

    points = vtk.vtkStructuredPoints()
    points.SetDimensions(dims)
    points.GetPointData().AddArray(vtkarray)

    writer = vtk.vtkStructuredPointsWriter()
    writer.SetFileTypeToBinary()
    writer.SetFileName(filename)
    writer.SetInputData(points)
    writer.Write()
Ejemplo n.º 17
0
Archivo: grid.py Proyecto: lqcata/ase
    def __init__(self, elements, cell, origin=None):

        # Make sure element argument is a valid array
        if not isinstance(elements, np.ndarray):
            elements = np.array(elements)

        assert elements.dtype == int and elements.shape == (3, )
        self.elements = elements

        vtkBaseGrid.__init__(self, np.prod(self.elements), cell)

        # Create a VTK grid of structured points
        self.vtk_spts = vtkStructuredPoints()
        self.vtk_spts.SetWholeBoundingBox(self.cell.get_bounding_box())
        self.vtk_spts.SetDimensions(self.elements)
        self.vtk_spts.SetSpacing(self.get_grid_spacing())

        if origin is not None:
            self.vtk_spts.SetOrigin(origin)

        # Extract the VTK point data set
        self.set_point_data(self.vtk_spts.GetPointData())
Ejemplo n.º 18
0
    def execute_module(self):
        # FIXME: if this module ever becomes anything other than an experiment, build
        # this logic into yet another ProgrammableSource

        # make sure marker is up to date
        self._markerSource.GetStructuredPointsOutput().Update()
        self._maskSource.GetStructuredPointsOutput().Update()

        tempJ = vtk.vtkStructuredPoints()
        tempJ.DeepCopy(self._markerSource.GetStructuredPointsOutput())

        self._imageErode.SetInput(tempJ)

        self._diff = vtk.vtkImageMathematics()
        self._diff.SetOperationToSubtract()

        self._accum = vtk.vtkImageAccumulate()
        self._accum.SetInput(self._diff.GetOutput())

        # now begin our loop
        stable = False
        while not stable:
            # do erosion, get supremum of erosion and mask I
            self._sup.GetOutput().Update()
            # compare this result with tempJ
            self._diff.SetInput1(tempJ)
            self._diff.SetInput2(self._sup.GetOutput())
            self._accum.Update()

            print "%f == %f ?" % (self._accum.GetMin()[0],
                                  self._accum.GetMax()[0])
            if abs(self._accum.GetMin()[0] - self._accum.GetMax()[0]) < 0.0001:
                stable = True
            else:
                # not stable yet...
                print "Trying again..."
                tempJ.DeepCopy(self._sup.GetOutput())
Ejemplo n.º 19
0
    def save(self, image):
        data = dti6to33(self._to_axis_aligned_lps_space(image))
        spacing = image.spacing
        origin = image.origin

        # Convert numpy -> VTK table
        vtk_array = vtkFloatArray()
        vtk_array.SetNumberOfComponents(9)
        vtk_array.SetVoidArray(data, len(data.ravel()), 1)

        # Create VTK dataset
        structured_points = vtkStructuredPoints()
        structured_points.SetDimensions(data.shape[2], data.shape[1],
                                        data.shape[0])
        structured_points.SetSpacing(spacing[2], spacing[1], spacing[0])
        structured_points.SetOrigin(origin[2], origin[1], origin[0])
        structured_points.GetPointData().SetTensors(vtk_array)

        # Write VTK file
        writer = vtkStructuredPointsWriter()
        writer.SetFileName(self._filename)
        writer.SetFileTypeToBinary()
        writer.SetInput(structured_points)
        writer.Update()
Ejemplo n.º 20
0
    def execute_module(self):
        # FIXME: if this module ever becomes anything other than an experiment, build
        # this logic into yet another ProgrammableSource
        
        # make sure marker is up to date
        self._markerSource.GetStructuredPointsOutput().Update()
        self._maskSource.GetStructuredPointsOutput().Update()

        tempJ = vtk.vtkStructuredPoints()
        tempJ.DeepCopy(self._markerSource.GetStructuredPointsOutput())

        self._imageErode.SetInput(tempJ)

        self._diff = vtk.vtkImageMathematics()
        self._diff.SetOperationToSubtract()

        self._accum = vtk.vtkImageAccumulate()
        self._accum.SetInput(self._diff.GetOutput())

        # now begin our loop
        stable = False
        while not stable:
            # do erosion, get supremum of erosion and mask I
            self._sup.GetOutput().Update()
            # compare this result with tempJ
            self._diff.SetInput1(tempJ)
            self._diff.SetInput2(self._sup.GetOutput())
            self._accum.Update()

            print "%f == %f ?" % (self._accum.GetMin()[0], self._accum.GetMax()[0])
            if abs(self._accum.GetMin()[0] - self._accum.GetMax()[0]) < 0.0001:
                stable = True
            else:
                # not stable yet...
                print "Trying again..."
                tempJ.DeepCopy(self._sup.GetOutput())
Ejemplo n.º 21
0
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Image pipeline
image1 = vtk.vtkTIFFReader()
image1.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")
# "beach.tif" image contains ORIENTATION tag which is
# ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
# reader parses this tag and sets the internal TIFF image
# orientation accordingly.  To overwrite this orientation with a vtk
# convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
# SetOrientationType method with parameter value of 4.
image1.SetOrientationType(4)
image1.Update()

sp = vtk.vtkStructuredPoints()
sp.SetDimensions(image1.GetOutput().GetDimensions())
sp.SetExtent(image1.GetOutput().GetExtent())
sp.SetScalarType(
  image1.GetOutput().GetScalarType(), image1.GetOutputInformation(0))
sp.SetNumberOfScalarComponents(
  image1.GetOutput().GetNumberOfScalarComponents(),
  image1.GetOutputInformation(0))
sp.GetPointData().SetScalars(image1.GetOutput().GetPointData().GetScalars())

luminance = vtk.vtkImageLuminance()
luminance.SetInputData(sp)

# Let's create a dictionary to test the writers, the key will be the writer
# and the value the file name used by the writer.
filenames = ["tiff1.tif", "tiff2.tif", "bmp1.bmp", "bmp2.bmp",
Ejemplo n.º 22
0
x1 = bounds[1]
xdm1 = x1 - x0
xd = int(x1 - x0 + 1)
y0 = bounds[2]
y1 = bounds[3]
ydm1 = y1 - y0
yd = int(y1 - y0 + 1)
z0 = bounds[4]
z1 = bounds[5]
zdm1 = z1 - z0
zd = int(z1 - z0 + 1)
print "DATA DIMENSIONS ARE: %d %d %d" % (xd, yd, zd)

vecinfo = reader.GetOutput().GetPointData().GetVectors()

curlData = vtk.vtkStructuredPoints()
curlData.SetDimensions(xd, yd, zd)
curlData.SetSpacing(1, 1, 1)
curlData.SetOrigin(0, 0, 0)

divData = vtk.vtkStructuredPoints()
divData.SetDimensions(xd, yd, zd)
divData.SetSpacing(1, 1, 1)
divData.SetOrigin(0, 0, 0)

curlmagData = vtk.vtkStructuredPoints()
curlmagData.SetDimensions(xd, yd, zd)
curlmagData.SetSpacing(1, 1, 1)
curlmagData.SetOrigin(0, 0, 0)

div = vtk.vtkFloatArray()
Ejemplo n.º 23
0
def write_vti(filename, atoms, data=None):
    from vtk import vtkStructuredPoints, vtkDoubleArray, vtkXMLImageDataWriter

    #if isinstance(fileobj, str):
    #    fileobj = paropen(fileobj, 'w')
        
    if isinstance(atoms, list):
        if len(atoms) > 1:
            raise ValueError('Can only write one configuration to a VTI file!')
        atoms = atoms[0]

    if data is None:
        raise ValueError('VTK XML Image Data (VTI) format requires data!')

    data = np.asarray(data)

    if data.dtype == complex:
        data = np.abs(data)

    cell = atoms.get_cell()

    assert np.all(cell==np.diag(cell.diagonal())), 'Unit cell must be orthogonal'

    bbox = np.array(list(zip(np.zeros(3),cell.diagonal()))).ravel()

    # Create a VTK grid of structured points
    spts = vtkStructuredPoints()
    spts.SetWholeBoundingBox(bbox)
    spts.SetDimensions(data.shape)
    spts.SetSpacing(cell.diagonal() / data.shape)
    #spts.SetSpacing(paw.gd.h_c * Bohr)

    #print 'paw.gd.h_c * Bohr=',paw.gd.h_c * Bohr
    #print 'atoms.cell.diagonal() / data.shape=', cell.diagonal()/data.shape
    #assert np.all(paw.gd.h_c * Bohr==cell.diagonal()/data.shape)

    #s = paw.wfs.kpt_u[0].psit_nG[0].copy()
    #data = paw.get_pseudo_wave_function(band=0, kpt=0, spin=0, pad=False)
    #spts.point_data.scalars = data.swapaxes(0,2).flatten()
    #spts.point_data.scalars.name = 'scalars'

    # Allocate a VTK array of type double and copy data
    da = vtkDoubleArray()
    da.SetName('scalars')
    da.SetNumberOfComponents(1)
    da.SetNumberOfTuples(np.prod(data.shape))

    for i,d in enumerate(data.swapaxes(0,2).flatten()):
        da.SetTuple1(i,d)

    # Assign the VTK array as point data of the grid
    spd = spts.GetPointData() # type(spd) is vtkPointData
    spd.SetScalars(da)

    """
    from vtk.util.vtkImageImportFromArray import vtkImageImportFromArray
    iia = vtkImageImportFromArray()
    #iia.SetArray(Numeric_asarray(data.swapaxes(0,2).flatten()))
    iia.SetArray(Numeric_asarray(data))
    ida = iia.GetOutput()
    ipd = ida.GetPointData()
    ipd.SetName('scalars')
    spd.SetScalars(ipd.GetScalars())
    """

    # Save the ImageData dataset to a VTK XML file.
    w = vtkXMLImageDataWriter()

    if fast:
        w.SetDataModeToAppend()
        w.EncodeAppendedDataOff()
    else:
        w.SetDataModeToAscii()

    w.SetFileName(filename)
    w.SetInput(spts)
    w.Write()
Ejemplo n.º 24
0
def vtkrender(d1=None, d2=None):
    
    x = (arange(50.0)-25)/2.0
    y = (arange(50.0)-25)/2.0
    r = sqrt(x[:]**2+y**2)
    z = 5.0*signal.special.j0(r)  # Bessel function of order 0
    z1 = reshape(transpose(z), (-1,))
    point_data = vtk.vtkPointData(vtk.vtkScalars(z1))
    grid = vtk.vtkStructuredPoints((50,50, 1), (-12.5, -12.5, 0), (0.5, 0.5, 1))
    data = vtk.VtkData(grid, point_data)
    data.tofile('/tmp/test.vtk')
    d1 = d2 = '/tmp/test.vtk'
    
    #v2,v1,data1,data2 = inputs()
    if d1 == None:
        d1 = "/home/danc/E0058brain.vtk"
        #d1 = "/home/danc/vtk/data1.vtk"
    if d2 == None:
        d2 = "/home/danc/E0058MEG.vtk"
        #d2='/home/danc/vtk/data2.vtk'
        #d2 = "/home/danc/mrvtk_0003overlay.vtk"


    v1 = vtk.vtkStructuredPointsReader()

    #v1.SetFileName("/home/danc/mrvtk.vtk")
    v1.SetFileName(d1)
    v2 = vtk.vtkStructuredPointsReader()
    #v2.SetFileName("/home/danc/mrvtk_overlay.vtk")
    v2.SetFileName(d2)
    v1.SetLookupTableName('/home/danc/colortable.lut')
    v1.SetReadAllColorScalars
    v1.Update()
    v2.Update()


    global xMax, xMin, yMin, yMax, zMin, zMax, current_widget, slice_number
    xMin, xMax, yMin, yMax, zMin, zMax = v1.GetOutput().GetWholeExtent()

    spacing = v1.GetOutput().GetSpacing()
    sx, sy, sz = spacing

    origin = v1.GetOutput().GetOrigin()
    ox, oy, oz = origin

    # An outline is shown for context.
    outline = vtk.vtkOutlineFilter()
    outline.SetInput(v1.GetOutput())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInput(outline.GetOutput())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)
    outlineActor.GetProperty().SetColor(1,1,1)

    # The shared picker enables us to use 3 planes at one time
    # and gets the picking order right
    picker = vtk.vtkCellPicker()
    picker.SetTolerance(0.005)

    # The 3 image plane widgets are used to probe the dataset.
    planeWidgetX = vtk.vtkImagePlaneWidget()
    planeWidgetX.DisplayTextOn()
    planeWidgetX.SetInput(v1.GetOutput())
    planeWidgetX.SetPlaneOrientationToXAxes()
    planeWidgetX.SetSliceIndex(int(round(xMax/2)))
    planeWidgetX.SetPicker(picker)
    planeWidgetX.SetKeyPressActivationValue("x")
    planeWidgetX.GetPlaneProperty().SetDiffuseColor((0,1,1))
    #planeWidgetX.GetPlaneProperty().SetColor(0,1,1)
    #planeWidgetX.GetPlaneProperty().SetSpecularColor(0,1,1)
    #planeWidgetX.GetPlaneProperty().SetAmbientColor(0,1,1)
    planeWidgetX.GetPlaneProperty().SetFrontfaceCulling(10)
    planeWidgetX.GetPlaneProperty().SetRepresentationToWireframe
    #planeWidgetX.GetColorMap()
    #print planeWidgetX.GetColorMap()
    #planeWidgetX.SetHueRange(0.667,0.0)
    #planeWidgetX.SetLookupTable('/home/danc/colortable.lut')

    prop1 = planeWidgetX.GetPlaneProperty()
    prop1.SetDiffuseColor(1, 0, 0)
    prop1.SetColor(1,0,0)
    prop1.SetSpecularColor(0, 1, 1)
    #print planeWidgetX.GetLookupTable()
    g = planeWidgetX.GetLookupTable()
    #print g



##    arrow = vtk.vtkArrowSource()
####    arrow.SetShaftRadius(100)
####    arrow.SetShaftResolution(80)
####    arrow.SetTipRadius(100)
####    arrow.SetTipLength(1000)
####    #arrow.SetTipResolution(80)
##    arrowMapper = vtk.vtkPolyDataMapper()
##    arrowMapper.SetInput(arrow.GetOutput())
##    arrowActor = vtk.vtkActor()
##    arrowActor.SetMapper(arrowMapper)
##    arrowActor.SetPosition(0, 0, 0)
##    arrowActor.GetProperty().SetColor(0, 1, 0)


    planeWidgetY = vtk.vtkImagePlaneWidget()
    planeWidgetY.DisplayTextOn()
    planeWidgetY.SetInput(v1.GetOutput())
    planeWidgetY.SetPlaneOrientationToYAxes()
    planeWidgetY.SetSliceIndex(int(round(yMax/2)))
    planeWidgetY.SetPicker(picker)
    planeWidgetY.SetKeyPressActivationValue("y")
    prop2 = planeWidgetY.GetPlaneProperty()
    prop2.SetColor(1, 1, 0)
    planeWidgetY.SetLookupTable(planeWidgetX.GetLookupTable())
    planeWidgetY.GetPlaneProperty().SetDiffuseColor(0,1,1)


    # for the z-slice, turn off texture interpolation:
    # interpolation is now nearest neighbour, to demonstrate
    # cross-hair cursor snapping to pixel centers
    planeWidgetZ = vtk.vtkImagePlaneWidget()

    planeWidgetZ.SetSliceIndex(100)
    planeWidgetZ.SetSlicePosition(100)
    planeWidgetZ.DisplayTextOn()
    planeWidgetZ.SetInput(v1.GetOutput())
    planeWidgetZ.SetPlaneOrientationToZAxes()
    planeWidgetZ.SetSliceIndex(int(round(yMax/2)))
    planeWidgetZ.SetPicker(picker)
    planeWidgetZ.SetKeyPressActivationValue("z")
    prop3 = planeWidgetZ.GetPlaneProperty()
    prop3.SetColor(0, 0, 1)
    planeWidgetZ.SetLookupTable(planeWidgetX.GetLookupTable())
    planeWidgetZ.GetPlaneProperty().SetDiffuseColor(0,1,1)

    filelist = [v2,v1];
    for i in filelist:


        coloroniso = vtk.vtkStructuredPointsReader()
        coloroniso.SetFileName(i.GetFileName())
        coloroniso.SetScalarsName("colors")
        coloroniso.Update()

        isosurface = vtk.vtkStructuredPointsReader()
        isosurface.SetFileName(i.GetFileName())
        isosurface.SetScalarsName("scalars")
        isosurface.Update()

        iso = vtk.vtkContourFilter()
        iso.SetInput(i.GetOutput())
        #iso.SetInput(isosurface.GetOutput())
        if i == v1:
            iso.SetValue(0, 20)
        else:
            iso.SetValue(0,10)
        #iso.SetNumberOfContours(10)

        probe = vtk.vtkProbeFilter()
        probe.SetInput(iso.GetOutput())
        probe.SetSource(coloroniso.GetOutput())

        cast = vtk.vtkCastToConcrete()
        cast.SetInput(probe.GetOutput())

        normals = vtk.vtkPolyDataNormals()
        #normals.SetMaxRecursionDepth(100)
        normals.SetInput(cast.GetPolyDataOutput())
        normals.SetFeatureAngle(45)

    ##    clut = vtk.vtkLookupTable()
    ##    clut.SetHueRange(0, .67)
    ##    clut.Build()
    ##    clut.SetValueRange(coloroniso.GetOutput().GetScalarRange())


    ##    normals = vtk.vtkPolyDataNormals()
    ##    normals.SetInput(iso.GetOutput())
    ##    normals.SetFeatureAngle(45)
        isoMapper = vtk.vtkPolyDataMapper()
        isoMapper.SetInput(normals.GetOutput())
        isoMapper.ScalarVisibilityOn()
        #isoMapper.SetColorModeToMapScalars()
        isoMapper.ColorByArrayComponent(0, 100)#("VelocityMagnitude", 0)

        isoMapper.SetScalarRange([1, 200])
    ##    isoMapper.SetLookupTable(clut)

        isoActor = vtk.vtkActor()
        isoActor.SetMapper(isoMapper)

    ##    isoActor.GetProperty().SetDiffuseColor([.5,.5,.5])
    ##    isoActor.GetProperty().SetSpecularColor([1,1,1])
    ##    isoActor.GetProperty().SetDiffuse(.5)
    ##    isoActor.GetProperty().SetSpecular(.5)
    ##    isoActor.GetProperty().SetSpecularPower(15)
    ##    isoActor.GetProperty().SetOpacity(.6)

        isoActor.GetProperty().SetDiffuseColor(1, .2, .2)
        isoActor.GetProperty().SetSpecular(.7)
        isoActor.GetProperty().SetSpecularPower(20)
        isoActor.GetProperty().SetOpacity(0.5)


        if i == v1:
            print 'under'
            isoActorUnderlay = isoActor
        else:
            print 'over'
            isoActorOverlay = isoActor




    # Create the RenderWindow and Renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

    # Add the outline actor to the renderer, set the background color and size
    ren.AddActor(outlineActor)
    #ren.AddActor(sphereActor)


    renWin.SetSize(700, 700)
    ren.SetBackground(0, 0, 0)

    current_widget = planeWidgetZ
    mode_widget = planeWidgetZ

    # Create the GUI
    # We first create the supporting functions (callbacks) for the GUI
    #
    # Align the camera so that it faces the desired widget
    def AlignCamera():
        #global ox, oy, oz, sx, sy, sz, xMax, xMin, yMax, yMin, zMax, \
        #      zMin, slice_number
        #global current_widget
        cx = ox+(0.5*(xMax-xMin))*sx
        cy = oy+(0.5*(yMax-yMin))*sy
        cz = oy+(0.5*(zMax-zMin))*sz
        vx, vy, vz = 0, 0, 0
        nx, ny, nz = 0, 0, 0
        iaxis = current_widget.GetPlaneOrientation()
        if iaxis == 0:
            vz = -1
            nx = ox + xMax*sx
            cx = ox + slice_number*sx
        elif iaxis == 1:
            vz = -1
            ny = oy+yMax*sy
            cy = oy+slice_number*sy
        else:
            vy = 1
            nz = oz+zMax*sz
            cz = oz+slice_number*sz

        px = cx+nx*2
        py = cy+ny*2
        pz = cz+nz*3

        camera = ren.GetActiveCamera()
        camera.SetViewUp(vx, vy, vz)
        camera.SetFocalPoint(cx, cy, cz)
        camera.SetPosition(px, py, pz)
        camera.OrthogonalizeViewUp()
        ren.ResetCameraClippingRange()
        renWin.Render()

    # Capture the display and place in a tiff
    def CaptureImage():
        w2i = vtk.vtkWindowToImageFilter()
        writer = vtk.vtkTIFFWriter()
        w2i.SetInput(renWin)
        w2i.Update()
        writer.SetInput(w2i.GetOutput())
        writer.SetFileName("/home/danc/image.tif")
        renWin.Render()
        writer.Write()


    # Align the widget back into orthonormal position,
    # set the slider to reflect the widget's position,
    # call AlignCamera to set the camera facing the widget
    def AlignXaxis():
        global xMax, xMin, current_widget, slice_number
        po = planeWidgetX.GetPlaneOrientation()
        if po == 3:
            planeWidgetX.SetPlaneOrientationToXAxes()
            slice_number = (xMax-xMin)/2
            planeWidgetX.SetSliceIndex(slice_number)
        else:
            slice_number = planeWidgetX.GetSliceIndex()

        current_widget = planeWidgetX

        slice.config(from_=xMin, to=xMax)
        slice.set(slice_number)
        AlignCamera()


    def AlignYaxis():
        global yMin, yMax, current_widget, slice_number
        po = planeWidgetY.GetPlaneOrientation()
        if po == 3:
            planeWidgetY.SetPlaneOrientationToYAxes()
            slice_number = (yMax-yMin)/2
            planeWidgetY.SetSliceIndex(slice_number)
        else:
            slice_number = planeWidgetY.GetSliceIndex()

        current_widget = planeWidgetY

        slice.config(from_=yMin, to=yMax)
        slice.set(slice_number)
        AlignCamera()

    def AlignZaxis():
        global yMin, yMax, current_widget, slice_number
        po = planeWidgetZ.GetPlaneOrientation()
        if po == 3:
            planeWidgetZ.SetPlaneOrientationToZAxes()
            slice_number = (zMax-zMin)/2
            planeWidgetZ.SetSliceIndex(slice_number)
        else:
            slice_number = planeWidgetZ.GetSliceIndex()

        current_widget = planeWidgetZ

        slice.config(from_=zMin, to=zMax)
        slice.set(slice_number)
        AlignCamera()

    ##################def flag(sw):


    def underlay():
        print 'under'
        global overunderstatus
        overunderstatus = 'under'
        isoActor = isoActorUnderlay
        u_button.config(relief='sunken')
        o_button.config(relief='raised')
        six=planeWidgetX.GetSliceIndex()
        siy=planeWidgetY.GetSliceIndex()
        siz=planeWidgetZ.GetSliceIndex()
        data = v1
        planeWidgetX.SetInput(data.GetOutput())
        planeWidgetY.SetInput(data.GetOutput())
        planeWidgetZ.SetInput(data.GetOutput())
        planeWidgetX.SetSliceIndex(six)
        planeWidgetY.SetSliceIndex(siy)
        planeWidgetZ.SetSliceIndex(siz)
        renWin.Render()


    def overlay():
        print 'over'
        global overunderstatus
        overunderstatus = 'over'
        isoActor = isoActorOverlay
        o_button.config(relief='sunken')
        u_button.config(relief='raised')
        six=planeWidgetX.GetSliceIndex()
        siy=planeWidgetY.GetSliceIndex()
        siz=planeWidgetZ.GetSliceIndex()
        data = v2
        planeWidgetX.SetInput(data.GetOutput())
        planeWidgetY.SetInput(data.GetOutput())
        planeWidgetZ.SetInput(data.GetOutput())
        planeWidgetX.SetSliceIndex(six)
        planeWidgetY.SetSliceIndex(siy)
        planeWidgetZ.SetSliceIndex(siz)
        renWin.Render()


    def render3d():
        print '3d rend'
        global buttonpos
        try:
            if overunderstatus == 'under':
                isoActor = isoActorUnderlay
            else:
                isoActor = isoActorOverlay
        except NameError:
            isoActor = isoActorUnderlay
        try:
            buttonpos
            print buttonpos
        except NameError:
            buttonpos = 0
            print buttonpos
            r_button.config(relief='sunken')
            ren.AddActor(isoActor)

            renWin.Render()
        else:
            if buttonpos == 0:
                buttonpos = 1
                r_button.config(relief='raised')
                ren.RemoveActor(isoActor)
                ren.RemoveActor(isoActorUnderlay)
                ren.RemoveActor(isoActorOverlay)
                renWin.Render()
            else:
                buttonpos = 0
                r_button.config(relief='sunken')
                print o_button
                ren.AddActor(isoActor)
                renWin.Render()
        return buttonpos

    # Set the widget's reslice interpolation mode
    # to the corresponding popup menu choice
    def SetInterpolation():
        global mode_widget, mode
        if mode.get() == 0:
            mode_widget.TextureInterpolateOff()
        else:
            mode_widget.TextureInterpolateOn()

        mode_widget.SetResliceInterpolate(mode.get())
        renWin.Render()

    # Share the popup menu among buttons, keeping track of associated
    # widget's interpolation mode
    def buttonEvent(event, arg=None):
        global mode, mode_widget, popm
        if arg == 0:
            mode_widget = planeWidgetX
        elif arg == 1:
            mode_widget = planeWidgetY
        elif arg == 2:
            mode_widget = planeWidgetZ
        else:
            return
        mode.set(mode_widget.GetResliceInterpolate())
        popm.entryconfigure(arg, variable=mode)
        popm.post(event.x + event.x_root, event.y + event.y_root)

    def SetSlice(sl):
        global current_widget
        current_widget.SetSliceIndex(int(sl))
        ren.ResetCameraClippingRange()
        renWin.Render()


    ###
    # Now actually create the GUI
    root = Tkinter.Tk()
    root.withdraw()
    top = Tkinter.Toplevel(root)

    # Define a quit method that exits cleanly.
    def quit(obj=root):
        print obj
        obj.quit()
        obj.destroy()
        #vtkrender.destroy()


    # Popup menu
    popm = Tkinter.Menu(top, tearoff=0)
    mode = Tkinter.IntVar()
    mode.set(1)
    popm.add_radiobutton(label="nearest", variable=mode, value=0,
                         command=SetInterpolation)
    popm.add_radiobutton(label="linear", variable=mode, value=1,
                         command=SetInterpolation)
    popm.add_radiobutton(label="cubic", variable=mode, value=2,
                         command=SetInterpolation)

    display_frame = Tkinter.Frame(top)
    display_frame.pack(side="top", anchor="n", fill="both", expand="false")

    # Buttons
    ctrl_buttons = Tkinter.Frame(top)
    ctrl_buttons.pack(side="top", anchor="n", fill="both", expand="false")

    quit_button = Tkinter.Button(ctrl_buttons, text="Quit", command=quit)
    capture_button = Tkinter.Button(ctrl_buttons, text="Tif",
                                    command=CaptureImage)
    quit_button.config(background='#C0C0C0')

    x_button = Tkinter.Button(ctrl_buttons, text="x", command=AlignXaxis)
    y_button = Tkinter.Button(ctrl_buttons, text="y", command=AlignYaxis)
    z_button = Tkinter.Button(ctrl_buttons, text="z", command=AlignZaxis)
    u_button = Tkinter.Button(ctrl_buttons, text="underlay", command=underlay)
    o_button = Tkinter.Button(ctrl_buttons, text="overlay", command=overlay)
    r_button = Tkinter.Button(ctrl_buttons, text="3d render", command=render3d)
    o_button.config(background='#FFFFFF')
    u_button.config(relief='sunken')



    x_button.bind("<Button-3>", lambda e: buttonEvent(e, 0))
    y_button.bind("<Button-3>", lambda e: buttonEvent(e, 1))
    z_button.bind("<Button-3>", lambda e: buttonEvent(e, 2))
    u_button.bind("<Button-3>", lambda e: buttonEvent(e, 3))
    o_button.bind("<Button-3>", lambda e: buttonEvent(e, 4))
    r_button.bind("<Button-3>", lambda e: buttonEvent(e, 5))

    for i in (quit_button, capture_button, x_button, y_button, z_button, u_button, o_button, r_button):
        i.pack(side="left", expand="true", fill="both")


    # Create the render widget
    renderer_frame = Tkinter.Frame(display_frame)
    renderer_frame.pack(padx=3, pady=3,side="left", anchor="n",
                        fill="both", expand="false")

    render_widget = vtkTkRenderWindowInteractor(renderer_frame,
                                                rw=renWin, width=600,
                                                height=600)
    for i in (render_widget, display_frame):
        i.pack(side="top", anchor="n",fill="both", expand="false")

    # Add a slice scale to browse the current slice stack
    slice_number = Tkinter.IntVar()
    slice_number.set(current_widget.GetSliceIndex())
    slice = Tkinter.Scale(top, from_=zMin, to=zMax, orient="horizontal",
                          command=SetSlice,variable=slice_number,
                          label="Slice")
    slice.pack(fill="x", expand="false")

    # Done with the GUI.
    ###

    # Set the interactor for the widgets
    iact = render_widget.GetRenderWindow().GetInteractor()
    planeWidgetX.SetInteractor(iact)
    planeWidgetX.On()
    planeWidgetY.SetInteractor(iact)
    planeWidgetY.On()
    planeWidgetZ.SetInteractor(iact)
    planeWidgetZ.On()

    # Create an initial interesting view
    cam1 = ren.GetActiveCamera()
    cam1.Elevation(210)
    cam1.SetViewUp(1, -1, 1)
    cam1.Azimuth(-145)
    ren.ResetCameraClippingRange()

    # Render it
    render_widget.Render()

    iact.Initialize()
    renWin.Render()
    iact.Start()

    # Start Tkinter event loop
    root.mainloop()
Ejemplo n.º 25
0
def write_vti(filename, atoms, data=None):
    from vtk import vtkStructuredPoints, vtkDoubleArray, vtkXMLImageDataWriter

    # if isinstance(fileobj, str):
    #     fileobj = paropen(fileobj, 'w')

    if isinstance(atoms, list):
        if len(atoms) > 1:
            raise ValueError('Can only write one configuration to a VTI file!')
        atoms = atoms[0]

    if data is None:
        raise ValueError('VTK XML Image Data (VTI) format requires data!')

    data = np.asarray(data)

    if data.dtype == complex:
        data = np.abs(data)

    cell = atoms.get_cell()

    if not np.all(cell == np.diag(np.diag(cell))):
        raise ValueError('Unit cell must be orthogonal')

    bbox = np.array(list(zip(np.zeros(3), cell.diagonal()))).ravel()

    # Create a VTK grid of structured points
    spts = vtkStructuredPoints()
    spts.SetWholeBoundingBox(bbox)
    spts.SetDimensions(data.shape)
    spts.SetSpacing(cell.diagonal() / data.shape)
    # spts.SetSpacing(paw.gd.h_c * Bohr)

    # print('paw.gd.h_c * Bohr=',paw.gd.h_c * Bohr)
    # print('atoms.cell.diagonal() / data.shape=', cell.diagonal()/data.shape)
    # assert np.all(paw.gd.h_c * Bohr==cell.diagonal()/data.shape)

    # s = paw.wfs.kpt_u[0].psit_nG[0].copy()
    # data = paw.get_pseudo_wave_function(band=0, kpt=0, spin=0, pad=False)
    # spts.point_data.scalars = data.swapaxes(0,2).flatten()
    # spts.point_data.scalars.name = 'scalars'

    # Allocate a VTK array of type double and copy data
    da = vtkDoubleArray()
    da.SetName('scalars')
    da.SetNumberOfComponents(1)
    da.SetNumberOfTuples(np.prod(data.shape))

    for i, d in enumerate(data.swapaxes(0, 2).flatten()):
        da.SetTuple1(i, d)

    # Assign the VTK array as point data of the grid
    spd = spts.GetPointData()  # type(spd) is vtkPointData
    spd.SetScalars(da)
    """
    from vtk.util.vtkImageImportFromArray import vtkImageImportFromArray
    iia = vtkImageImportFromArray()
    #iia.SetArray(Numeric_asarray(data.swapaxes(0,2).flatten()))
    iia.SetArray(Numeric_asarray(data))
    ida = iia.GetOutput()
    ipd = ida.GetPointData()
    ipd.SetName('scalars')
    spd.SetScalars(ipd.GetScalars())
    """

    # Save the ImageData dataset to a VTK XML file.
    w = vtkXMLImageDataWriter()

    if fast:
        w.SetDataModeToAppend()
        w.EncodeAppendedDataOff()
    else:
        w.SetDataModeToAscii()

    w.SetFileName(filename)
    w.SetInput(spts)
    w.Write()
Ejemplo n.º 26
0
import numpy as np
import vtk
from vtk.util import numpy_support

### STRUCTURED_POINTS - SCALARS ###
reader = vtk.vtkStructuredPointsReader()
reader.SetFileName("fMag.0001.vtk")
reader.Update()
vtk_data = reader.GetOutput()
scalar_data = numpy_support.vtk_to_numpy(vtk_data.GetPointData().GetScalars())
mesh_shape = vtk_data.GetDimensions()
origin = vtk_data.GetOrigin()
spacing = vtk_data.GetSpacing()
scalar_data_vtk = numpy_support.numpy_to_vtk(scalar_data)
scalar_data_vtk.SetName('fMag')
vtk_obj = vtk.vtkStructuredPoints()
vtk_obj.SetDimensions(mesh_shape)
vtk_obj.SetOrigin(origin)
vtk_obj.SetSpacing(spacing)
vtk_obj.GetPointData().SetScalars(scalar_data_vtk)
writer = vtk.vtkGenericDataObjectWriter()
writer.SetFileName("test_out.vtk")
writer.SetInputDataObject(vtk_obj)
writer.Update()
writer.Write()  # returns 1 on success, 0 on failure

### STRUCTURED_POINTS - VECTORS ###
reader = vtk.vtkStructuredPointsReader()
reader.SetFileName("u.0001.vtk")
reader.Update()
vtk_data = reader.GetOutput()
Ejemplo n.º 27
0
import vtk
import sys

infile = sys.argv[1]
dimsin = sys.argv[2]

inbits = infile.split(".")
outputfile = inbits[0] + ".bin"

sgr = vtk.vtkStructuredGridReader()
sgr.SetFileName(infile)
sgr.Update()

p_data = vtk.vtkStructuredPoints()
fil = vtk.vtkProbeFilter()
fil.SetSource(sgr.GetOutput())
fil.SetInput(p_data)
fil.Update()

pd = p_data
out = sgr.GetOutput()
b = out.GetBounds()
pd.SetOrigin(b[0], b[2], b[4])
l = [b[1] - b[0], b[3] - b[2], b[5] - b[4]]
tot_len = float(l[0] + l[1] + l[2])
npnt = pow(out.GetNumberOfPoints(), 1. / 3.) + 0.5
fac = 3.0 * npnt / tot_len
dims = eval(dimsin)
pd.SetExtent(0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1)
pd.SetUpdateExtent(0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1)
pd.SetWholeExtent(0, dims[0] - 1, 0, dims[1] - 1, 0, dims[2] - 1)
Ejemplo n.º 28
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Example of "structured points" dataset
#   vtkStructuredPoints is a child class of vtkImageData

import vtk

dx = 0.2
grid = vtk.vtkStructuredPoints()
#grid = vtk.vtkImageData()
grid.SetOrigin(0.1, 0.1, 0.1) # default values
grid.SetSpacing(dx, dx, dx)
grid.SetDimensions(5, 8, 10) # number of points in each direction

array = vtk.vtkDoubleArray()
array.SetNumberOfComponents(1) # this is 3 for a vector
array.SetNumberOfTuples(grid.GetNumberOfPoints())
for i in range(grid.GetNumberOfPoints()):
    array.SetValue(i, i/2.0)
grid.GetPointData().AddArray(array)
array.SetName("my_data1")


# write structured points to disk...
writer = vtk.vtkStructuredPointsWriter()
writer.SetInputData(grid)
writer.SetFileName("points.vtk")
writer.Write()

writer = vtk.vtkXMLImageDataWriter()
Ejemplo n.º 29
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Example of "structured points" dataset
#   vtkStructuredPoints is a child class of vtkImageData

import vtk

dx = 0.2
grid = vtk.vtkStructuredPoints()
#grid = vtk.vtkImageData()
grid.SetOrigin(0, 0, 0)  # default values
grid.SetSpacing(dx, dx, dx)
grid.SetDimensions(5, 8, 10)  # number of points in each direction

array = vtk.vtkDoubleArray()
array.SetNumberOfComponents(1)  # this is 3 for a vector
array.SetNumberOfTuples(grid.GetNumberOfPoints())
for i in range(grid.GetNumberOfPoints()):
    array.SetValue(i, i)
grid.GetPointData().AddArray(array)
array.SetName("my_data1")

# write structured points to disk...
writer = vtk.vtkStructuredPointsWriter()
writer.SetInputData(grid)
writer.SetFileName("points.vtk")
writer.Write()

# display grid... (to be finished)
    def array2vtk(self,
                  array,
                  final_filename,
                  path,
                  origin=[0, 0, 0],
                  spacing=[1, 1, 1]):
        """
        Convert array into .vtk file
        
        - Params:
            inherited class parameters (see description at beginning of the class)
            array: array to be converted into .vtk file
            flag: parameter specifying if what is saved is a contour image or a binary mask
                'contour': contour is saved
                'binary': binary mask is saved
            origin: origin of coordinate system, by default (0,0,0)
            spacing: spacing of coordinate system, by default (1,1,1)
        
        """

        vtk_writer = vtk.vtkStructuredPointsWriter()

        # Check if destination folder exists

        #print('Checking if destination folder exists\n')

        isdir = os.path.isdir(path)

        if not isdir:

            os.makedirs(path)

            print('Non-existing destination path. Created\n')

        # Check if files already exist in destination folder

        overwrite = 'y'

        exist = final_filename in os.listdir(path)

        if exist:

            overwrite = input(
                "File is already in folder. Do you want to overwrite? [y/n]")

        if overwrite == 'y' or overwrite == 'Y':

            vtk_writer.SetFileName(path + final_filename)

        else:

            print('\nOperation aborted\n')

        vtk_im = vtk.vtkStructuredPoints()

        vtk_im.SetDimensions((array.shape[1], array.shape[0], array.shape[2]))

        vtk_im.SetOrigin(origin)

        vtk_im.SetSpacing(spacing)

        pdata = vtk_im.GetPointData()

        vtk_array = numpy_to_vtk(array.swapaxes(0, 1).ravel(order='F'), deep=1)

        pdata.SetScalars(vtk_array)

        #vtk_writer.SetFileType(VTK_BINARY)

        vtk_writer.SetInputData(vtk_im)

        vtk_writer.Update()
Ejemplo n.º 31
0
def main():
    colors = vtk.vtkNamedColors()

    Pr = 10.0  # The Lorenz parameters
    b = 2.667
    r = 28.0
    # x = 0.0
    # y = 0.0
    # z = 0.0  # starting (and current) x, y, z
    h = 0.01  # integration step size
    resolution = 200  # slice resolution
    iterations = 10000000  # number of iterations
    xmin = -30.0  # x, y, z range for voxels
    xmax = 30.0
    ymin = -30.0
    ymax = 30.0
    zmin = -10.0
    zmax = 60.0

    # Take a stab at an integration step size.
    xIncr = resolution / (xmax - xmin)
    yIncr = resolution / (ymax - ymin)
    zIncr = resolution / (zmax - zmin)

    print('The Lorenz Attractor\n')
    print(' Pr =', Pr)
    print(' b =', b)
    print(' r =', r)
    print(' integration step size =', h)
    print(' slice resolution =', resolution)
    print(' # of iterations =', iter)
    print(' specified range:')
    print('     x: {:f}, {:f}'.format(xmin, xmax))
    print('     y: {:f}, {:f}'.format(ymin, ymax))
    print('     z: {:f}, {:f}'.format(zmin, zmax))

    randomSequence = vtk.vtkMinimalStandardRandomSequence()
    randomSequence.SetSeed(8775070)
    x = randomSequence.GetRangeValue(xmin, xmax)
    randomSequence.Next()
    y = randomSequence.GetRangeValue(ymin, ymax)
    randomSequence.Next()
    z = randomSequence.GetRangeValue(zmin, zmax)
    randomSequence.Next()
    print(' starting at {:f}, {:f}, {:f}'.format(x, y, z))
    # allocate memory for the slices
    sliceSize = resolution * resolution
    numPts = sliceSize * resolution
    scalars = vtk.vtkShortArray()
    for i in range(0, numPts):
        scalars.InsertTuple1(i, 0)
    for j in range(0, iterations):
        # Integrate to the next time step.
        xx = x + h * Pr * (y - x)
        yy = y + h * (x * (r - z) - y)
        zz = z + h * (x * y - (b * z))

        x = xx
        y = yy
        z = zz

        # Calculate the voxel index.
        if xmax > x > xmin and ymax > y > ymin and zmax > z > zmin:
            xxx = int(float(xx - xmin) * xIncr)
            yyy = int(float(yy - ymin) * yIncr)
            zzz = int(float(zz - zmin) * zIncr)
            index = xxx + yyy * resolution + zzz * sliceSize
            scalars.SetTuple1(index, scalars.GetTuple1(index) + 1)

    volume = vtk.vtkStructuredPoints()
    volume.GetPointData().SetScalars(scalars)
    volume.SetDimensions(resolution, resolution, resolution)
    volume.SetOrigin(xmin, ymin, zmin)
    volume.SetSpacing((xmax - xmin) / resolution, (ymax - ymin) / resolution,
                      (zmax - zmin) / resolution)

    print(' contouring...')
    # Do the graphics dance.
    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Create iso-surface
    contour = vtk.vtkContourFilter()
    contour.SetInputData(volume)
    contour.SetValue(0, 50)

    # Create mapper.
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(contour.GetOutputPort())
    mapper.ScalarVisibilityOff()

    # Create actor.
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('DodgerBlue'))

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d('PaleGoldenrod'))

    renWin.SetSize(640, 480)

    # interact with data
    renWin.Render()
    renWin.SetWindowName('Lorenz')

    camera = renderer.GetActiveCamera()
    camera.SetPosition(-67.645167, -25.714343, 63.483516)
    camera.SetFocalPoint(3.224902, -4.398594, 29.552112)
    camera.SetViewUp(-0.232264, 0.965078, 0.121151)
    camera.SetDistance(81.414176)
    camera.SetClippingRange(18.428905, 160.896031)

    iren.Start()
Ejemplo n.º 32
0
def main():
    colors = vtk.vtkNamedColors()

    Pr = 10.0  # The Lorenz parameters
    b = 2.667
    r = 28.0
    # x = 0.0
    # y = 0.0
    # z = 0.0  # starting (and current) x, y, z
    h = 0.01  # integration step size
    resolution = 200  # slice resolution
    iterations = 10000000  # number of iterations
    xmin = -30.0  # x, y, z range for voxels
    xmax = 30.0
    ymin = -30.0
    ymax = 30.0
    zmin = -10.0
    zmax = 60.0

    # Take a stab at an integration step size.
    xIncr = resolution / (xmax - xmin)
    yIncr = resolution / (ymax - ymin)
    zIncr = resolution / (zmax - zmin)

    print("The Lorenz Attractor\n")
    print(" Pr =", Pr)
    print(" b =", b)
    print(" r =", r)
    print(" integration step size =", h)
    print(" slice resolution =", resolution)
    print(" # of iterations =", iter)
    print(" specified range:")
    print("     x: {:f}, {:f}".format(xmin, xmax))
    print("     y: {:f}, {:f}".format(ymin, ymax))
    print("     z: {:f}, {:f}".format(zmin, zmax))

    x = vtk.vtkMath.Random(xmin, xmax)
    y = vtk.vtkMath.Random(ymin, ymax)
    z = vtk.vtkMath.Random(zmin, zmax)
    print(" starting at {:f}, {:f}, {:f}".format(x, y, z))
    # allocate memory for the slices
    sliceSize = resolution * resolution
    numPts = sliceSize * resolution
    scalars = vtk.vtkShortArray()
    for i in range(0, numPts):
        scalars.InsertTuple1(i, 0)
    for j in range(0, iterations):
        # Integrate to the next time step.
        xx = x + h * Pr * (y - x)
        yy = y + h * (x * (r - z) - y)
        zz = z + h * (x * y - (b * z))

        x = xx
        y = yy
        z = zz

        # Calculate the voxel index.
        if xmax > x > xmin and ymax > y > ymin and zmax > z > zmin:
            xxx = int(float(xx - xmin) * xIncr)
            yyy = int(float(yy - ymin) * yIncr)
            zzz = int(float(zz - zmin) * zIncr)
            index = xxx + yyy * resolution + zzz * sliceSize
            scalars.SetTuple1(index, scalars.GetTuple1(index) + 1)

    volume = vtk.vtkStructuredPoints()
    volume.GetPointData().SetScalars(scalars)
    volume.SetDimensions(resolution, resolution, resolution)
    volume.SetOrigin(xmin, ymin, zmin)
    volume.SetSpacing((xmax - xmin) / resolution, (ymax - ymin) / resolution,
                      (zmax - zmin) / resolution)

    print(" contouring...")
    # Do the graphics dance.
    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # Create iso-surface
    contour = vtk.vtkContourFilter()
    contour.SetInputData(volume)
    contour.SetValue(0, 50)

    # Create mapper.
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(contour.GetOutputPort())
    mapper.ScalarVisibilityOff()

    # Create actor.
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d("PaleTurquoise"))

    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("PeachPuff"))

    renWin.SetSize(640, 480)

    # interact with data
    renWin.Render()

    iren.Start()
Ejemplo n.º 33
0
pArray = map(ord,voxels.tostring()) #unpack
pDims = shape(voxels)
if debug: print pDims

# need a reshuffle of indices ?? -- doesn't matter if cube (same xyz dims)
pDims = [pDims[2],pDims[1],pDims[0]]

scale = mmPerVox
iSizes = [pDims[0]+2, pDims[1]+2, pDims[2]+2]

nTotalValues = iSizes[0] * iSizes[1] * iSizes[2]

pClassValues = vtk.vtkUnsignedCharArray()
pClassValues.SetNumberOfValues(nTotalValues)

pClassData = vtk.vtkStructuredPoints()
pClassData.SetDimensions(iSizes[0], iSizes[1], iSizes[2])
pClassData.SetOrigin(-scale[0], -scale[1], -scale[2]) #???
pClassData.SetOrigin(-1, -1, -1) #???
pClassData.SetSpacing(scale[0], scale[1], scale[2])


for iSrcZ in range(pDims[2]):

    for iSrcY in range(pDims[1]):

        iSrcIndex = iSrcZ * pDims[1] * pDims[0] + iSrcY * pDims[0]
        iDstIndex = (iSrcZ+1) * iSizes[1] * iSizes[0] + (iSrcY+1) * iSizes[0] + 1

        for iSrcX in range(pDims[0]):
Ejemplo n.º 34
0
    def array2vtk(self,
                  array,
                  filename,
                  path,
                  origin=[0, 0, 0],
                  spacing=[1, 1, 1]):
        """
        Convert array into .vtk file
        
        - Params:
            inherited class parameters (see description at beginning of the class)
            array: array to be converted into .vtk file (array)
            filename: filename with which to save array as VTK file (str)
            path: path where to save VTK file (str)
            origin: origin of coordinate system, by default [0,0,0] (list of 3)
            spacing: spacing of coordinate system, by default [1,1,1] (list of 3)
        
        """

        vtk_writer = vtk.vtkStructuredPointsWriter()

        # Check if destination folder exists

        #print('Checking if destination folder exists\n')

        isdir = os.path.isdir(path)

        if not isdir:

            os.makedirs(path)

            print('Non-existing destination path. Created\n')

        # Check if files already exist in destination folder

        exist = filename in os.listdir(path)

        overwrite = 'y'

        if exist:

            overwrite = input(
                "File is already in folder. Do you want to overwrite? [y/n]\n")

        if overwrite == 'y' or overwrite == 'Y':

            vtk_writer.SetFileName(path + filename)

            vtk_im = vtk.vtkStructuredPoints()

            vtk_im.SetDimensions(
                (array.shape[1], array.shape[0], array.shape[2]))

            vtk_im.SetOrigin(origin)

            vtk_im.SetSpacing(spacing)

            pdata = vtk_im.GetPointData()

            vtk_array = numpy_to_vtk(array.swapaxes(0, 1).ravel(order='F'),
                                     deep=1)

            pdata.SetScalars(vtk_array)

            vtk_writer.SetFileType(vtk.VTK_BINARY)

            vtk_writer.SetInputData(vtk_im)

            vtk_writer.Update()

            #print('VTK file saved successfully!\n')

        else:
            print('\nOperation aborted\n')
Ejemplo n.º 35
0
    def init_concentration_field_actors(self,
                                        actor_specs,
                                        drawing_params=None):
        """
        initializes concentration field actors
        :param actor_specs:
        :param drawing_params:
        :return: None
        """

        actors_dict = actor_specs.actors_dict

        field_dim = self.currentDrawingParameters.bsd.fieldDim
        # dim_order = self.dimOrder(self.currentDrawingParameters.plane)
        # dim = self.planeMapper(dim_order, (field_dim.x, field_dim.y, field_dim.z))# [fieldDim.x, fieldDim.y, fieldDim.z]
        dim = [field_dim.x, field_dim.y, field_dim.z]
        field_name = drawing_params.fieldName
        scene_metadata = drawing_params.screenshot_data.metadata
        mdata = MetadataHandler(mdata=scene_metadata)

        try:
            isovalues = mdata.get('ScalarIsoValues', default=[])
            isovalues = list([float(x) for x in isovalues])
        except:
            print('Could not process isovalue list ')
            isovalues = []

        try:
            numIsos = mdata.get('NumberOfContourLines', default=3)
        except:
            print('could not process NumberOfContourLines setting')
            numIsos = 0

        hex_flag = False
        lattice_type_str = self.get_lattice_type_str()
        if lattice_type_str.lower() == 'hexagonal':
            hex_flag = True

        types_invisible = PlayerPython.vectorint()
        for type_label in drawing_params.screenshot_data.invisible_types:
            types_invisible.append(int(type_label))

        # self.isovalStr = Configuration.getSetting("ScalarIsoValues", field_name)
        # if type(self.isovalStr) == QVariant:
        #     self.isovalStr = str(self.isovalStr.toString())
        # else:
        #     self.isovalStr = str(self.isovalStr)

        con_array = vtk.vtkDoubleArray()
        con_array.SetName("concentration")
        con_array_int_addr = extract_address_int_from_vtk_object(
            vtkObj=con_array)

        cell_type_con = vtk.vtkIntArray()
        cell_type_con.SetName("concelltype")
        cell_type_con_int_addr = extract_address_int_from_vtk_object(
            vtkObj=cell_type_con)

        field_type = drawing_params.fieldType.lower()
        if field_type == 'confield':
            fill_successful = self.field_extractor.fillConFieldData3D(
                con_array_int_addr, cell_type_con_int_addr, field_name,
                types_invisible)
        elif field_type == 'scalarfield':
            fill_successful = self.field_extractor.fillScalarFieldData3D(
                con_array_int_addr, cell_type_con_int_addr, field_name,
                types_invisible)
        elif field_type == 'scalarfieldcelllevel':
            fill_successful = self.field_extractor.fillScalarFieldCellLevelData3D(
                con_array_int_addr, cell_type_con_int_addr, field_name,
                types_invisible)

        if not fill_successful:
            return

        range_array = con_array.GetRange()
        min_con = range_array[0]
        max_con = range_array[1]
        field_max = range_array[1]
        #        print MODULENAME, '  initScalarFieldDataActors(): min,maxCon=',self.minCon,self.maxCon

        min_max_dict = self.get_min_max_metadata(scene_metadata=scene_metadata,
                                                 field_name=field_name)
        min_range_fixed = min_max_dict['MinRangeFixed']
        max_range_fixed = min_max_dict['MaxRangeFixed']
        min_range = min_max_dict['MinRange']
        max_range = min_max_dict['MaxRange']

        # Note! should really avoid doing a getSetting with each step to speed up the rendering;
        # only update when changed in Prefs
        if min_range_fixed:
            min_con = min_range

        if max_range_fixed:
            max_con = max_range

        uGrid = vtk.vtkStructuredPoints()
        uGrid.SetDimensions(
            dim[0] + 2, dim[1] + 2, dim[2] + 2
        )  # only add 2 if we're filling in an extra boundary (rf. FieldExtractor.cpp)
        #        uGrid.SetDimensions(self.dim[0],self.dim[1],self.dim[2])
        #        uGrid.GetPointData().SetScalars(self.cellTypeCon)   # cellType scalar field
        uGrid.GetPointData().SetScalars(con_array)
        #        uGrid.GetPointData().AddArray(self.conArray)        # additional scalar field

        voi = vtk.vtkExtractVOI()
        ##        voi.SetInputConnection(uGrid.GetOutputPort())
        #        voi.SetInput(uGrid.GetOutput())

        if VTK_MAJOR_VERSION >= 6:
            voi.SetInputData(uGrid)
        else:
            voi.SetInput(uGrid)

        voi.SetVOI(1, dim[0] - 1, 1, dim[1] - 1, 1, dim[2] -
                   1)  # crop out the artificial boundary layer that we created

        isoContour = vtk.vtkContourFilter()
        # skinExtractorColor = vtk.vtkDiscreteMarchingCubes()
        # skinExtractorColor = vtk.vtkMarchingCubes()
        #        isoContour.SetInput(uGrid)
        isoContour.SetInputConnection(voi.GetOutputPort())

        isoNum = 0
        for isoNum, isoVal in enumerate(isovalues):
            try:
                isoContour.SetValue(isoNum, isoVal)
            except:
                print(
                    MODULENAME,
                    '  initScalarFieldDataActors(): cannot convert to float: ',
                    self.isovalStr[idx])

        if isoNum > 0:
            isoNum += 1

        delIso = (max_con - min_con) / (numIsos + 1
                                        )  # exclude the min,max for isovalues
        isoVal = min_con + delIso
        for idx in range(numIsos):
            isoContour.SetValue(isoNum, isoVal)
            isoNum += 1
            isoVal += delIso

        # UGLY hack to NOT display anything since our attempt to RemoveActor (below) don't seem to work
        if isoNum == 0:
            isoVal = field_max + 1.0  # go just outside valid range
            isoContour.SetValue(isoNum, isoVal)

        #        concLut = vtk.vtkLookupTable()
        # concLut.SetTableRange(conc_vol.GetScalarRange())
        #        concLut.SetTableRange([self.minCon,self.maxCon])
        self.scalarLUT.SetTableRange([min_con, max_con])
        #        concLut.SetNumberOfColors(256)
        #        concLut.Build()
        # concLut.SetTableValue(39,0,0,0,0)

        #        skinColorMapper = vtk.vtkPolyDataMapper()
        # skinColorMapper.SetInputConnection(skinNormals.GetOutputPort())
        #        self.conMapper.SetInputConnection(skinExtractorColor.GetOutputPort())
        self.conMapper.SetInputConnection(isoContour.GetOutputPort())
        self.conMapper.ScalarVisibilityOn()
        self.conMapper.SetLookupTable(self.scalarLUT)
        # # # print " this is conc_vol.GetScalarRange()=",conc_vol.GetScalarRange()
        # self.conMapper.SetScalarRange(conc_vol.GetScalarRange())
        self.conMapper.SetScalarRange([min_con, max_con])
        # self.conMapper.SetScalarRange(0,1500)

        # rwh - what does this do?
        #        self.conMapper.SetScalarModeToUsePointFieldData()
        #        self.conMapper.ColorByArrayComponent("concentration",0)

        #        print MODULENAME,"initScalarFieldDataActors():  Plotting 3D Scalar field"
        # self.conMapper      = vtk.vtkPolyDataMapper()
        # self.conActor       = vtk.vtkActor()

        concentration_actor = actors_dict['concentration_actor']

        concentration_actor.SetMapper(self.conMapper)

        self.init_min_max_actor(
            min_max_actor=actors_dict['min_max_text_actor'],
            range_array=range_array)

        if hex_flag:
            concentration_actor.SetScale(self.xScaleHex, self.yScaleHex,
                                         self.zScaleHex)

        if actor_specs.metadata is None:
            actor_specs.metadata = {'mapper': self.conMapper}
        else:
            actor_specs.metadata['mapper'] = self.conMapper

        if mdata.get('LegendEnable', default=False):
            self.init_legend_actors(actor_specs=actor_specs,
                                    drawing_params=drawing_params)
Ejemplo n.º 36
0
 def isosurface(self, cubeobject, isovalue):
     me = Mesh.New()
     me2 = Mesh.New()
     faces = []
     vertices = []
     scalars = vtk.vtkFloatArray()
     for k in range(cubeobject.nz):
         for j in range(cubeobject.ny):
             for i in range(cubeobject.nx):
                 scalars.InsertNextValue(cubeobject.data3d[k][j][i])
     grid = vtk.vtkStructuredPoints()
     info = vtk.vtkInformation()
     grid.SetOrigin(cubeobject.origin[0], cubeobject.origin[1],
                    cubeobject.origin[2])
     grid.SetDimensions(cubeobject.nx, cubeobject.ny, cubeobject.nz)
     grid.SetSpacing(cubeobject.dx, cubeobject.dy, cubeobject.dz)
     grid.SetNumberOfScalarComponents(
         cubeobject.nx * cubeobject.ny * cubeobject.nz, info)
     grid.GetPointData().SetScalars(scalars)
     Marching = vtk.vtkContourFilter()
     Marching.SetInputData(grid)
     Marching.SetValue(0, isovalue)
     Marching.Update()
     contoursurface = Marching.GetOutput()
     for i in range(contoursurface.GetNumberOfPoints()):
         point = contoursurface.GetPoint(i)
         vertices.append([
             point[0] + self.cursorXYZ[0], point[1] + self.cursorXYZ[1],
             point[2] + self.cursorXYZ[2]
         ])
     me.verts.extend(vertices)
     me.materials = [materials["positivelobe"]]
     for i in range(contoursurface.GetNumberOfCells()):
         cell = contoursurface.GetCell(i)
         n1 = cell.GetPointId(0)
         n2 = cell.GetPointId(1)
         n3 = cell.GetPointId(2)
         faces.append([me.verts[n1], me.verts[n2], me.verts[n3]])
     me.faces.extend(faces)
     for face in me.faces:
         face.smooth = True
     ob = self.scene.objects.new(me, 'Positive Lobe')
     Marching.SetValue(0, -isovalue)
     Marching.Update()
     contoursurface = Marching.GetOutput()
     vertices = []
     for i in range(contoursurface.GetNumberOfPoints()):
         point = contoursurface.GetPoint(i)
         vertices.append([
             point[0] + self.cursorXYZ[0], point[1] + self.cursorXYZ[1],
             point[2] + self.cursorXYZ[2]
         ])
     me2.verts.extend(vertices)
     faces = []
     for i in range(contoursurface.GetNumberOfCells()):
         cell = contoursurface.GetCell(i)
         n1 = cell.GetPointId(0)
         n2 = cell.GetPointId(1)
         n3 = cell.GetPointId(2)
         faces.append([me2.verts[n1], me2.verts[n2], me2.verts[n3]])
     me2.faces.extend(faces)
     me2.materials = [materials["negativelobe"]]
     for face in me2.faces:
         face.smooth = True
     ob = self.scene.objects.new(me2, 'Negative Lobe')
Ejemplo n.º 37
0
def save_vtk_stru_point(path, vtk_dict, verbose=True):
    """
    A routine to save a structured point vtk file given by a dictionary.

    Parameters
    ----------
    path : string
        Path for the file to be saved to.
    vtk_dict : dict
        Dictionary containing information of a structured point vtk file.
        The following keywords are allowed:

        * ``"dimensions"``: (int, int, int)
        * ``"origin"``: (float, float, float)
        * ``"spacing"``: (float, float, float)
        * ``"header"``: string
        * ``"field_data"``: dict of {"name": array}
        * ``"point_data"``: dict of {"name": array}
        * ``"cell_data"``: dict of {"name": array}

    verbose : bool, optional
        Print information of the writing process. Default: True

    Notes
    -----
    All data is assumed to be scalar.
    """
    from numpy import ascontiguousarray as ascont
    from vtk import (
        vtkStructuredPoints,
        vtkStructuredPointsWriter,
        vtkFieldData,
    )
    from vtk.util.numpy_support import numpy_to_vtk as np2vtk

    out = vtkStructuredPoints()
    if verbose:
        print("Set 'dimensions', 'origin', 'spacing'")
    out.SetDimensions(vtk_dict["dimensions"])
    out.SetOrigin(vtk_dict["origin"])
    out.SetSpacing(vtk_dict["spacing"])

    if vtk_dict["field_data"]:
        if verbose:
            print("Set 'field_data'")
        data = vtkFieldData()
        for sgl_data in vtk_dict["field_data"]:
            if verbose:
                print("  Set '" + sgl_data + "'")
            arr = np2vtk(
                ascont(vtk_dict["field_data"][sgl_data].reshape(-1,
                                                                order="F")))
            arr.SetName(sgl_data)
            data.AddArray(arr)
        out.SetFieldData(data)

    if vtk_dict["point_data"]:
        if verbose:
            print("Set 'point_data'")
        data = out.GetPointData()
        for sgl_data in vtk_dict["point_data"]:
            if verbose:
                print("  Set '" + sgl_data + "'")
            arr = np2vtk(
                ascont(vtk_dict["point_data"][sgl_data].reshape(-1,
                                                                order="F")))
            arr.SetName(sgl_data)
            data.AddArray(arr)

    if vtk_dict["cell_data"]:
        if verbose:
            print("Set 'cell_data'")
        data = out.GetCellData()
        for sgl_data in vtk_dict["cell_data"]:
            if verbose:
                print("  Set '" + sgl_data + "'")
            arr = np2vtk(
                ascont(vtk_dict["cell_data"][sgl_data].reshape(-1, order="F")))
            arr.SetName(sgl_data)
            data.AddArray(arr)

    writer = vtkStructuredPointsWriter()
    writer.SetFileName(path)
    writer.SetInputData(out)
    if "header" in vtk_dict:
        writer.SetHeader(vtk_dict["header"])
    writer.Write()
Ejemplo n.º 38
0
p.add_option("-v", action="store_true", dest="verbose", help="Verbose")
p.add_option("-a",
             action="store_true",
             dest="ascii",
             help="ASCII, instead of binary, .vtu output")

(opts, args) = p.parse_args()
# get the com filename
if len(args) != 2:
    p.print_help()
    sys.exit(1)
(in_file, out_file) = args

f = open(in_file + ".dat", 'r')
#output = vtk.vtkPolyData()
output = vtk.vtkStructuredPoints()

nodes = []
nodes_array = vtk.vtkIntArray()
nodes_array.SetName("nodes")
node_x = []
node_y = []
node_z = []
counter = 0
point = vtk.vtkPoints()
field_data = vtk.vtkFieldData()

for line in f:
    if not line.split():
        continue
Ejemplo n.º 39
0
    def init_concentration_field_actors(self, actor_specs, drawing_params=None):
        """
        initializes concentration field actors
        :param actor_specs:
        :param drawing_params:
        :return: None
        """

        actors_dict = actor_specs.actors_dict

        field_dim = self.currentDrawingParameters.bsd.fieldDim
        # dim_order = self.dimOrder(self.currentDrawingParameters.plane)
        # dim = self.planeMapper(dim_order, (field_dim.x, field_dim.y, field_dim.z))# [fieldDim.x, fieldDim.y, fieldDim.z]
        dim = [field_dim.x, field_dim.y, field_dim.z]
        field_name = drawing_params.fieldName
        scene_metadata = drawing_params.screenshot_data.metadata
        mdata = MetadataHandler(mdata=scene_metadata)

        try:
            isovalues = mdata.get('ScalarIsoValues',default=[])
            isovalues = list(map(lambda x: float(x), isovalues))
        except:
            print('Could not process isovalue list ')
            isovalues = []

        try:
            numIsos = mdata.get('NumberOfContourLines',default=3)
        except:
            print('could not process NumberOfContourLines setting')
            numIsos = 0

        hex_flag = False
        lattice_type_str = self.get_lattice_type_str()
        if lattice_type_str.lower() == 'hexagonal':
            hex_flag = True

        import PlayerPython

        types_invisible = PlayerPython.vectorint()
        for type_label in drawing_params.screenshot_data.invisible_types:
            types_invisible.append(int(type_label))

        # self.isovalStr = Configuration.getSetting("ScalarIsoValues", field_name)
        # if type(self.isovalStr) == QVariant:
        #     self.isovalStr = str(self.isovalStr.toString())
        # else:
        #     self.isovalStr = str(self.isovalStr)

        con_array = vtk.vtkDoubleArray()
        con_array.SetName("concentration")
        con_array_int_addr = extract_address_int_from_vtk_object(field_extractor=self.field_extractor, vtkObj=con_array)

        cell_type_con = vtk.vtkIntArray()
        cell_type_con.SetName("concelltype")
        cell_type_con_int_addr = extract_address_int_from_vtk_object(field_extractor=self.field_extractor,
                                                                     vtkObj=cell_type_con)

        field_type = drawing_params.fieldType.lower()
        if field_type == 'confield':
            fill_successful = self.field_extractor.fillConFieldData3D(con_array_int_addr, cell_type_con_int_addr,
                                                                      field_name, types_invisible)
        elif field_type == 'scalarfield':
            fill_successful = self.field_extractor.fillScalarFieldData3D(con_array_int_addr, cell_type_con_int_addr,
                                                                         field_name, types_invisible)
        elif field_type == 'scalarfieldcelllevel':
            fill_successful = self.field_extractor.fillScalarFieldCellLevelData3D(con_array_int_addr,
                                                                                  cell_type_con_int_addr, field_name,
                                                                                  types_invisible)

        if not fill_successful:
            return

        range_array = con_array.GetRange()
        min_con = range_array[0]
        max_con = range_array[1]
        field_max = range_array[1]
        #        print MODULENAME, '  initScalarFieldDataActors(): min,maxCon=',self.minCon,self.maxCon

        min_max_dict = self.get_min_max_metadata(scene_metadata=scene_metadata, field_name=field_name)
        min_range_fixed = min_max_dict['MinRangeFixed']
        max_range_fixed = min_max_dict['MaxRangeFixed']
        min_range = min_max_dict['MinRange']
        max_range = min_max_dict['MaxRange']

        # Note! should really avoid doing a getSetting with each step to speed up the rendering;
        # only update when changed in Prefs
        if min_range_fixed:
            min_con = min_range

        if max_range_fixed:
            max_con = max_range

        uGrid = vtk.vtkStructuredPoints()
        uGrid.SetDimensions(dim[0] + 2, dim[1] + 2, dim[
            2] + 2)  # only add 2 if we're filling in an extra boundary (rf. FieldExtractor.cpp)
        #        uGrid.SetDimensions(self.dim[0],self.dim[1],self.dim[2])
        #        uGrid.GetPointData().SetScalars(self.cellTypeCon)   # cellType scalar field
        uGrid.GetPointData().SetScalars(con_array)
        #        uGrid.GetPointData().AddArray(self.conArray)        # additional scalar field

        voi = vtk.vtkExtractVOI()
        ##        voi.SetInputConnection(uGrid.GetOutputPort())
        #        voi.SetInput(uGrid.GetOutput())

        if VTK_MAJOR_VERSION >= 6:
            voi.SetInputData(uGrid)
        else:
            voi.SetInput(uGrid)

        voi.SetVOI(1, dim[0] - 1, 1, dim[1] - 1, 1,
                   dim[2] - 1)  # crop out the artificial boundary layer that we created

        isoContour = vtk.vtkContourFilter()
        # skinExtractorColor = vtk.vtkDiscreteMarchingCubes()
        # skinExtractorColor = vtk.vtkMarchingCubes()
        #        isoContour.SetInput(uGrid)
        isoContour.SetInputConnection(voi.GetOutputPort())

        isoNum = 0
        for isoNum, isoVal in enumerate(isovalues):
            try:
                isoContour.SetValue(isoNum, isoVal)
            except:
                print MODULENAME, '  initScalarFieldDataActors(): cannot convert to float: ', self.isovalStr[idx]

        if isoNum > 0:
            isoNum += 1

        delIso = (max_con - min_con) / (numIsos + 1)  # exclude the min,max for isovalues
        isoVal = min_con + delIso
        for idx in xrange(numIsos):
            isoContour.SetValue(isoNum, isoVal)
            isoNum += 1
            isoVal += delIso

        # UGLY hack to NOT display anything since our attempt to RemoveActor (below) don't seem to work
        if isoNum == 0:
            isoVal = field_max + 1.0  # go just outside valid range
            isoContour.SetValue(isoNum, isoVal)

        #        concLut = vtk.vtkLookupTable()
        # concLut.SetTableRange(conc_vol.GetScalarRange())
        #        concLut.SetTableRange([self.minCon,self.maxCon])
        self.scalarLUT.SetTableRange([min_con, max_con])
        #        concLut.SetNumberOfColors(256)
        #        concLut.Build()
        # concLut.SetTableValue(39,0,0,0,0)

        #        skinColorMapper = vtk.vtkPolyDataMapper()
        # skinColorMapper.SetInputConnection(skinNormals.GetOutputPort())
        #        self.conMapper.SetInputConnection(skinExtractorColor.GetOutputPort())
        self.conMapper.SetInputConnection(isoContour.GetOutputPort())
        self.conMapper.ScalarVisibilityOn()
        self.conMapper.SetLookupTable(self.scalarLUT)
        # # # print " this is conc_vol.GetScalarRange()=",conc_vol.GetScalarRange()
        # self.conMapper.SetScalarRange(conc_vol.GetScalarRange())
        self.conMapper.SetScalarRange([min_con, max_con])
        # self.conMapper.SetScalarRange(0,1500)

        # rwh - what does this do?
        #        self.conMapper.SetScalarModeToUsePointFieldData()
        #        self.conMapper.ColorByArrayComponent("concentration",0)

        #        print MODULENAME,"initScalarFieldDataActors():  Plotting 3D Scalar field"
        # self.conMapper      = vtk.vtkPolyDataMapper()
        # self.conActor       = vtk.vtkActor()

        concentration_actor = actors_dict['concentration_actor']

        concentration_actor.SetMapper(self.conMapper)

        self.init_min_max_actor(min_max_actor=actors_dict['min_max_text_actor'], range_array=range_array)

        if hex_flag:
            concentration_actor.SetScale(self.xScaleHex, self.yScaleHex, self.zScaleHex)

        if actor_specs.metadata is None:
            actor_specs.metadata = {'mapper': self.conMapper}
        else:
            actor_specs.metadata['mapper'] = self.conMapper

        if mdata.get('LegendEnable',default=False):
            print 'Enabling legend'
            self.init_legend_actors(actor_specs=actor_specs, drawing_params=drawing_params)
Ejemplo n.º 40
0
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Image pipeline
image1 = vtk.vtkTIFFReader()
image1.SetFileName(VTK_DATA_ROOT + "/Data/beach.tif")
# "beach.tif" image contains ORIENTATION tag which is
# ORIENTATION_TOPLEFT (row 0 top, col 0 lhs) type. The TIFF
# reader parses this tag and sets the internal TIFF image
# orientation accordingly.  To overwrite this orientation with a vtk
# convention of ORIENTATION_BOTLEFT (row 0 bottom, col 0 lhs ), invoke
# SetOrientationType method with parameter value of 4.
image1.SetOrientationType(4)
image1.Update()

sp = vtk.vtkStructuredPoints()
sp.SetDimensions(image1.GetOutput().GetDimensions())
sp.SetExtent(image1.GetOutput().GetExtent())
sp.SetScalarType(image1.GetOutput().GetScalarType(),
                 image1.GetOutputInformation(0))
sp.SetNumberOfScalarComponents(
    image1.GetOutput().GetNumberOfScalarComponents(),
    image1.GetOutputInformation(0))
sp.GetPointData().SetScalars(image1.GetOutput().GetPointData().GetScalars())

luminance = vtk.vtkImageLuminance()
luminance.SetInputData(sp)

# Let's create a dictionary to test the writers, the key will be the writer
# and the value the file name used by the writer.
filenames = [