Esempio n. 1
0
def transferTCoords():
	input = paf.GetInputDataObject(0,0)
	refin = paf.GetInputList().GetItem(0)
	output = paf.GetPolyDataOutput()
	# output.CopyStructure(input)
	# output.CopyAttributes(input)
	
	TCorig = refin.GetPointData().GetTCoords()
	Norig = refin.GetPointData().GetNormals()
	
	TC = vtk.vtkFloatArray()
	TC.SetNumberOfComponents(TCorig.GetNumberOfComponents())
	TC.SetNumberOfTuples(TCorig.GetNumberOfTuples())
	TC.SetName('Texture Coordinates')
	for ii in range(TCorig.GetNumberOfTuples()):
		ff = TCorig.GetTuple2(ii)
		TC.SetTuple2(ii,ff[0],ff[1])
	
	NN = vtk.vtkFloatArray()
	NN.SetNumberOfComponents(Norig.GetNumberOfComponents())
	NN.SetNumberOfTuples(Norig.GetNumberOfTuples())
	NN.SetName('normals')
	for ii in range(Norig.GetNumberOfTuples()):
		ff = Norig.GetTuple3(ii)
		NN.SetTuple3(ii,ff[0],ff[1],ff[2])
		
	output.GetPointData().AddArray(TC)
	output.GetPointData().SetActiveTCoords('Texture Coordinates')
	output.GetPointData().AddArray(NN)
	output.GetPointData().SetActiveNormals('normals')
Esempio n. 2
0
 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
Esempio n. 3
0
    def findLocalCsys(self, filename):
        poly = vtk.vtkGeometryFilter()
        poly.SetInputData(self.vtkMeshes[filename])
        poly.Update()

        distanceFilter = vtk.vtkImplicitPolyDataDistance()
        distanceFilter.SetInput(poly.GetOutput())

        gradients = vtk.vtkFloatArray()
        gradients.SetNumberOfComponents(3)
        gradients.SetName("LevelSet Normals")

        distances = vtk.vtkFloatArray()
        distances.SetNumberOfComponents(1)
        distances.SetName("Signed Distances")

        N = self.vtkMeshes[filename].GetCellData().GetArray(
            "Centroids").GetNumberOfTuples()
        for i in range(N):
            g = np.zeros(3, np.float32)
            p = self.vtkMeshes[filename].GetCellData().GetArray(
                "Centroids").GetTuple3(i)
            d = distanceFilter.EvaluateFunction(p)
            distanceFilter.EvaluateGradient(p, g)
            g = old_div(np.array(g), np.linalg.norm(np.array(g)))
            gradients.InsertNextTuple(g)
            distances.InsertNextValue(d)
        self.vtkMeshes[filename].GetCellData().AddArray(gradients)
        self.vtkMeshes[filename].GetCellData().AddArray(distances)
Esempio n. 4
0
    def addPlot(self,_plotName,_style="Lines"):   # called directly from Steppable; add a (possibly more than one) plot to a plot window

        self.plotWindowInterfaceMutex.lock()
#        self.plotWindowMutex.lock()

#        return
#        print MODULENAME,'   addPlot():  _plotName= ',_plotName
#        import pdb; pdb.set_trace()
        
#        self.plotData[_plotName] = [array([],dtype=double),array([],dtype=double),False]  # 'array': from PyQt4.Qwt5.anynumpy import *
        
        self.chart = vtk.vtkChartXY()
#        self.chart.GetAxis(vtk.vtkAxis.LEFT).SetLogScale(True)
#        self.chart.GetAxis(vtk.vtkAxis.BOTTOM).SetLogScale(True)
#        self.numCharts += 1
        self.plotData[_plotName] = [self.chart]

        self.view = vtk.vtkContextView()
        self.ren = self.view.GetRenderer()
#        self.renWin = self.qvtkWidget.GetRenderWindow()
        self.renWin = self.pW.GetRenderWindow()
        self.renWin.AddRenderer(self.ren)

        # Create a table with some points in it
        self.table = vtk.vtkTable()

        self.arrX = vtk.vtkFloatArray()
        self.arrX.SetName("xarray")

        self.arrC = vtk.vtkFloatArray()
        self.arrC.SetName("yarray")

        numPoints = 5
        numPoints = 15
        inc = 7.5 / (numPoints - 1)

#        for i in range(0,numPoints):
#            self.arrX.InsertNextValue(i*inc)
#            self.arrC.InsertNextValue(math.cos(i * inc) + 0.0)

#        self.arrX.InsertNextValue(0.0)
#        self.arrC.InsertNextValue(0.0)
#        self.arrX.InsertNextValue(0.1)
#        self.arrC.InsertNextValue(0.1)

        self.table.AddColumn(self.arrX)
        self.table.AddColumn(self.arrC)

        # Now add the line plots with appropriate colors
        self.line = self.chart.AddPlot(0)
        self.line.SetInput(self.table,0,1)
        self.line.SetColor(0,0,255,255)
        self.line.SetWidth(1.0)


        self.view.GetRenderer().SetBackground([0.6,0.6,0.1])
        self.view.GetRenderer().SetBackground([1.0,1.0,1.0])
        self.view.GetScene().AddItem(self.chart)

        self.plotWindowInterfaceMutex.unlock()
Esempio n. 5
0
    def testLinePlot(self):
        "Test if line plots can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0,1.0,1.0)
        view.GetRenderWindow().SetSize(400,300)
        chart = vtk.vtkChartXY()
        view.GetScene().AddItem(chart)

        # Create a table with some points in it
        table = vtk.vtkTable()

        arrX = vtk.vtkFloatArray()
        arrX.SetName("X Axis")

        arrC = vtk.vtkFloatArray()
        arrC.SetName("Cosine")

        arrS = vtk.vtkFloatArray()
        arrS.SetName("Sine")

        arrS2 = vtk.vtkFloatArray()
        arrS2.SetName("Sine2")

        numPoints = 69
        inc = 7.5 / (numPoints - 1)

        for i in range(0,numPoints):
            arrX.InsertNextValue(i*inc)
            arrC.InsertNextValue(math.cos(i * inc) + 0.0)
            arrS.InsertNextValue(math.sin(i * inc) + 0.0)
            arrS2.InsertNextValue(math.sin(i * inc) + 0.5)

        table.AddColumn(arrX)
        table.AddColumn(arrC)
        table.AddColumn(arrS)
        table.AddColumn(arrS2)

        # Now add the line plots with appropriate colors
        line = chart.AddPlot(0)
        line.SetInput(table,0,1)
        line.SetColor(0,255,0,255)
        line.SetWidth(1.0)

        line = chart.AddPlot(0)
        line.SetInput(table,0,2)
        line.SetColor(255,0,0,255);
        line.SetWidth(5.0)

        line = chart.AddPlot(0)
        line.SetInput(table,0,3)
        line.SetColor(0,0,255,255);
        line.SetWidth(4.0)

        view.GetRenderWindow().SetMultiSamples(0)

        img_file = "TestLinePlot.png"
        vtk.test.Testing.compareImage(view.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25)
        vtk.test.Testing.interact()
Esempio n. 6
0
def ndarray_to_vtkarray(colors, radius, nbat):
    # define the colors
    color_scalars = vtk.vtkFloatArray()
    for c in colors:
            color_scalars.InsertNextValue(c)
    color_scalars.SetName("colors")
    
    # some radii
    radius_scalars = vtk.vtkFloatArray()
    for r in radius:
        radius_scalars.InsertNextValue(r)
    radius_scalars.SetName("radius")
    
    # the original index
    index_scalars = vtk.vtkIntArray()
    for i in range(nbat):
        index_scalars.InsertNextValue(i)
    radius_scalars.SetName("index")
    
    scalars = vtk.vtkFloatArray()
    scalars.SetNumberOfComponents(3)
    scalars.SetNumberOfTuples(radius_scalars.GetNumberOfTuples())
    scalars.CopyComponent(0, radius_scalars ,0 )
    scalars.CopyComponent(1, color_scalars ,0 )
    scalars.CopyComponent(2, index_scalars ,0 )
    scalars.SetName("scalars")
    return scalars 
Esempio n. 7
0
    def testBufferShared(self):
        """Test the special buffer_shared() check that VTK provides."""
        a = bytearray(b'hello')
        self.assertEqual(vtk.buffer_shared(a, a), True)
        b = bytearray(b'hello')
        self.assertEqual(vtk.buffer_shared(a, b), False)

        a = vtk.vtkFloatArray()
        a.SetNumberOfComponents(3)
        a.InsertNextTuple((10, 7, 4))
        a.InsertNextTuple((85, 8, 2))

        b = vtk.vtkFloatArray()
        b.SetVoidArray(a, 6, True)
        self.assertEqual(vtk.buffer_shared(a, b), True)

        c = vtk.vtkFloatArray()
        c.DeepCopy(a)
        self.assertEqual(vtk.buffer_shared(a, c), False)

        if sys.hexversion >= 0x02070000:
            m = memoryview(a)
            self.assertEqual(vtk.buffer_shared(a, m), True)

        if sys.hexversion < 0x03000000:
            m = buffer(a)
            self.assertEqual(vtk.buffer_shared(a, m), True)
Esempio n. 8
0
def BlenderToPolyData(me, uvlayer=None):

	pcoords = vtk.vtkFloatArray()
	pcoords.SetNumberOfComponents(3)
	pcoords.SetNumberOfTuples(len(me.verts))
	for i in range(len(me.verts)):
		p0 = me.verts[i].co[0]
		p1 = me.verts[i].co[1]
		p2 = me.verts[i].co[2]
		pcoords.SetTuple3(i, p0, p1, p2)

	points = vtk.vtkPoints()
	points.SetData(pcoords)

	polys = vtk.vtkCellArray()
	lines = vtk.vtkCellArray()
	for face in me.faces:
		if len(face.v) == 4:
			polys.InsertNextCell(4)
			polys.InsertCellPoint(face.v[0].index)
			polys.InsertCellPoint(face.v[1].index)
			polys.InsertCellPoint(face.v[2].index)
			polys.InsertCellPoint(face.v[3].index)
		elif len(face.v) == 3:
			polys.InsertNextCell(3)
			polys.InsertCellPoint(face.v[0].index)
			polys.InsertCellPoint(face.v[1].index)
			polys.InsertCellPoint(face.v[2].index)
		elif len(face.v) == 2:
			lines.InsertNextCell(2)
			lines.InsertCellPoint(face.v[0].index)
			lines.InsertCellPoint(face.v[1].index)

	for edge in me.edges:
		lines.InsertNextCell(2)
		lines.InsertCellPoint(edge.v1.index)
		lines.InsertCellPoint(edge.v2.index)

	pdata =vtk.vtkPolyData()
	pdata.SetPoints(points)
	pdata.SetPolys(polys)
	pdata.SetLines(lines)

	if me.faceUV:
		if uvlayer:
			uvnames = me.getUVLayerNames()
			if uvlayer in uvnames:
				me.activeUVLayer = uvlayer
		tcoords = vtk.vtkFloatArray()
		tcoords.SetNumberOfComponents(2)
		tcoords.SetNumberOfTuples(len(me.verts))
		for face in me.faces:
			for i in range(len(face.verts)):
				uv = face.uv[i]
				tcoords.SetTuple2(face.v[i].index, uv[0], uv[1])
		pdata.GetPointData().SetTCoords(tcoords);

	pdata.Update()

	return pdata
def ndarray_to_vtkarray(colors, radius, nbat):
    # define the colours
    color_scalars = vtk.vtkFloatArray()
    color_scalars.SetNumberOfValues(colors.shape[0])
    for i,c in enumerate(colors):
            color_scalars.SetValue(i,c)
    color_scalars.SetName("colors")
    
    # some radii
    radius_scalars = vtk.vtkFloatArray()
    radius_scalars.SetNumberOfValues(radius.shape[0])
    for i,r in enumerate(radius):
        radius_scalars.SetValue(i,r)
    radius_scalars.SetName("radius")
    
    # the original index
    index_scalars = vtk.vtkIntArray()
    index_scalars.SetNumberOfValues(nbat)
    for i in range(nbat):
        index_scalars.SetValue(i,i)
    index_scalars.SetName("index")
    
    scalars = vtk.vtkFloatArray()
    scalars.SetNumberOfComponents(3)
    scalars.SetNumberOfTuples(radius_scalars.GetNumberOfTuples())
    scalars.CopyComponent(0, radius_scalars ,0 )
    scalars.CopyComponent(1, color_scalars ,0 )
    scalars.CopyComponent(2, index_scalars ,0 )
    scalars.SetName("scalars")
    return scalars 
Esempio n. 10
0
  def section_CreateTable(self):
    self.delayDisplay("Create table",self.delayMs)

    tableNode = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLTableNode", self.tableName)
    self.assertIsNotNone(tableNode)
    table = tableNode.GetTable()
    self.assertIsNotNone(table)

    # Create X, Y1, and Y2 series

    arrX = vtk.vtkFloatArray()
    arrX.SetName(self.xColumnName)
    table.AddColumn(arrX)

    arrY1 = vtk.vtkFloatArray()
    arrY1.SetName(self.y1ColumnName)
    table.AddColumn(arrY1)

    arrY2 = vtk.vtkFloatArray()
    arrY2.SetName(self.y2ColumnName)
    table.AddColumn(arrY2)

    # Fill in the table with some example values
    import math
    numPoints = 69
    inc = 7.5 / (numPoints - 1)
    table.SetNumberOfRows(numPoints)
    for i in range(numPoints):
      table.SetValue(i, 0, i * inc )
      table.SetValue(i, 1, math.cos(i * inc))
      table.SetValue(i, 2, math.sin(i * inc))
Esempio n. 11
0
    def generateMesh(self, x, y, z, in_x, in_y, in_z):
        x_coord = vtk.vtkFloatArray()
        x_coord.InsertNextValue(x)

        y_coord = vtk.vtkFloatArray()
        y_coord.InsertNextValue(y)

        z_coord = vtk.vtkFloatArray()
        z_coord.InsertNextValue(z)

        grid = vtk.vtkRectilinearGrid()
        grid.SetDimensions(self.nx if in_x else 1, self.ny if in_y else 1, self.nz if in_z else 1)
        grid.SetXCoordinates(self.x_coords if in_x else x_coord);
        grid.SetYCoordinates(self.y_coords if in_y else y_coord);
        grid.SetZCoordinates(self.z_coords if in_z else z_coord);

        # We're going to generate all of the IDs of the cells in that rectilinear grid so we can extract them as an UnstructuredGrid
        # Why would we do such a thing?  Because there is some bug associated with RecitilinearGrids and clipping / rendering
        # So, instead I'm going to use RectilinearGrid for generating the cells and then "copy" it to an UnstructuredGrid using ExtractCells
        num_cells = grid.GetNumberOfCells()
        id_list = vtk.vtkIdList()
        for i in xrange(num_cells):
            id_list.InsertNextId(i)

        extract = vtk.vtkExtractCells()
        if vtk.VTK_MAJOR_VERSION <= 5:
            extract.SetInput(grid)
        else:
            extract.SetInputData(grid)
        extract.SetCellList(id_list)

        return extract.GetOutput()
Esempio n. 12
0
    def removeOldGeometry(self, fileName):
        if fileName is None:
            self.grid = vtk.vtkUnstructuredGrid()
            self.gridResult = vtk.vtkFloatArray()
            #self.emptyResult = vtk.vtkFloatArray()
            #self.vectorResult = vtk.vtkFloatArray()
            self.grid2 = vtk.vtkUnstructuredGrid()
            self.scalarBar.VisibilityOff()
            skipReading = True
        else:
            self.TurnTextOff()
            self.grid.Reset()
            self.grid2.Reset()
            self.gridResult = vtk.vtkFloatArray()
            self.gridResult.Reset()
            self.gridResult.Modified()
            self.eidMap = {}
            self.nidMap = {}

            self.resultCases = {}
            self.nCases = 0
            try:
                del self.caseKeys
                del self.iCase
                del self.iSubcaseNameMap
            except:
                print "cant delete geo"
                pass
            ###
            #print dir(self)
            skipReading = False
        self.scalarBar.VisibilityOff()
        self.scalarBar.Modified()
        return skipReading
def compute_scalar_measures(pd):
    tensors = pd.GetPointData().GetTensors()
    lines = pd.GetLines()

    fa = vtk.vtkFloatArray()
    lambda_parallel = vtk.vtkFloatArray()
    lambda_perp = vtk.vtkFloatArray()
    #fa_array = list()
    
    for tidx in range(tensors.GetNumberOfTuples()):
        if (tidx % 5000) == 0:
            print tidx, '/', tensors.GetNumberOfTuples()
        D = tensors.GetTuple9(tidx)
        D = numpy.array(D).reshape(3,3)
        w, v = numpy.linalg.eig(D)
        fa_tidx = fractional_anisotropy(w)
        lambda_parallel_tidx = w[2]
        lambda_perp_tidx = (w[0] + w[1])/2.0
        fa.InsertNextTuple1(fa_tidx)
        lambda_parallel.InsertNextTuple1(lambda_parallel_tidx)
        lambda_perp.InsertNextTuple1(lambda_perp_tidx)

    fa_avg = vtk.vtkFloatArray()
    fa_lines_list = list()
    fa_avg_list = list()
    lines.InitTraversal()
    for lidx in range(0, pd.GetNumberOfLines()):
        if (lidx % 100) == 0:
            print lidx, '/', pd.GetNumberOfLines()
        pts = vtk.vtkIdList()       
        #lines.GetCell(lidx, pts)
        lines.GetNextCell(pts)
        # compute average FA for this line
        if pts.GetNumberOfIds():
            fa_list = list()
            for pidx in range(0, pts.GetNumberOfIds()):
                fa_list.append(fa.GetTuple1(pts.GetId(pidx)))
            #fa_avg.InsertNextTuple1(numpy.mean(numpy.array(fa_list)))
            fa_avg.InsertNextTuple1(numpy.median(numpy.array(fa_list)))
            fa_lines_list.append(fa_list)
            fa_avg_list.append(numpy.median(numpy.array(fa_list)))
        else:
            fa_avg.InsertNextTuple1(0.0)
            fa_lines_list.append([0.0])
            
    fa_avg.SetName('mean_FA')
    fa.SetName('FA')
    lambda_parallel.SetName('parallel_diffusivity')
    lambda_perp.SetName('perpendicular_diffusivity')

    outpd = pd
    outpd.GetCellData().AddArray(fa_avg)
    outpd.GetCellData().SetActiveScalars('mean_FA')
    outpd.GetPointData().AddArray(fa)
    outpd.GetPointData().AddArray(lambda_parallel)
    outpd.GetPointData().AddArray(lambda_perp)
    outpd.GetPointData().SetActiveScalars('FA')

    return outpd, fa_lines_list, fa_avg_list
Esempio n. 14
0
def writeVTR(vtr_name, scalar_fields, vector_fields, vtkX, vtkY, vtkZ, localZrange):
    """Writes a single VTR file per Python processor/variable

    Parameters:
     vtr_name - name of the VTR file
     scalar_fields - dictionary with scalar field arrays ordered [x, y, z], e.g. {'p': array[nx,ny,nz], 'rho0': array[nx,ny,nz]}
     vector_fields - dictionary with vector fields ordered [3, x, y, z], e.g. {'J': array[3,nx,ny,nz], 'B': array[3,nx,ny,nz]}
     vtkX, vtkY, vtkZ - VTR coordinates, see createVtrCoordinates()
     localZrange - local range for Z indices

    """

    Nx = vtkX.GetNumberOfTuples() - 1
    Ny = vtkY.GetNumberOfTuples() - 1
    Nz=0 #2D
    numpoints = (Nx+1)*(Ny+1)*(Nz+1)
    rtg = vtk.vtkRectilinearGrid()
    rtg.SetExtent(0, Nx, 0, Ny, localZrange[0], localZrange[1]) 
    rtg.SetXCoordinates(vtkX)
    rtg.SetYCoordinates(vtkY)
    vtk_data = []
    array_list = []
    for f in scalar_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints)
        vtk_data[-1].SetNumberOfComponents(1)
        array_list.append(scalar_fields[f].swapaxes(0,2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints, 1)
        vtk_data[-1].SetName(f)
        if f == scalar_fields.keys()[0]:
            rtg.GetPointData().SetScalars(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    for f in vector_fields:
        vtk_data.append(vtk.vtkFloatArray())
        vtk_data[-1].SetNumberOfTuples(numpoints*3)
        vtk_data[-1].SetNumberOfComponents(3)
        array_list.append(vector_fields[f].swapaxes(0,3).swapaxes(1,2).flatten().astype("float32"))
        vtk_data[-1].SetVoidArray(array_list[-1], numpoints*3, 1)
        vtk_data[-1].SetName(f)
        if f == vector_fields.keys()[0]:
            rtg.GetPointData().SetVectors(vtk_data[-1])
        else:
            rtg.GetPointData().AddArray(vtk_data[-1])
    #end for
    try:
        writer = vtk.vtkXMLRectilinearGridWriter()                                                                                              
        writer.SetFileName(vtr_name)
        writer.SetInput(rtg)
        writer.Write()
    except:
        print 'Error writing VTR file: ', vtr_name
Esempio n. 15
0
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
Esempio n. 16
0
def _format_output_polydata(output_polydata, cluster_idx, color, embed):
    """ Output polydata with embedding colors, cluster numbers, and
    embedding coordinates.

    Cell data array names are:
    EmbeddingColor
    ClusterNumber
    EmbeddingCoordinate

    """

    embed_colors = vtk.vtkUnsignedCharArray()
    embed_colors.SetNumberOfComponents(3)
    embed_colors.SetName('EmbeddingColor')
    cluster_colors = vtk.vtkIntArray()
    cluster_colors.SetName('ClusterNumber')
    embed_data = vtk.vtkFloatArray()
    embed_data.SetNumberOfComponents(embed.shape[1])
    embed_data.SetName('EmbeddingCoordinate')

    for lidx in range(0, output_polydata.GetNumberOfLines()):
        embed_colors.InsertNextTuple3(
            color[lidx, 0], color[lidx, 1], color[lidx, 2])
        cluster_colors.InsertNextTuple1(int(cluster_idx[lidx]))
        embed_data.InsertNextTupleValue(embed[lidx, :])

    output_polydata.GetCellData().AddArray(embed_data)
    output_polydata.GetCellData().AddArray(cluster_colors)
    output_polydata.GetCellData().AddArray(embed_colors)

    output_polydata.GetCellData().SetActiveScalars('EmbeddingColor')

    return output_polydata
Esempio n. 17
0
    def draw(self, renderer):
        ### FIXME this should be made faster (C++ Module? How to deal with C++ linkage problems?)
        ### Sticking the vtkPoints objects in a cache would help somewhat but not on the first view.
        ### - Jack
        if not self.drawn:
            vtk_points = vtkPoints()
            points = self.visualiser.getQuantityPoints(self.quantityName, dynamic=self.dynamic)
            nPoints = len(points)
            vtk_points.SetNumberOfPoints(nPoints)
            setPoint = vtkPoints.SetPoint
            for i in xrange(nPoints):
                z = points[i] * self.zScale + self.offset
                setPoint(vtk_points, i, self.visualiser.xPoints[i], self.visualiser.yPoints[i], z)

            polyData = vtkPolyData()
            polyData.SetPoints(vtk_points)
            polyData.SetPolys(self.visualiser.vtk_cells)
            mapper = vtkPolyDataMapper()
            mapper.SetInput(polyData)
            setValue = vtkFloatArray.SetValue
            if hasattr(self.colour[0], '__call__'):
                scalars = self.colour[0](self.visualiser.getQuantityDict())
                nScalars = len(scalars)
                vtk_scalars = vtkFloatArray()
                vtk_scalars.SetNumberOfValues(nScalars)
                for i in xrange(nScalars):
                    setValue(vtk_scalars, i, scalars[i])
                polyData.GetPointData().SetScalars(vtk_scalars)
                mapper.SetScalarRange(self.colour[1:3])
            mapper.Update()
            self.actor.SetMapper(mapper)
        Feature.draw(self, renderer)
Esempio n. 18
0
    def _update_vtk_objects(self):
        """When n is changed the thus the number of coordinates this function is needed
        to update the vtk objects with the new number of points."""
        # self._vtk_points.SetNumberOfPoints(len(self._points))
        # for i, c in enumerate(self._points):
        #     self._vtk_points.InsertPoint(i, c[0], c[1], c[2])
        self._vtk_points = _vtk.vtkPoints()
        for coordinates in self._points:
            self._vtk_points.InsertNextPoint(coordinates[0], coordinates[1], coordinates[2])

        self._vtk_polygons = _vtk.vtkCellArray()
        for polygon in self._polygons:
            vtk_polygon = _vtk.vtkPolygon()
            vtk_polygon.GetPointIds().SetNumberOfIds(3)
            for local_index, global_index in enumerate(polygon):
                vtk_polygon.GetPointIds().SetId(local_index, global_index)
            self._vtk_polygons.InsertNextCell(vtk_polygon)

        self._vtk_poly_data.SetPoints(self._vtk_points)
        self._vtk_poly_data.SetPolys(self._vtk_polygons)

        self._vtk_scalars = _vtk.vtkFloatArray()
        self._vtk_scalars.SetNumberOfValues(self._vtk_poly_data.GetPoints().GetNumberOfPoints())
        for i in range(self._vtk_scalars.GetNumberOfTuples()):
            self._vtk_scalars.SetValue(i, 0.)

        self._vtk_poly_data.GetPointData().SetScalars(self._vtk_scalars)
        self._vtk_poly_data.Modified()
def compute_max_array_along_lines(pd, array_name, output_array_name):
    lines = pd.GetLines()
    point_array = pd.GetPointData().GetArray(array_name)
    
    point_array_max = vtk.vtkFloatArray()
    point_array_lines_list = list()
    point_array_max_list = list()
    lines.InitTraversal()
    for lidx in range(0, pd.GetNumberOfLines()):
        if (lidx % 100) == 0:
            print lidx, '/', pd.GetNumberOfLines()
        pts = vtk.vtkIdList()       
        lines.GetNextCell(pts)
        # compute mean POINT_ARRAY for this line
        if pts.GetNumberOfIds():
            point_array_list = list()
            for pidx in range(0, pts.GetNumberOfIds()):
                point_array_list.append(point_array.GetTuple1(pts.GetId(pidx)))
            point_array_max.InsertNextTuple1(numpy.max(numpy.array(point_array_list)))
            #fa_max.InsertNextTuple1(numpy.median(numpy.array(fa_list)))
        else:
            point_array_max.InsertNextTuple1(0.0)
            
    point_array_max.SetName(output_array_name)

    outpd = pd
    outpd.GetCellData().AddArray(point_array_max)
    outpd.GetCellData().SetActiveScalars(output_array_name)

    return outpd
Esempio n. 20
0
def array2vtk(z):    
    """Converts a numpy Array to a VTK array object directly. The
    resulting array copies the data in the passed  array.  The
    array can therefore be deleted safely.  This works for real arrays.
    """ 
    arr_vtk = {'c':vtkConstants.VTK_UNSIGNED_CHAR,
               'b':vtkConstants.VTK_UNSIGNED_CHAR,
               '1':vtkConstants.VTK_CHAR,
               's':vtkConstants.VTK_SHORT,
               'i':vtkConstants.VTK_INT,
               'l':vtkConstants.VTK_LONG,
               'f':vtkConstants.VTK_FLOAT,
               'd':vtkConstants.VTK_DOUBLE,
               'F':vtkConstants.VTK_FLOAT,
               'D':vtkConstants.VTK_DOUBLE }

    # A dummy array used to create others.
    f = vtk.vtkFloatArray()
    # First create an array of the right type by using the typecode.
    tmp = f.CreateDataArray(arr_vtk[z.dtype.char])
    tmp.SetReferenceCount(2) # Prevents memory leak.
    zf = N.ravel(z)
    tmp.SetNumberOfTuples(len(zf))
    tmp.SetNumberOfComponents(1)
    tmp.SetVoidArray(zf, len(zf), 1)
    # Now create a new array that is a DeepCopy of tmp.  This is
    # required because tmp does not copy the data from the NumPy array
    # and will point to garbage if the NumPy array is deleted.
    arr = f.CreateDataArray(arr_vtk[z.dtype.char])
    arr.SetReferenceCount(2) # Prevents memory leak.
    arr.DeepCopy(tmp)
    return arr
Esempio n. 21
0
def make_spreadsheet(column_names, table):
    # column_names is a list of strings
    # table is a 2D numpy.ndarray
    # returns a vtkTable object that stores the table content

    # Create a vtkTable to store the output.
    rows = table.shape[0]

    if (table.shape[1] != len(column_names)):
        print('Warning: table number of columns differs from number of '
              'column names')
        return

    from vtk import vtkTable, vtkFloatArray
    vtk_table = vtkTable()
    for (column, name) in enumerate(column_names):
        array = vtkFloatArray()
        array.SetName(name)
        array.SetNumberOfComponents(1)
        array.SetNumberOfTuples(rows)
        vtk_table.AddColumn(array)

        for row in range(0, rows):
            array.InsertValue(row, table[row, column])

    return vtk_table
Esempio n. 22
0
    def add_runs(self, eclipse, search_terms):
        """Uses self.prt to search PRT file using list of search terms then creates
        vtkFloatArrays for the scalar values"""

        self.prt.set_dims(eclipse.dims())

        # actual PRT file parsing
        self.prt.add_runs(search_terms)

        x_dim, y_dim, z_dim = eclipse.dims()

        # self.prt.runs is dictionary referencing lists of PRTEntry objects
        for term, runs in self.prt.runs.iteritems():
            # run is PRTEntry object
            for run in tqdm(runs, "creating "+term+"'s vtk arrays"):

                # writing individual time steps requires seperate VTK grids
                tmp = vtkImageData()
                self._set_grid_spec(tmp, eclipse)

                array = vtkFloatArray()
                array.SetName(run.name)
                array.SetNumberOfComponents(1)

                # starts at bottom and moves down x rows, building up
                for z in range(z_dim - 1, -1, -1):
                    for y in range(0, y_dim):
                        for x in range(0, x_dim):
                            scalar = run.cells[z][y][x]
                            array.InsertNextTuple1(scalar)
                tmp.GetCellData().AddArray(array)
                self.grid[term] += [tmp]
Esempio n. 23
0
def generateSpline(markers):
    aSplineX = vtk.vtkCardinalSpline()
    aSplineY = vtk.vtkCardinalSpline()
    aSplineZ = vtk.vtkCardinalSpline()
    
    for i, marker in enumerate(markers):
        center = Vec3f(marker.GetCenter()) if not isinstance(marker, Vec3f) else marker
        aSplineX.AddPoint(i, center.x)
        aSplineY.AddPoint(i, center.y)
        aSplineZ.AddPoint(i, center.z)
    
    # Generate the polyline for the spline.
    points = vtk.vtkPoints()
    scalars = vtk.vtkFloatArray()
    
    # Number of points on the spline
    splineRes = len(markers)*1
    
    # Interpolate x, y and z by using the three spline filters and
    # create new points
    splineList = []
    for i in range(splineRes):
        t = (len(markers)-1.0)/(splineRes-1.0)*i
        splineList.append((aSplineX.Evaluate(t), aSplineY.Evaluate(t),
                           aSplineZ.Evaluate(t)))
        points.InsertPoint(i, splineList[-1][0], splineList[-1][1],
                           splineList[-1][2])
        scalars.InsertTuple1(i,t)
        
    return points, scalars, t, splineList
        
    
Esempio n. 24
0
 def pca(self):
   """Performs Principle Component Analysis on the alignedGrids. Also calculates the mean shape.
   """
   
   logging.info("running pca")
   
   size = len(self.alignedGrids)
   
   self.filterPCA.SetNumberOfInputs(size)
   
   for id, grid in enumerate(self.alignedGrids):    
     self.filterPCA.SetInput(id, grid)
   
   self.filterPCA.Update()
      
   #Get the eigenvalues
   evals = self.filterPCA.GetEvals()
   
   #Now let's get mean ^^
   b = vtk.vtkFloatArray()
   b.SetNumberOfComponents(0)
   b.SetNumberOfTuples(0)
   mean = vtk.vtkUnstructuredGrid()
   mean.DeepCopy(self.alignedGrids[0])
   #Get the mean shape:
   self.filterPCA.GetParameterisedShape(b, mean)
   self.meanShape.append(mean)   
   
   #get the meanpositions
   for pos in range(self.meanShape[0].GetNumberOfCells()):
     bounds = self.meanShape[0].GetCell(pos).GetBounds()
     self.meanPositions.append((bounds[0],bounds[2]))
     
   logging.info("done")
Esempio n. 25
0
    def __init__(self, filename, max_num_of_vertices=-1, edge_color_filename=None):
        super(VTKVisualizer, self).__init__()
        self.vertex_id_idx_map = {}
        self.next_vertex_id = 0
        self.edge_counter = 0
        self.lookup_table = vtk.vtkLookupTable()
        self.lookup_table.SetNumberOfColors(int(1e8))
        self.edge_color_tuples = {}
        self.edge_color_filename = edge_color_filename
        self.label_vertex_id_map = {}
        self.starting_vertex = None
        self.starting_vertex_index = -1
        self.filename = filename
        self.max_num_of_vertices = max_num_of_vertices
        self.g = vtk.vtkMutableDirectedGraph()

        self.vertex_ids = vtk.vtkIntArray()
        self.vertex_ids.SetNumberOfComponents(1)
        self.vertex_ids.SetName(VERTEX_ID)

        self.labels = vtk.vtkStringArray()
        self.labels.SetNumberOfComponents(1)
        self.labels.SetName(LABELS)

        self.glyph_scales = vtk.vtkFloatArray()
        self.glyph_scales.SetNumberOfComponents(1)
        self.glyph_scales.SetName(SCALES)

        self.edge_weights = vtk.vtkDoubleArray()
        self.edge_weights.SetNumberOfComponents(1)
        self.edge_weights.SetName(WEIGHTS)

        self.edge_colors = vtk.vtkIntArray()
        self.edge_colors.SetNumberOfComponents(1)
        self.edge_colors.SetName(EDGE_COLORS)
Esempio n. 26
0
def damage():
    input = test.GetPolyDataInput()
    numPts = input.GetNumberOfPoints()
    newPts = vtk.vtkPoints()
    isolines = vtk.vtkFloatArray()

    for i in range(0, numPts):
        x = input.GetPoint(i)
        x0, x1 = x[:2]

        r = sqrt(x0**2+x1**2)
        if r < 1:
            x2 = 1
        else:
            x2 = (1/sqrt(r))*(abs(cos(x1/r)))**2 + (1/r**3)*abs((sin(x1/r)))**2
        
        if r < 1:
            isoline = 1
        else:
            isoline = (1/sqrt(r))*(abs(cos(x1/r)))**2 + (1/r**2)*abs((sin(x1/r)))**2

        newPts.InsertPoint(i, x0, x1, x2)
        isolines.InsertValue(i, isoline) 

    test.GetPolyDataOutput().CopyStructure(input)
    test.GetPolyDataOutput().SetPoints(newPts)
    test.GetPolyDataOutput().GetPointData().SetScalars(isolines)
Esempio n. 27
0
    def __init__(self, side, curvature):
        self._side = side
        self._curvature = curvature
        x_array_single = _numpy.arange(self._side) - self._side/2. + 0.5
        y_array_single = _numpy.arange(self._side) - self._side/2. + 0.5
        y_array, x_array = _numpy.meshgrid(y_array_single, x_array_single)
        z_array = (self._curvature - _numpy.sqrt(self._curvature**2 -
                                                x_array**2 - y_array**2))

        self._image_values = _vtk.vtkFloatArray()
        self._image_values.SetNumberOfComponents(1)
        self._image_values.SetName("Intensity")

        self._points = _vtk.vtkPoints()
        for i in range(self._side):
            for j in range(self._side):
                self._points.InsertNextPoint(x_array[i, j],
                                             y_array[i, j],
                                             z_array[i, j])
                self._image_values.InsertNextTuple1(0.)

        self._polygons = _vtk.vtkCellArray()

        self._square_slice()
        self._template_poly_data = _vtk.vtkPolyData()
        self._template_poly_data.SetPoints(self._points)
        self._template_poly_data.GetPointData().SetScalars(self._image_values)
        self._template_poly_data.SetPolys(self._polygons)
def addPlot(chart, reader, name):
        data1 = reader.GetOutput()
        
        coords = vtk.vtkFloatArray()
        coords.SetName("Coords")

        for i in range(data1.GetNumberOfPoints()):
                x,y,z = data1.GetPoint(i)
		coords.InsertNextValue(y)

	table = vtk.vtkTable()
	table.AddColumn(coords)
	table.AddColumn(data1.GetPointData().GetArray("S_g"))
        table.AddColumn(data1.GetPointData().GetArray("S_n"))
        table.AddColumn(data1.GetPointData().GetArray("S_w"))

        line1 = chart.AddPlot(vtk.vtkChart.LINE)
        line1.SetInput(table, 0, 1)
	line1.SetMarkerStyle(vtk.vtkPlotPoints.CROSS)

        line2 = chart.AddPlot(vtk.vtkChart.LINE)
        line2.SetInput(table, 0, 2)
	line2.SetMarkerStyle(vtk.vtkPlotPoints.PLUS)

        line3 = chart.AddPlot(vtk.vtkChart.LINE)
        line3.SetInput(table, 0, 3)
        line3.SetMarkerStyle(vtk.vtkPlotPoints.CIRCLE)
Esempio n. 29
0
    def Execute(self, *args):
        polydata = self.GetPolyDataInput()
        nTris = polydata.GetNumberOfCells()
        
        totalPerim = 0.
        for i in xrange(nTris):
            tri = polydata.GetCell(i)
            perim = 0.
            for j in range(3):
                perim += sqrt(tri.GetEdge(j).GetLength2())
                continue
            totalPerim += perim
            continue
        
        aveSide = totalPerim / (3*nTris)

        p = vtkPoints()
        p.InsertPoint(0, 0.,0.,0.)
        
        val = vtkFloatArray()
        val.InsertValue(0, aveSide)
        
        out = vtkPolyData()
        out.SetPoints(p)
        out.GetPointData().SetScalars(val)
        
        self.GetPolyDataOutput().ShallowCopy(out)
        return
Esempio n. 30
0
def main():
    colors = vtk.vtkNamedColors()

    g = vtk.vtkMutableUndirectedGraph()

    v1 = g.AddVertex()
    v2 = g.AddVertex()

    g.AddEdge(v1, v2)
    g.AddEdge(v1, v2)

    scales = vtk.vtkFloatArray()
    scales.SetNumberOfComponents(1)
    scales.SetName('Scales')
    scales.InsertNextValue(2.0)
    scales.InsertNextValue(5.0)

    # Add the scale array to the graph
    g.GetVertexData().AddArray(scales)

    # Create the color array
    vertexColors = vtk.vtkIntArray()
    vertexColors.SetNumberOfComponents(1)
    vertexColors.SetName('Color')

    lookupTable = vtk.vtkLookupTable()
    lookupTable.SetNumberOfTableValues(2)
    lookupTable.SetTableValue(0, colors.GetColor4d('Yellow'))
    lookupTable.SetTableValue(1, colors.GetColor4d('Lime'))
    lookupTable.Build()

    vertexColors.InsertNextValue(0)
    vertexColors.InsertNextValue(1)

    # Add the color array to the graph
    g.GetVertexData().AddArray(vertexColors)

    theme = vtk.vtkViewTheme()
    theme.SetPointLookupTable(lookupTable)

    force_directed = vtk.vtkForceDirectedLayoutStrategy()

    layout_view = vtk.vtkGraphLayoutView()
    # If we create a layout object directly, just set the pointer through this method.
    # graph_layout_view.SetLayoutStrategy(force_directed)
    layout_view.SetLayoutStrategyToForceDirected()
    layout_view.AddRepresentationFromInput(g)
    layout_view.ApplyViewTheme(theme)
    layout_view.ScaledGlyphsOn()
    layout_view.SetScalingArrayName('Scales')
    layout_view.SetVertexColorArrayName('Color')
    layout_view.ColorVerticesOn()
    rGraph = vtk.vtkRenderedGraphRepresentation()
    gGlyph = vtk.vtkGraphToGlyphs()
    rGraph.SafeDownCast(layout_view.GetRepresentation()).SetGlyphType(
        gGlyph.CIRCLE)
    layout_view.GetRenderer().SetBackground(colors.GetColor3d('Navy'))
    layout_view.GetRenderer().SetBackground2(colors.GetColor3d('MidnightBlue'))
    layout_view.GetRenderWindow().SetWindowName('ScaleVertices')
    layout_view.Render()
    layout_view.ResetCamera()
    layout_view.GetInteractor().Start()
Esempio n. 31
0
    def testGlyphs(self):
        """Test if texturing of the glyphs works correctly."""
        # The Glyph
        cs = vtk.vtkCubeSource()
        cs.SetXLength(2.0)
        cs.SetYLength(1.0)
        cs.SetZLength(0.5)

        # Create input point data.
        pts = vtk.vtkPoints()
        pts.InsertPoint(0, (1, 1, 1))
        pts.InsertPoint(1, (0, 0, 0))
        pts.InsertPoint(2, (-1, -1, -1))
        polys = vtk.vtkCellArray()
        polys.InsertNextCell(1)
        polys.InsertCellPoint(0)
        polys.InsertNextCell(1)
        polys.InsertCellPoint(1)
        polys.InsertNextCell(1)
        polys.InsertCellPoint(2)
        pd = vtk.vtkPolyData()
        pd.SetPoints(pts)
        pd.SetPolys(polys)

        # Orient the glyphs as per vectors.
        vec = vtk.vtkFloatArray()
        vec.SetNumberOfComponents(3)
        vec.InsertTuple3(0, 1, 0, 0)
        vec.InsertTuple3(1, 0, 1, 0)
        vec.InsertTuple3(2, 0, 0, 1)
        pd.GetPointData().SetVectors(vec)

        # The glyph filter.
        g = vtk.vtkGlyph3D()
        g.SetScaleModeToDataScalingOff()
        g.SetVectorModeToUseVector()
        g.SetInputData(pd)
        g.SetSourceConnection(cs.GetOutputPort())

        m = vtk.vtkPolyDataMapper()
        m.SetInputConnection(g.GetOutputPort())
        a = vtk.vtkActor()
        a.SetMapper(m)

        # The texture.
        img_file = os.path.join(Testing.VTK_DATA_ROOT, "Data", "masonry.bmp")
        img_r = vtk.vtkBMPReader()
        img_r.SetFileName(img_file)
        t = vtk.vtkTexture()
        t.SetInputConnection(img_r.GetOutputPort())
        t.InterpolateOn()
        a.SetTexture(t)

        # Renderer, RenderWindow etc.
        ren = vtk.vtkRenderer()
        ren.SetBackground(0.5, 0.5, 0.5)
        ren.AddActor(a)

        ren.ResetCamera()
        cam = ren.GetActiveCamera()
        cam.Azimuth(-90)
        cam.Zoom(1.4)

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        rwi = vtk.vtkRenderWindowInteractor()
        rwi.SetRenderWindow(renWin)
        rwi.Initialize()
        rwi.Render()
Esempio n. 32
0
def laplacian_of_gaussian(inpd,
                          fiber_distance_sigma=25,
                          points_per_fiber=30,
                          n_jobs=2,
                          upper_thresh=30):
    """ Filter nearby fibers, using LoG weights.
    
    The pairwise fiber distance matrix is computed, then fibers are
    averaged with their neighbors using LoG weighting.  This is
    essentially a fiber subtraction operation, giving vectors pointing
    from the center fiber under the kernel, to all nearby fibers. Thus
    the output of this operation is not a fiber, but we compute
    properties of the output that might be interesting and related to
    fibers. We summarize the result using the average vector at each
    fiber point (output is its magnitude, similar to edge
    strength). The covariance of the vectors is also
    investigated. This matrix would be spherical in an isotropic
    region such as a tract center (tube/line detector), or planar in a
    sheetlike tract (sheet detector).

    The equation is: (1-d^2/sigma^2) exp(-d^2/(2*sigma^2)), and
    weights are normalized in the neighborhood (weighted averaging).
    """

    sigmasq = fiber_distance_sigma * fiber_distance_sigma

    # polydata to array conversion, fixed-length fiber representation
    fiber_array = fibers.FiberArray()
    fiber_array.points_per_fiber = points_per_fiber
    fiber_array.convert_from_polydata(inpd)

    fiber_indices = list(range(0, fiber_array.number_of_fibers))

    # pairwise distance matrix
    if USE_PARALLEL:
        distances = Parallel(n_jobs=n_jobs, verbose=1)(
            delayed(similarity.fiber_distance)(fiber_array.get_fiber(
                lidx), fiber_array, 0, 'Hausdorff') for lidx in fiber_indices)
        distances = numpy.array(distances)
    else:
        distances = \
            numpy.zeros(
            (fiber_array.number_of_fibers,
             fiber_array.number_of_fibers))
        for lidx in fiber_indices:
            distances[lidx, :] = \
                similarity.fiber_distance(
                    fiber_array.get_fiber(lidx),
                    fiber_array, 0)

    # fiber list data structure initialization for easy fiber averaging
    fiber_list = list()
    for lidx in range(0, fiber_array.number_of_fibers):
        fiber_list.append(fiber_array.get_fiber(lidx))

    filter_vectors = list()
    filter_vector_magnitudes = list()
    filter_confidences = list()

    # gaussian smooth all fibers using local neighborhood
    for fidx in fiber_indices:
        if (fidx % 100) == 0:
            print(fidx, '/', fiber_array.number_of_fibers)

        current_fiber = fiber_list[fidx]

        # find indices of all nearby fibers
        # this includes the center fiber under the kernel
        indices = numpy.nonzero(distances[fidx] < upper_thresh)[0]
        local_fibers = list()
        local_weights = list()

        for idx in indices:
            dist = distances[fidx][idx]
            # compute filter kernel weights
            weight = numpy.exp(-(dist * dist) / sigmasq)
            #weight = (1 - (dist*dist)/sigmasq) * numpy.exp(-(dist*dist)/(2*sigmasq))
            local_fibers.append(fiber_list[idx])
            local_weights.append(weight)

        # actually perform the weighted average
        #mean_weight = numpy.mean(numpy.array(local_weights))
        #out_weights = local_weights[0]
        #for weight in local_weights[1:]:
        #    out_weights += weight
        # the weights must sum to 0 for LoG
        # (response in constant region is 0)
        #mean_weight = out_weights / len(local_weights)
        #local_normed_weights = list()
        #for weight in local_weights:
        #    local_normed_weights.append(weight - mean_weight)

        #match_fiber = local_fibers[0]
        #out_vector = local_fibers[0] * local_normed_weights[0]
        idx = 0
        for fiber in local_fibers:
            #out_vector += fiber
            # ensure fiber ordering by matching to current fiber only
            # otherwise the order is undefined after fiber subtraction
            matched_fiber = current_fiber.match_order(fiber)
            #filtered_fiber = matched_version * local_normed_weights[idx]
            #filtered_fiber = matched_version * local_weights[idx]
            if idx == 0:
                out_vector = fibers.Fiber()
                out_vector.points_per_fiber = points_per_fiber
                out_vector.r = numpy.zeros(points_per_fiber)
                out_vector.a = numpy.zeros(points_per_fiber)
                out_vector.s = numpy.zeros(points_per_fiber)
            #filtered_fiber = match_fiber.match_order(fiber)
            #out_vector.r = (out_vector.r + matched_fiber.r) * local_weights[idx]
            #out_vector.a = (out_vector.a + matched_fiber.a) * local_weights[idx]
            #out_vector.s = (out_vector.s + matched_fiber.s) * local_weights[idx]
            out_vector.r += (current_fiber.r -
                             matched_fiber.r) * local_weights[idx]
            out_vector.a += (current_fiber.a -
                             matched_fiber.a) * local_weights[idx]
            out_vector.s += (current_fiber.s -
                             matched_fiber.s) * local_weights[idx]
            idx += 1

        total_weights = numpy.sum(numpy.array(local_weights))
        out_vector = out_vector / total_weights

        filter_vectors.append(out_vector)
        filter_confidences.append(total_weights)

        filter_vector_magnitudes.append(numpy.sqrt(\
                numpy.multiply(out_vector.r, out_vector.r) + \
                    numpy.multiply(out_vector.a, out_vector.a) + \
                    numpy.multiply(out_vector.s, out_vector.s)))
        #filter_vector_magnitudes.append(numpy.sum(out_vector.r))

    # output a new pd!!!!
    # with fixed length fibers. and the new vector field.
    # output the vectors from the filtering
    outpd = fiber_array.convert_to_polydata()
    vectors = vtk.vtkFloatArray()
    vectors.SetName('FiberDifferenceVectors')
    vectors.SetNumberOfComponents(3)
    for vec in filter_vectors:
        for idx in range(points_per_fiber):
            vectors.InsertNextTuple3(vec.r[idx], vec.a[idx], vec.s[idx])
    magnitudes = vtk.vtkFloatArray()
    magnitudes.SetName('FiberDifferenceMagnitudes')
    magnitudes.SetNumberOfComponents(1)
    for mag in filter_vector_magnitudes:
        for idx in range(points_per_fiber):
            magnitudes.InsertNextTuple1(mag[idx])
    confidences = vtk.vtkFloatArray()
    confidences.SetName('FiberDifferenceConfidences')
    confidences.SetNumberOfComponents(1)
    for mag in filter_confidences:
        for idx in range(points_per_fiber):
            confidences.InsertNextTuple1(mag)

    outpd.GetPointData().AddArray(vectors)
    outpd.GetPointData().SetActiveVectors('FiberDifferenceVectors')

    outpd.GetPointData().AddArray(confidences)
    outpd.GetPointData().SetActiveScalars('FiberDifferenceConfidences')

    outpd.GetPointData().AddArray(magnitudes)
    outpd.GetPointData().SetActiveScalars('FiberDifferenceMagnitudes')

    # color by the weights or "local density"
    # color output by the number of fibers that each output fiber corresponds to
    #outcolors = vtk.vtkFloatArray()
    #outcolors.SetName('KernelDensity')
    #for weight in next_weights:
    #    outcolors.InsertNextTuple1(weight)
    #inpd.GetCellData().AddArray(outcolors)
    #inpd.GetCellData().SetActiveScalars('KernelDensity')
    #outcolors = vtk.vtkFloatArray()
    #outcolors.SetName('EdgeMagnitude')
    #for magnitude in filter_vector_magnitudes:
    #    outcolors.InsertNextTuple1(magnitude)
    #inpd.GetCellData().AddArray(outcolors)
    #inpd.GetCellData().SetActiveScalars('EdgeMagnitude')

    return outpd, numpy.array(filter_vector_magnitudes)
Esempio n. 33
0
def parseFile():
    global VTK_DATA_ROOT, dos

    # Use Python to read an ASCII file
    file = open(os.path.join(VTK_DATA_ROOT, "Data/financial.txt"), "r")

    line = file.readline()
    numPts = int(getNumberFromLine(line)[0])

    numLines = (numPts - 1) // 8
    # Get the data object's field data and allocate
    # room for 4, fields
    fieldData = dos.GetOutput().GetFieldData()
    fieldData.AllocateArrays(4)

    # read TIME_LATE - dependent variable
    # search the file until an array called TIME_LATE is found
    while file.readline()[:9] != "TIME_LATE":
        pass

    # Create the corresponding float array
    timeLate = vtk.vtkFloatArray()
    timeLate.SetName("TIME_LATE")
    # Read the values
    for i in range(0, numLines):
        val = getNumberFromLine(file.readline())
        for j in range(0, 8):
            timeLate.InsertNextValue(val[j])
    # Add the array
    fieldData.AddArray(timeLate)

    # MONTHLY_PAYMENT - independent variable
    while file.readline()[:15] != "MONTHLY_PAYMENT":
        pass

    monthlyPayment = vtk.vtkFloatArray()
    monthlyPayment.SetName("MONTHLY_PAYMENT")
    for i in range(0, numLines):
        val = getNumberFromLine(file.readline())
        for j in range(0, 8):
            monthlyPayment.InsertNextValue(val[j])

    fieldData.AddArray(monthlyPayment)

    # UNPAID_PRINCIPLE - skip
    while file.readline()[:16] != "UNPAID_PRINCIPLE":
        pass
    for i in range(0, numLines):
        file.readline()

    # LOAN_AMOUNT - skip
    while file.readline()[:11] != "LOAN_AMOUNT":
        pass
    for i in range(0, numLines):
        file.readline()

    # INTEREST_RATE - independent variable
    while file.readline()[:13] != "INTEREST_RATE":
        pass

    interestRate = vtk.vtkFloatArray()
    interestRate.SetName("INTEREST_RATE")
    for i in range(0, numLines):
        val = getNumberFromLine(file.readline())
        for j in range(0, 8):
            interestRate.InsertNextValue(val[j])

    fieldData.AddArray(interestRate)

    # MONTHLY_INCOME - independent variable
    while file.readline()[:14] != "MONTHLY_INCOME":
        pass

    monthlyIncome = vtk.vtkFloatArray()
    monthlyIncome.SetName("MONTHLY_INCOME")
    for i in range(0, numLines):
        val = getNumberFromLine(file.readline())
        for j in range(0, 8):
            monthlyIncome.InsertNextValue(val[j])

    fieldData.AddArray(monthlyIncome)
Esempio n. 34
0
#!/bin/python

import vtk
import math

view = vtk.vtkContextView()
view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
view.GetRenderWindow().SetSize(400, 300)

chart = vtk.vtkChartXY()
view.GetScene().AddItem(chart)
chart.SetShowLegend(True)

arrX = vtk.vtkFloatArray()
arrX.SetName("X Axis")

arrC = vtk.vtkFloatArray()
arrC.SetName("Cosine")

arrS = vtk.vtkFloatArray()
arrS.SetName("Sine")

arrT = vtk.vtkFloatArray()
arrT.SetName("Sine - Cosine")

numPoints = 40
inc = 7.5 / (numPoints - 1)
#table.SetNumberOfRows(numPoints)
for i in range(numPoints):
    #table.SetValue(i, 0, i * inc)
    #table.SetValue(i, 1, math.cos(i * inc) + 0.0)
Esempio n. 35
0
    def _plotInternal(self):
        """Overrides baseclass implementation."""
        # Preserve time and z axis for plotting these inof in rendertemplate
        projection = vcs.elements["projection"][self._gm.projection]
        zaxis, taxis = self.getZandT()
        scale = 1.0

        if self._vtkGeoTransform is not None:
            lat = None
            lon = None

            latAccessor = self._data1.getLatitude()
            lonAccessor = self._data1.getLongitude()
            if latAccessor:
                lat = latAccessor[:]
            if lonAccessor:
                lon = lonAccessor[:]
            newv = vtk.vtkDoubleArray()
            newv.SetNumberOfComponents(3)
            newv.InsertTypedTuple(0, [lon.min(), lat.min(), 0])
            newv.InsertTypedTuple(1, [lon.max(), lat.max(), 0])

            vcs2vtk.projectArray(newv, projection, self._vtkDataSetBounds)
            dimMin = [0, 0, 0]
            dimMax = [0, 0, 0]

            newv.GetTypedTuple(0, dimMin)
            newv.GetTypedTuple(1, dimMax)

            maxDimX = max(dimMin[0], dimMax[0])
            maxDimY = max(dimMin[1], dimMax[1])

            if lat.max() != 0.0:
                scale = abs((maxDimY / lat.max()))

            if lon.max() != 0.0:
                temp = abs((maxDimX / lon.max()))
                if scale < temp:
                    scale = temp
        else:
            scale = 1.0

        # Vector attempt
        ltp_tmp = self._gm.linetype
        if ltp_tmp is None:
            ltp_tmp = "default"
        try:
            ltp_tmp = vcs.getline(ltp_tmp)
            lwidth = ltp_tmp.width[0]  # noqa
            lcolor = ltp_tmp.color[0]
            lstyle = ltp_tmp.type[0]  # noqa
        except Exception:
            lstyle = "solid"  # noqa
            lwidth = 1.  # noqa
            lcolor = [0., 0., 0., 100.]
        if self._gm.linewidth is not None:
            lwidth = self._gm.linewidth  # noqa
        if self._gm.linecolor is not None:
            lcolor = self._gm.linecolor

        arrow = vtk.vtkGlyphSource2D()
        arrow.SetGlyphTypeToArrow()
        arrow.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION)
        arrow.FilledOff()

        plotting_dataset_bounds = self.getPlottingBounds()
        x1, x2, y1, y2 = plotting_dataset_bounds
        vp = self._resultDict.get('ratio_autot_viewport', [
            self._template.data.x1, self._template.data.x2,
            self._template.data.y1, self._template.data.y2
        ])

        # The unscaled continent bounds were fine in the presence of axis
        # conversion, so save them here
        adjusted_plotting_bounds = vcs2vtk.getProjectedBoundsForWorldCoords(
            plotting_dataset_bounds, self._gm.projection)
        continentBounds = vcs2vtk.computeDrawAreaBounds(
            adjusted_plotting_bounds)

        # Transform the input data
        T = vtk.vtkTransform()
        T.Scale(self._context_xScale, self._context_yScale, 1.)
        self._vtkDataSetFittedToViewport = vcs2vtk.applyTransformationToDataset(
            T, self._vtkDataSetFittedToViewport)
        self._vtkDataSetBoundsNoMask = self._vtkDataSetFittedToViewport.GetBounds(
        )

        polydata = self._vtkDataSetFittedToViewport

        # view and interactive area
        view = self._context().contextView
        area = vtk.vtkInteractiveArea()
        view.GetScene().AddItem(area)

        drawAreaBounds = vcs2vtk.computeDrawAreaBounds(
            self._vtkDataSetBoundsNoMask, self._context_flipX,
            self._context_flipY)

        [renWinWidth, renWinHeight] = self._context().renWin.GetSize()
        geom = vtk.vtkRecti(int(round(vp[0] * renWinWidth)),
                            int(round(vp[2] * renWinHeight)),
                            int(round((vp[1] - vp[0]) * renWinWidth)),
                            int(round((vp[3] - vp[2]) * renWinHeight)))

        vcs2vtk.configureContextArea(area, drawAreaBounds, geom)

        # polydata = tmpMapper.GetInput()
        plotting_dataset_bounds = self.getPlottingBounds()

        vectors = polydata.GetPointData().GetVectors()

        if self._gm.scaletype == 'constant' or\
           self._gm.scaletype == 'constantNNormalize' or\
           self._gm.scaletype == 'constantNLinear':
            scaleFactor = scale * self._gm.scale
        else:
            scaleFactor = 1.0

        glyphFilter = vtk.vtkGlyph2D()
        glyphFilter.SetInputArrayToProcess(1, 0, 0, 0, "vector")
        glyphFilter.SetSourceConnection(arrow.GetOutputPort())
        glyphFilter.SetVectorModeToUseVector()

        # Rotate arrows to match vector data:
        glyphFilter.OrientOn()
        glyphFilter.ScalingOn()

        glyphFilter.SetScaleModeToScaleByVector()

        maxNormInVp = None
        minNormInVp = None
        # Find the min and max vector magnitudes
        (minNorm, maxNorm) = vectors.GetRange(-1)
        if maxNorm == 0:
            maxNorm = 1.0

        if self._gm.scaletype == 'normalize' or self._gm.scaletype == 'linear' or\
           self._gm.scaletype == 'constantNNormalize' or self._gm.scaletype == 'constantNLinear':
            if self._gm.scaletype == 'normalize' or self._gm.scaletype == 'constantNNormalize':
                scaleFactor /= maxNorm

            if self._gm.scaletype == 'linear' or self._gm.scaletype == 'constantNLinear':
                noOfComponents = vectors.GetNumberOfComponents()
                scalarArray = vtk.vtkDoubleArray()
                scalarArray.SetNumberOfComponents(1)
                scalarArray.SetNumberOfValues(vectors.GetNumberOfTuples())

                oldRange = maxNorm - minNorm
                oldRange = 1.0 if oldRange == 0.0 else oldRange

                # New range min, max.
                newRangeValues = self._gm.scalerange
                newRange = newRangeValues[1] - newRangeValues[0]

                for i in range(0, vectors.GetNumberOfTuples()):
                    norm = vtk.vtkMath.Norm(vectors.GetTuple(i),
                                            noOfComponents)
                    newValue = (((norm - minNorm) * newRange) /
                                oldRange) + newRangeValues[0]
                    scalarArray.SetValue(i, newValue)

                polydata.GetPointData().SetScalars(scalarArray)
                maxNormInVp = newRangeValues[1] * scaleFactor
                minNormInVp = newRangeValues[0] * scaleFactor

                # Scale to vector magnitude:
                # NOTE: Currently we compute our own scaling factor since VTK does
                # it by clamping the values > max to max  and values < min to min
                # and not remap the range.
                glyphFilter.SetScaleModeToScaleByScalar()

        if (maxNormInVp is None):
            maxNormInVp = maxNorm * scaleFactor
            # minNormInVp is left None, as it is displayed only for linear scaling.

        cmap = self.getColorMap()
        if isinstance(lcolor, (list, tuple)):
            r, g, b, a = lcolor
        else:
            r, g, b, a = cmap.index[lcolor]
        # act.GetProperty().SetColor(r / 100., g / 100., b / 100.)
        vtk_color = [int((c / 100.) * 255) for c in [r, g, b, a]]

        # Using the scaled data, set the glyph filter input
        glyphFilter.SetScaleFactor(scaleFactor)
        glyphFilter.SetInputData(polydata)
        glyphFilter.Update()
        # and set the arrows to be rendered.

        data = glyphFilter.GetOutput()

        floatValue = vtk.vtkFloatArray()
        floatValue.SetNumberOfComponents(1)
        floatValue.SetName("LineWidth")
        floatValue.InsertNextValue(lwidth)
        data.GetFieldData().AddArray(floatValue)

        item = vtk.vtkPolyDataItem()
        item.SetPolyData(data)

        item.SetScalarMode(vtk.VTK_SCALAR_MODE_USE_CELL_DATA)

        colorArray = vtk.vtkUnsignedCharArray()
        colorArray.SetNumberOfComponents(4)
        for i in range(data.GetNumberOfCells()):
            colorArray.InsertNextTypedTuple(vtk_color)

        item.SetMappedColors(colorArray)
        area.GetDrawAreaItem().AddItem(item)

        kwargs = {
            'vtk_backend_grid':
            self._vtkDataSet,
            'dataset_bounds':
            self._vtkDataSetBounds,
            'plotting_dataset_bounds':
            plotting_dataset_bounds,
            "vtk_dataset_bounds_no_mask":
            self._vtkDataSetBoundsNoMask,
            'vtk_backend_geo':
            self._vtkGeoTransform,
            "vtk_backend_draw_area_bounds":
            continentBounds,
            "vtk_backend_viewport_scale":
            [self._context_xScale, self._context_yScale]
        }
        if ('ratio_autot_viewport' in self._resultDict):
            kwargs["ratio_autot_viewport"] = vp
        self._resultDict.update(self._context().renderTemplate(
            self._template, self._data1, self._gm, taxis, zaxis, **kwargs))

        # assume that self._data1.units has the proper vector units
        unitString = None
        if (hasattr(self._data1, 'units')):
            unitString = self._data1.units

        if self._vtkGeoTransform:
            worldWidth = self._vtkDataSetBoundsNoMask[
                1] - self._vtkDataSetBoundsNoMask[0]
        else:
            worldWidth = self._vtkDataSetBounds[1] - self._vtkDataSetBounds[0]

        worldToViewportXScale = (vp[1] - vp[0]) / worldWidth
        maxNormInVp *= worldToViewportXScale
        if (minNormInVp):
            minNormInVp *= worldToViewportXScale
        vcs.utils.drawVectorLegend(self._context().canvas,
                                   self._template.legend,
                                   lcolor,
                                   lstyle,
                                   lwidth,
                                   unitString,
                                   maxNormInVp,
                                   maxNorm,
                                   minNormInVp,
                                   minNorm,
                                   reference=self._gm.reference)

        kwargs['xaxisconvert'] = self._gm.xaxisconvert
        kwargs['yaxisconvert'] = self._gm.yaxisconvert
        if self._data1.getAxis(-1).isLongitude() and self._data1.getAxis(
                -2).isLatitude():
            self._context().plotContinents(
                self._plot_kargs.get("continents", self._useContinents),
                plotting_dataset_bounds, projection, self._dataWrapModulo, vp,
                self._template.data.priority, **kwargs)
        self._resultDict["vtk_backend_actors"] = [[
            item, plotting_dataset_bounds
        ]]
        self._resultDict["vtk_backend_glyphfilters"] = [glyphFilter]
        self._resultDict["vtk_backend_luts"] = [[None, None]]
Esempio n. 36
0
def bbox2vtk(data, attributes, vtk_file):
    points_data = vtk.vtkPoints()
    cells = vtk.vtkCellArray()
    num_cells = data.shape[0]
    for i in range(num_cells):
        pos = data[i, 0:3]
        print('pos:', pos)
        x = 0.5 * data[i, 3]  # len, x
        h = data[i, 4]  # height, z
        y = 0.5 * data[i, 5]  # width, y
        yaw = 0.5 * math.pi - data[i, 6]
        q = Quaternion(axis=[0, 0, 1], angle=yaw)
        tmp_pos0 = q.rotate([-x, -y, pos[2]])
        tmp_pos1 = q.rotate([-x, +y, pos[2]])
        tmp_pos2 = q.rotate([+x, +y, pos[2]])
        tmp_pos3 = q.rotate([+x, -y, pos[2]])
        points_data.InsertNextPoint(pos[0] + tmp_pos0[0], pos[1] + tmp_pos0[1],
                                    tmp_pos0[2])
        points_data.InsertNextPoint(pos[0] + tmp_pos1[0], pos[1] + tmp_pos1[1],
                                    tmp_pos1[2])
        points_data.InsertNextPoint(pos[0] + tmp_pos2[0], pos[1] + tmp_pos2[1],
                                    tmp_pos2[2])
        points_data.InsertNextPoint(pos[0] + tmp_pos3[0], pos[1] + tmp_pos3[1],
                                    tmp_pos3[2])

        points_data.InsertNextPoint(pos[0] + tmp_pos0[0], pos[1] + tmp_pos0[1],
                                    tmp_pos0[2] + h)
        points_data.InsertNextPoint(pos[0] + tmp_pos1[0], pos[1] + tmp_pos1[1],
                                    tmp_pos1[2] + h)
        points_data.InsertNextPoint(pos[0] + tmp_pos2[0], pos[1] + tmp_pos2[1],
                                    tmp_pos2[2] + h)
        points_data.InsertNextPoint(pos[0] + tmp_pos3[0], pos[1] + tmp_pos3[1],
                                    tmp_pos3[2] + h)
        off = i * 8
        cells.InsertNextCell(5, [off + 0, off + 1, off + 2, off + 3, off + 0])
        cells.InsertNextCell(5, [off + 4, off + 5, off + 6, off + 7, off + 4])
        cells.InsertNextCell(2, [off + 0, off + 4])
        cells.InsertNextCell(2, [off + 1, off + 5])
        cells.InsertNextCell(2, [off + 2, off + 6])
        cells.InsertNextCell(2, [off + 3, off + 7])
    bx_attrs = []
    for attr in attributes:
        if attr[1] == 'int1':
            tmp_attr = vtk.vtkIntArray()
            tmp_attr.SetName(attr[0])
            tmp_attr.SetNumberOfComponents(1)
            tmp_attr.SetNumberOfTuples(num_cells * 6)
            for i in range(0, num_cells):
                tmp_attr.SetTuple1(i * 6, attr[2][i])
                tmp_attr.SetTuple1(i * 6 + 1, attr[2][i])
                tmp_attr.SetTuple1(i * 6 + 2, attr[2][i])
                tmp_attr.SetTuple1(i * 6 + 3, attr[2][i])
                tmp_attr.SetTuple1(i * 6 + 4, attr[2][i])
                tmp_attr.SetTuple1(i * 6 + 5, attr[2][i])
            bx_attrs.append(tmp_attr)
        elif attr[1] == 'float1':
            tmp_attr = vtk.vtkFloatArray()
            tmp_attr.SetName(attr[0])
            tmp_attr.SetNumberOfComponents(1)
            tmp_attr.SetNumberOfTuples(num_cells * 6)
            for i in range(0, num_cells):
                tmp_attr.SetTuple1(i * 6, attr[2][i])
                tmp_attr.SetTuple1(i * 6 + 1, attr[2][i])
                tmp_attr.SetTuple1(i * 6 + 2, attr[2][i])
                tmp_attr.SetTuple1(i * 6 + 3, attr[2][i])
                tmp_attr.SetTuple1(i * 6 + 4, attr[2][i])
                tmp_attr.SetTuple1(i * 6 + 5, attr[2][i])
            bx_attrs.append(tmp_attr)

    bboxes = vtk.vtkPolyData()
    bboxes.SetPoints(points_data)
    bboxes.SetLines(cells)
    for bx_at in bx_attrs:
        bboxes.GetCellData().AddArray(bx_at)
    poly_data_writer = vtk.vtkPolyDataWriter()
    poly_data_writer.SetInputData(bboxes)
    poly_data_writer.SetFileName(vtk_file)
    poly_data_writer.SetFileTypeToBinary()
    poly_data_writer.Write()
Esempio n. 37
0
    ]
    points.InsertNextPoint(numPointData[:])

# Separar las conexiones entre puntos y guardarlas en una estructura
lines = vtk.vtkCellArray()
for line in atomsConnectionsDataset:
    stringList = line.split(' ')
    position = int(stringList[0])
    value = int(stringList[1])

    lines.InsertNextCell(2)
    lines.InsertCellPoint(position)
    lines.InsertCellPoint(value)

# Guardar los radios en una estructura
scalars = vtk.vtkFloatArray()
for valueStr in radiusDataset:
    value = float(valueStr)
    scalars.InsertNextValue(value)

# Crear el renderer
renderer = vtk.vtkRenderer()

# Crear la estructura para pintar los datos
glyph = vtk.vtkGlyph3D()
glyph.SetScaleFactor(0.1)

# Crear LUT para colorear las esferas
lut = vtkColorTransferFunction()
lut.SetColorSpaceToRGB()
lut.AddRGBPoint(0.3, 1, 1, 1)
Esempio n. 38
0
def main():
    # x = array of 8 3-tuples of float representing the vertices of a cube:
    x = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0),
         (0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0)]

    # pts = array of 6 4-tuples of vtkIdType (int) representing the faces
    #     of the cube in terms of the above vertices
    pts = [(0, 1, 2, 3), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5),
           (2, 3, 7, 6), (3, 0, 4, 7)]

    # We'll create the building blocks of polydata including data attributes.
    cube = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    polys = vtk.vtkCellArray()
    scalars = vtk.vtkFloatArray()

    # Load the point, cell, and data attributes.
    for i in range(8):
        points.InsertPoint(i, x[i])
    for i in range(6):
        polys.InsertNextCell(mkVtkIdList(pts[i]))
    for i in range(8):
        scalars.InsertTuple1(i, i)

    # We now assign the pieces to the vtkPolyData.
    cube.SetPoints(points)
    del points
    cube.SetPolys(polys)
    del polys
    cube.GetPointData().SetScalars(scalars)
    del scalars

    # Now we'll look at it.
    cubeMapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        cubeMapper.SetInput(cube)
    else:
        cubeMapper.SetInputData(cube)
    cubeMapper.SetScalarRange(0, 7)
    cubeActor = vtk.vtkActor()
    cubeActor.SetMapper(cubeMapper)

    # The usual rendering stuff.
    camera = vtk.vtkCamera()
    camera.SetPosition(1, 1, 1)
    camera.SetFocalPoint(0, 0, 0)

    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)

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

    renderer.AddActor(cubeActor)
    renderer.SetActiveCamera(camera)
    renderer.ResetCamera()
    renderer.SetBackground(1, 1, 1)

    renWin.SetSize(300, 300)

    # interact with data
    renWin.Render()
    iren.Start()

    # Clean up
    del cube
    del cubeMapper
    del cubeActor
    del camera
    del renderer
    del renWin
    del iren
Esempio n. 39
0
sphereActor.GetProperty().SetOpacity(.3)
sphereActor.GetProperty().SetColor(1, 0, 0)

implicitPolyDataDistance = vtk.vtkImplicitPolyDataDistance()
implicitPolyDataDistance.SetInput(sphereSource.GetOutput())

# Setup a grid
points = vtk.vtkPoints()
step = 0.1
for x in np.arange(-2, 2, step):
    for y in np.arange(-2, 2, step):
        for z in np.arange(-2, 2, step):
            points.InsertNextPoint(x, y, z)

# Add distances to each point
signedDistances = vtk.vtkFloatArray()
signedDistances.SetNumberOfComponents(1)
signedDistances.SetName("SignedDistances")

# Evaluate the signed distance function at all of the grid points
for pointId in range(points.GetNumberOfPoints()):
    p = points.GetPoint(pointId)
    signedDistance = implicitPolyDataDistance.EvaluateFunction(p)
    signedDistances.InsertNextValue(signedDistance)

polyData = vtk.vtkPolyData()
polyData.SetPoints(points)
polyData.GetPointData().SetScalars(signedDistances)

vertexGlyphFilter = vtk.vtkVertexGlyphFilter()
vertexGlyphFilter.SetInputData(polyData)
Esempio n. 40
0
import vtk
from math import sqrt

plane = vtk.vtkPlane()
plane.SetOrigin(5, 5, 9.8)
plane.SetNormal(0, 0, 1)

coords = [(0, 0, 0), (10, 0, 0), (10, 10, 0), (0, 10, 0), (0, 0, 10),
          (10, 0, 10), (10, 10, 10), (0, 10, 10), (5, 0, 0), (10, 5, 0),
          (5, 10, 0), (0, 5, 0), (5, 0, 9.5), (10, 5, 9.3), (5, 10, 9.5),
          (0, 5, 9.3), (0, 0, 5), (10, 0, 5), (10, 10, 5), (0, 10, 5)]
data = vtk.vtkFloatArray()
points = vtk.vtkPoints()
ptIds = vtk.vtkIdList()
mesh = vtk.vtkUnstructuredGrid()
mesh.SetPoints(points)
mesh.GetPointData().SetScalars(data)

for id in range(0, 20):
    x = coords[id][0]
    y = coords[id][1]
    z = coords[id][2]
    ptIds.InsertNextId(id)
    points.InsertNextPoint(x, y, z)
    data.InsertNextValue(sqrt(x * x + y * y + z * z))
mesh.InsertNextCell(vtk.VTK_QUADRATIC_HEXAHEDRON, ptIds)

ptIds.Reset()
for id in range(0, 8):
    x = coords[id][0] + 20
    y = coords[id][1] + 20
Esempio n. 41
0
def readPoints(file, depth_scaling=0.01):
    # Create an array of Points
    points = vtk.vtkPoints()
    # Create arrays of Scalars
    scalars = vtk.vtkFloatArray()
    tid     = vtk.vtkFloatArray()
    depth   = vtk.vtkFloatArray()

    # Initialize
    LatMax=0
    LatMin=360
    LonMax=0
    LonMin=360
    tMin=99999999999999

    # Open the file
    file = open(file)

    # Read one line
    line = file.readline()

    # Loop through lines
    tMin = 1.0e15
    while line:
        # Split the line into data
        data = line.split('|')
        # Skip the commented lines
        if data and data[0][0] != '#':
            # Convert data into float
            print(data[0], data[1], data[2], data[3], data[4].split('--')[0], data[10])
            date, x, y, z, r = data[1], float(data[2]), float(data[3]),  float(data[4]), float(data[10])
            z_scaled = z * depth_scaling
            row=date.split('T')
            adate=row[0].split('-')
            atime=row[1].split(':')
            temp=atime[2].split('.')
            atime[2]=temp[0]

            if atime[2]=='':
                atime[2]='00'
            t= time.mktime((int(adate[0]),int(adate[1]),int(adate[2]),int(atime[0]),int(atime[1]),int(atime[2]),0,0,0))
            if x > LatMax:
                LatMax=x
            if x< LatMin:
                LatMin=x
            if y > LonMax:
                LonMax=y
            if y< LonMin:
                LonMin=y
            if t< tMin:
                 tMin=t

            # Insert floats into the point array
            points.InsertNextPoint(x, y, z_scaled)
            scalars.InsertNextValue(r)
            t -= 1467247524.0  #FIXME
            tid.InsertNextValue(t)
            depth.InsertNextValue(z_scaled)

        # read next line
        line = file.readline()
    print(LatMin, LatMax, LonMin, LonMax)

    return points, scalars, tid, depth
Esempio n. 42
0
def smooth(inpd,
           fiber_distance_sigma=25,
           points_per_fiber=30,
           n_jobs=2,
           upper_thresh=30):
    """ Average nearby fibers.
    
    The pairwise fiber distance matrix is computed, then fibers
    are averaged with their neighbors using Gaussian weighting.

    The "local density" or soft neighbor count is also output.
    """

    sigmasq = fiber_distance_sigma * fiber_distance_sigma

    # polydata to array conversion, fixed-length fiber representation
    current_fiber_array = fibers.FiberArray()
    current_fiber_array.points_per_fiber = points_per_fiber
    current_fiber_array.convert_from_polydata(inpd)

    # fiber list data structure initialization for easy fiber averaging
    curr_count = list()
    curr_fibers = list()
    next_fibers = list()
    next_weights = list()
    for lidx in range(0, current_fiber_array.number_of_fibers):
        curr_fibers.append(current_fiber_array.get_fiber(lidx))
        curr_count.append(1)

    fiber_indices = list(range(0, current_fiber_array.number_of_fibers))

    # compare squared distances to squared distance threshold
    upper_thresh = upper_thresh * upper_thresh

    print("<filter.py> Computing pairwise distances...")

    # pairwise distance matrix
    if USE_PARALLEL:
        distances = Parallel(n_jobs=n_jobs, verbose=1)(
            delayed(similarity.fiber_distance)(current_fiber_array.get_fiber(
                lidx), current_fiber_array, 0, 'Hausdorff')
            for lidx in fiber_indices)
        distances = numpy.array(distances)
    else:
        distances = \
            numpy.zeros(
            (current_fiber_array.number_of_fibers,
             current_fiber_array.number_of_fibers))
        for lidx in fiber_indices:
            distances[lidx, :] = \
                similarity.fiber_distance(
                    current_fiber_array.get_fiber(lidx),
                    current_fiber_array, 0)

    # gaussian smooth all fibers using local neighborhood
    for fidx in fiber_indices:
        if (fidx % 100) == 0:
            print(fidx, '/', current_fiber_array.number_of_fibers)

        # find indices of all nearby fibers
        indices = numpy.nonzero(distances[fidx] < upper_thresh)[0]
        local_fibers = list()
        local_weights = list()

        for idx in indices:
            dist = distances[fidx][idx]
            # these are now squared distances
            weight = numpy.exp(-dist / sigmasq)
            #weight = numpy.exp(-(dist*dist)/sigmasq)
            local_fibers.append(curr_fibers[idx] * weight)
            local_weights.append(weight)
        # actually perform the weighted average
        # start with the one under the center of the kernel
        #out_fiber = curr_fibers[fidx]
        #out_weights = 1.0
        out_fiber = local_fibers[0]
        out_weights = local_weights[0]
        for fiber in local_fibers[1:]:
            out_fiber += fiber
        for weight in local_weights[1:]:
            out_weights += weight
        out_fiber = out_fiber / out_weights
        next_fibers.append(out_fiber)
        next_weights.append(out_weights)

    # set up array for output
    output_fiber_array = fibers.FiberArray()
    output_fiber_array.number_of_fibers = len(curr_fibers)
    output_fiber_array.points_per_fiber = points_per_fiber
    dims = [
        output_fiber_array.number_of_fibers,
        output_fiber_array.points_per_fiber
    ]
    # fiber data
    output_fiber_array.fiber_array_r = numpy.zeros(dims)
    output_fiber_array.fiber_array_a = numpy.zeros(dims)
    output_fiber_array.fiber_array_s = numpy.zeros(dims)
    next_fidx = 0
    for next_fib in next_fibers:
        output_fiber_array.fiber_array_r[next_fidx] = next_fib.r
        output_fiber_array.fiber_array_a[next_fidx] = next_fib.a
        output_fiber_array.fiber_array_s[next_fidx] = next_fib.s
        next_fidx += 1

    # convert output to polydata
    outpd = output_fiber_array.convert_to_polydata()

    # color by the weights or "local density"
    # color output by the number of fibers that each output fiber corresponds to
    outcolors = vtk.vtkFloatArray()
    outcolors.SetName('KernelDensity')
    for weight in next_weights:
        outcolors.InsertNextTuple1(weight)
    #outpd.GetCellData().SetScalars(outcolors)
    outpd.GetCellData().AddArray(outcolors)
    outpd.GetCellData().SetActiveScalars('KernelDensity')

    return outpd, numpy.array(next_weights)
Esempio n. 43
0
def isoFile(filename):
 lines=0
 geomfile=open(filename,"rb")
 m=1
 spherepoints= vtk.vtkPoints()
 radii=vtk.vtkFloatArray()
 cubepoints=vtk.vtkPoints()
 while geomfile:
   line = geomfile.readline()
   if line == "":
    break
   line = str.rstrip(line)
   cols =line.split('	')
   
   x=cols[0]    
   y=cols[1]
   z=cols[2]
   r=cols[3]
   if m==1:
     sr=r
    
     spherepoints.InsertNextPoint(float(x),float(y), float(z))
   radii.InsertNextValue(float(r))
   if m>1:
     cubepoints.InsertNextPoint(float(x),float(y),float(z))
    
   m+=1  

# Putting the data into cellarray
 
 cubecell=vtk.vtkCellArray()
 cubecell.InsertNextCell(m-1)

 for j in range(0,m-1):
  cubecell.InsertCellPoint(j)
# Getting Points for spherevisualization

 spheredata=vtk.vtkPolyData()
 spheredata.SetPoints(spherepoints)

 vector=vtk.vtkFloatArray() 
 vector.SetNumberOfComponents(3)
 vector.SetNumberOfTuples(m)
 
 pline=vtk.vtkCellArray()
   
 pline.InsertNextCell(1)
 for i in range(0,1):
  pline.InsertCellPoint(i)
 spheredata.SetPolys(pline)
 spheredata.GetPointData().SetVectors(vector)
 

# Cube Rendering from Geometry file

 CubeData = vtk.vtkPolyData()
 CubeData.SetPoints(cubepoints)
 CubeData.GetPointData().SetVectors(vector)
# CubeSource is using as a source of vtkGlyph3D to visualize cube 

 Cube=vtk.vtkCubeSource()
 Cubesurface=vtk.vtkGlyph3D()
 Cubesurface.SetSource(Cube.GetOutput())
 Cubesurface.SetInput(CubeData)

# Data mapping for cube visualization

 CubeMapper = vtk.vtkPolyDataMapper()
 CubeMapper.SetInput(Cubesurface.GetOutput())
 CubeMapper.GlobalImmediateModeRenderingOn()
 CubeActor = vtk.vtkLODActor()
 CubeActor.SetMapper(CubeMapper)
 #CubeActor.GetProperty().SetColor(1, 0, 0)
 CubeActor.GetProperty().SetDiffuseColor(1, 0, 0);
 #CubeActor.GetProperty().SetSpecular(.3);
 #CubeActor.GetProperty().SetSpecularPower(20);
 #CubeActor.GetProperty().SetOpacity(0.5)
 #Sphere Rendering

# Sphere visualization. If you to want chage the radius, resolution, please  do changes in the numeric parameter only. 
 
 spheres=vtk.vtkSphereSource()
 spheres.SetRadius(16.0)
 spheres.SetThetaResolution(32)
 spheres.SetPhiResolution(32)

 Glyph=vtk.vtkGlyph3D()
 Glyph.SetSource(spheres.GetOutput())
 Glyph.SetInput(spheredata)

# Mapping of sphere data and also adding actors for rendering the spheres.Here you can also chnage the color of shere changing the parameters into SetColor. You can put any values and observe changes but (0,0,0) is used for black and (1,1,1) is for white.

 sphereMapper = vtk.vtkPolyDataMapper()
 sphereMapper.SetInput(Glyph.GetOutput())
 sphereMapper.GlobalImmediateModeRenderingOn()
 sphereActor = vtk.vtkLODActor()
 sphereActor.SetMapper(sphereMapper)
 sphereActor.GetProperty().SetColor(1, 0, 1) 

 ren.AddActor(CubeActor)
 ren.AddActor(sphereActor)
Esempio n. 44
0
def symmetrize(inpd):
    """Generate symmetric polydata by reflecting.

    Output polydata has twice as many lines as input.

    """

    # output and temporary objects
    ptids = vtk.vtkIdList()
    points = inpd.GetPoints()
    outpd = vtk.vtkPolyData()
    outlines = vtk.vtkCellArray()
    outpoints = vtk.vtkPoints()
    outpoints.DeepCopy(points)

    # loop over lines
    inpd.GetLines().InitTraversal()
    outlines.InitTraversal()

    # set scalar cell data to 1 for orig, -1 for reflect, for vis
    outcolors = vtk.vtkFloatArray()

    # index into end of point array
    lastidx = outpoints.GetNumberOfPoints()
    print("<filter.py> Input number of points: ", lastidx)

    # loop over all lines, insert line and reflected copy into output pd
    for lidx in range(0, inpd.GetNumberOfLines()):
        # progress
        if verbose:
            if lidx % 100 == 0:
                print("<filter.py> Line:", lidx, "/", inpd.GetNumberOfLines())

        inpd.GetLines().GetNextCell(ptids)

        num_points = ptids.GetNumberOfIds()

        # insert fiber (ptids are same since new points go at the end)
        outlines.InsertNextCell(ptids)
        outcolors.InsertNextTuple1(1)

        # insert reflection into END of point array and into line array
        refptids = vtk.vtkIdList()
        for pidx in range(0, num_points):

            point = points.GetPoint(ptids.GetId(pidx))

            # reflect (RAS -> reflect first value)
            refpoint = (-point[0], point[1], point[2])
            idx = outpoints.InsertNextPoint(refpoint)
            refptids.InsertNextId(idx)

        outlines.InsertNextCell(refptids)
        outcolors.InsertNextTuple1(-1)

    # put data into output polydata
    outpd.SetLines(outlines)
    outpd.SetPoints(outpoints)
    outpd.GetCellData().SetScalars(outcolors)

    return outpd
Esempio n. 45
0
array1.SetNumberOfTuples(10)
for idArray in range(0,10):
  array1.SetTuple3(idArray, idArray+1, idArray+2, idArray+3)

modifiedTable.GetFieldData().AddArray(array1)

array2 = vtk.vtkDoubleArray()
array2.SetName("Array 2")
array2.SetNumberOfComponents(1)
array2.SetNumberOfTuples(10)
for idArray in range(0,10):
  array2.SetTuple1(idArray, idArray+1.5)

modifiedTable.GetFieldData().AddArray(array2)

array3 = vtk.vtkFloatArray()
array3.SetName("Array 3")
array3.SetNumberOfComponents(3)
array3.SetNumberOfTuples(10)
for idArray in range(0,10):
  array3.SetTuple3(idArray, idArray+1.5, idArray+2.5, idArray+3.5)

modifiedTable.GetFieldData().AddArray(array3)

xmlTableWriter = vtk.vtkXMLTableWriter()
xmlTableWriter.SetFileName(file2)
xmlTableWriter.SetDataModeToAppended()
xmlTableWriter.SetInputData(modifiedTable)
xmlTableWriter.Write()

# read the ASCII version
Esempio n. 46
0
def mask(inpd,
         fiber_mask,
         color=None,
         preserve_point_data=False,
         preserve_cell_data=True,
         verbose=True):
    """ Keep lines and their points where fiber_mask == 1.

     Unlike vtkMaskPolyData that samples every nth cell, this function
     uses an actual mask, and also gets rid of points that
     are not used by any cell, reducing the size of the polydata file.

     This code also sets scalar cell data to input color data.  This
     input data is expected to be 1 or 3 components.

     If there is no input cell scalar color data, existing cell
     scalars that we have created (EmbeddingColor, ClusterNumber,
     EmbeddingCoordinate) are looked for and masked as well.

     """

    inpoints = inpd.GetPoints()
    inpointdata = inpd.GetPointData()
    incelldata = inpd.GetCellData()

    # output and temporary objects
    ptids = vtk.vtkIdList()
    outpd = vtk.vtkPolyData()
    outlines = vtk.vtkCellArray()
    outpoints = vtk.vtkPoints()
    outcolors = None
    outpointdata = outpd.GetPointData()
    outcelldata = outpd.GetCellData()
    tensor_names = []

    if color is not None:
        # if input is RGB
        if len(color.shape) == 2:
            if color.shape[1] == 3:
                outcolors = vtk.vtkUnsignedCharArray()
                outcolors.SetNumberOfComponents(3)

        # otherwise output floats as colors
        if outcolors == None:
            outcolors = vtk.vtkFloatArray()

    # check for cell data arrays to keep
    if preserve_cell_data:
        if incelldata.GetNumberOfArrays() > 0:
            cell_data_array_indices = list(
                range(incelldata.GetNumberOfArrays()))
            for idx in cell_data_array_indices:
                array = incelldata.GetArray(idx)
                dtype = array.GetDataType()
                if dtype == 10:
                    out_array = vtk.vtkFloatArray()
                elif dtype == 6:
                    out_array = vtk.vtkIntArray()
                elif dtype == 3:
                    out_array = vtk.vtkUnsignedCharArray()
                else:
                    out_array = vtk.vtkFloatArray()
                out_array.SetNumberOfComponents(array.GetNumberOfComponents())
                out_array.SetName(array.GetName())
                if verbose:
                    print("Cell data array found:", array.GetName(),
                          array.GetNumberOfComponents())
                outcelldata.AddArray(out_array)
                # make sure some scalars are active so rendering works
                #outpd.GetCellData().SetActiveScalars(array.GetName())

            #if inpd.GetCellData().GetArray('ClusterNumber'):
            #    # this will be active unless we have embedding colors
            #    outpd.GetCellData().SetActiveScalars('ClusterNumber')
            #if inpd.GetCellData().GetArray('EmbeddingColor'):
            #    # Note Slicer can't display these cell scalars (all is red)
            #    outpd.GetCellData().SetActiveScalars('EmbeddingColor')

        else:
            preserve_cell_data = False

    # check for point data arrays to keep
    if preserve_point_data:
        if inpointdata.GetNumberOfArrays() > 0:
            point_data_array_indices = list(
                range(inpointdata.GetNumberOfArrays()))
            for idx in point_data_array_indices:
                array = inpointdata.GetArray(idx)
                out_array = vtk.vtkFloatArray()
                out_array.SetNumberOfComponents(array.GetNumberOfComponents())
                out_array.SetName(array.GetName())
                if verbose:
                    print("Point data array found:", array.GetName(),
                          array.GetNumberOfComponents())
                outpointdata.AddArray(out_array)
                # make sure some scalars are active so rendering works
                #outpd.GetPointData().SetActiveScalars(array.GetName())
                # keep track of tensors to choose which is active
                if array.GetNumberOfComponents() == 9:
                    tensor_names.append(array.GetName())
        else:
            preserve_point_data = False

    # Set up scalars and tensors attributes for correct visualization in Slicer.
    # Slicer works with point data and does not handle cell data well.
    # This set of changes breaks old internal wma default visualization of cell scalars.
    # Changes must be propagated through wma so that render is called with the name of the field to visualize.
    # the new way in wma is like this line, below.
    #ren = wma.render.render(output_polydata_s, 1000, data_mode="Cell", data_name='EmbeddingColor')

    # For Slicer: First set one of the expected tensor arrays as default for vis
    tensors_labeled = False
    for name in tensor_names:
        if name == "tensors":
            outpd.GetPointData().SetTensors(
                outpd.GetPointData().GetArray("tensors"))
            tensors_labeled = True
        if name == "Tensors":
            outpd.GetPointData().SetTensors(
                outpd.GetPointData().GetArray("Tensors"))
            tensors_labeled = True
        if name == "tensor1":
            outpd.GetPointData().SetTensors(
                outpd.GetPointData().GetArray("tensor1"))
            tensors_labeled = True
        if name == "Tensor1":
            outpd.GetPointData().SetTensors(
                outpd.GetPointData().GetArray("Tensor1"))
            tensors_labeled = True
    if not tensors_labeled:
        if len(tensor_names) > 0:
            print(
                "Data has unexpected tensor name(s). Unable to set active for visualization:",
                tensor_names)
    # now set cell data visualization inactive.
    outpd.GetCellData().SetActiveScalars(None)

    # loop over lines
    inpd.GetLines().InitTraversal()
    outlines.InitTraversal()

    for lidx in range(0, inpd.GetNumberOfLines()):
        inpd.GetLines().GetNextCell(ptids)

        if fiber_mask[lidx]:

            if verbose:
                if lidx % 100 == 0:
                    print("<filter.py> Line:", lidx, "/",
                          inpd.GetNumberOfLines())

            # get points for each ptid and add to output polydata
            cellptids = vtk.vtkIdList()

            for pidx in range(0, ptids.GetNumberOfIds()):
                point = inpoints.GetPoint(ptids.GetId(pidx))
                idx = outpoints.InsertNextPoint(point)
                cellptids.InsertNextId(idx)
                if preserve_point_data:
                    for idx in point_data_array_indices:
                        array = inpointdata.GetArray(idx)
                        out_array = outpointdata.GetArray(idx)
                        out_array.InsertNextTuple(
                            array.GetTuple(ptids.GetId(pidx)))

            outlines.InsertNextCell(cellptids)

            if color is not None:
                # this code works with either 3 or 1 component only
                if outcolors.GetNumberOfComponents() == 3:
                    outcolors.InsertNextTuple3(color[lidx, 0], color[lidx, 1],
                                               color[lidx, 2])
                else:
                    outcolors.InsertNextTuple1(color[lidx])

            if preserve_cell_data:
                for idx in cell_data_array_indices:
                    array = incelldata.GetArray(idx)
                    out_array = outcelldata.GetArray(idx)
                    out_array.InsertNextTuple(array.GetTuple(lidx))

    # put data into output polydata
    outpd.SetLines(outlines)
    outpd.SetPoints(outpoints)

    # if we had an input color requested during masking, set that to be the default scalar for vis
    if color is not None:
        outpd.GetCellData().SetScalars(outcolors)

    if verbose:
        print("<filter.py> Fibers sampled:", outpd.GetNumberOfLines(), "/",
              inpd.GetNumberOfLines())

    return outpd
    det_corners.InsertNextPoint(det_r0cN[0], det_r0cN[1], det_r0cN[2])

    det_quad = vtkQuad()
    det_quad.GetPointIds().SetId(0, 0)
    det_quad.GetPointIds().SetId(1, 1)
    det_quad.GetPointIds().SetId(2, 2)
    det_quad.GetPointIds().SetId(3, 3)

    quads = vtkCellArray()
    quads.InsertNextCell(det_quad)

    det_poly_data = vtkPolyData()
    det_poly_data.SetPoints(det_corners)
    det_poly_data.SetPolys(quads)

    tex_coords = vtkFloatArray()
    tex_coords.SetNumberOfComponents(2)
    tex_coords.SetName('TextureCoordinates')
    tex_coords.InsertNextTuple([0, 0])
    tex_coords.InsertNextTuple([0, 1])
    tex_coords.InsertNextTuple([1, 1])
    tex_coords.InsertNextTuple([1, 0])

    det_poly_data.GetPointData().SetTCoords(tex_coords)

    tex = vtkTexture()
    tex.SetInputData(proj_vtk_img)

    plane_mapper = vtkPolyDataMapper()
    plane_mapper.SetInputData(det_poly_data)
    plane_mapper.Update()
#http://www.vtk.org/pipermail/vtkusers/2013-February/078465.html

import vtk
from pyNastran.bdf.bdf import (BDF, CQUAD4, CQUAD8, CQUADR, CSHEAR, CTRIA3,
                               CTRIA6, CTRIAR, CTRIAX6, CTETRA4, CTETRA10,
                               CPENTA6, CPENTA15, CHEXA8, CHEXA20, CBUSH,
                               CBEAM, CONM2)

model = BDF()
bdf_file = r'C:\Users\Michael\PycharmProjects\FEMAnalysisTool\fem_post\data\rotor.bdf'
vtk_file = r'C:\Users\Michael\PycharmProjects\FEMAnalysisTool\fem_post\data\rotor.vtk_widget'
model.readBDF(bdf_file, includeDir=None, xref=False)
points = vtk.vtkPoints()
grid = vtk.vtkUnstructuredGrid()
Color = vtk.vtkFloatArray()
CntCONM2 = 0
for (eid, element) in model.elements.iteritems():
    CntCONM2 = CntCONM2 + 1

Scale = vtk.vtkFloatArray()

nidMap = {}
EidMap = {}

i = 0
for (nid, node) in model.nodes.iteritems():
    #node = model.Node(1)
    cp = node.Cp()
    coord = model.Coord(cp)
    pos = coord.transformToGlobal(node.xyz)
    Coord = []
Esempio n. 49
0
def make_patterned_polydata(inputContours,
                            fillareastyle=None,
                            fillareaindex=None,
                            fillareacolors=None,
                            fillareaopacity=None,
                            fillareapixelspacing=None,
                            fillareapixelscale=None,
                            size=None,
                            renderer=None):
    if inputContours is None or fillareastyle == 'solid':
        return None
    if inputContours.GetNumberOfCells() == 0:
        return None
    if fillareaindex is None:
        fillareaindex = 1
    if fillareaopacity is None:
        fillareaopacity = 100
    if fillareapixelspacing is None:
        if size is not None:
            sp = int(0.015 * min(size[0], size[1]))
            fillareapixelspacing = 2 * [sp if sp > 1 else 1]
        else:
            fillareapixelspacing = [15, 15]
    if fillareapixelscale is None:
        fillareapixelscale = 1.0 * min(fillareapixelspacing[0],
                                       fillareapixelspacing[1])

    # Create a point set laid out on a plane that will be glyphed with the
    # pattern / hatch
    # The bounds of the plane match the bounds of the input polydata
    bounds = inputContours.GetBounds()

    patternPolyData = vtk.vtkPolyData()
    patternPts = vtk.vtkPoints()
    patternPolyData.SetPoints(patternPts)

    xBounds = bounds[1] - bounds[0]
    yBounds = bounds[3] - bounds[2]

    xres = yres = 1
    scale = [1.0, 1.0]
    if renderer is not None:
        # Be smart about calculating the resolution by taking the screen pixel
        # size into account
        # First, convert a distance of one unit screen distance to data
        # coordinates
        point1 = [1.0, 1.0, 0.0]
        point2 = [0.0, 0.0, 0.0]
        renderer.SetDisplayPoint(point1)
        renderer.DisplayToWorld()
        wpoint1 = renderer.GetWorldPoint()
        renderer.SetDisplayPoint(point2)
        renderer.DisplayToWorld()
        wpoint2 = renderer.GetWorldPoint()
        diffwpoints = [
            abs(wpoint1[0] - wpoint2[0]),
            abs(wpoint1[1] - wpoint2[1])
        ]
        diffwpoints = [1.0 if i < 1e-6 else i for i in diffwpoints]

        # Choosing an arbitary factor to scale the number of points.  A spacing
        # of 10 pixels and a scale of 7.5 pixels was chosen based on visual
        # inspection of result.  Essentially, it means each glyph is 10 pixels
        # away from its neighbors and 7.5 pixels high and wide.
        xres = int(xBounds / (fillareapixelspacing[0] * diffwpoints[0])) + 1
        yres = int(yBounds / (fillareapixelspacing[1] * diffwpoints[1])) + 1
        scale = [fillareapixelscale * x for x in diffwpoints[:2]]
    else:
        if xBounds <= 1 and yBounds <= 1 and size is not None:
            xBounds *= size[0] / 3
            yBounds *= size[1] / 3

        xres = int(xBounds / 3)
        yres = int(yBounds / 3)

    numPts = (xres + 1) * (yres + 1)
    patternPts.Allocate(numPts)
    normals = vtk.vtkFloatArray()
    normals.SetName("Normals")
    normals.SetNumberOfComponents(3)
    normals.Allocate(3 * numPts)
    tcoords = vtk.vtkFloatArray()
    tcoords.SetName("TextureCoordinates")
    tcoords.SetNumberOfComponents(2)
    tcoords.Allocate(2 * numPts)

    x = [0.0, 0.0, 0.0]
    tc = [0.0, 0.0]
    v1 = [0.0, bounds[3] - bounds[2]]
    v2 = [bounds[1] - bounds[0], 0.0]
    normal = [0.0, 0.0, 1.0]
    numPt = 0
    for i in range(yres + 1):
        tc[0] = i * 1.0 / yres
        for j in range(xres + 1):
            tc[1] = j * 1.0 / xres
            for ii in range(2):
                x[ii] = bounds[2 * ii] + tc[0] * v1[ii] + tc[1] * v2[ii]
            patternPts.InsertPoint(numPt, x)
            tcoords.InsertTuple(numPt, tc)
            normals.InsertTuple(numPt, normal)
            numPt += 1
    patternPolyData.GetPointData().SetNormals(normals)
    patternPolyData.GetPointData().SetTCoords(tcoords)

    # Create the pattern
    create_pattern(patternPolyData, scale, fillareastyle, fillareaindex)

    # Create pipeline to create a clipped polydata from the pattern plane.
    cutter = vtk.vtkCookieCutter()
    cutter.SetInputData(patternPolyData)
    cutter.SetLoopsData(inputContours)
    cutter.Update()

    # Now map the colors as cell scalars.
    # We are doing this here because the vtkCookieCutter does not preserve
    # cell scalars
    map_colors(cutter.GetOutput(), fillareastyle, fillareacolors,
               fillareaopacity)

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(cutter.GetOutputPort())
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    return actor
Esempio n. 50
0
# coordinates
x = linspace(-lx / 2, lx / 2, Nx + 1)
y = linspace(-ly / 2, ly / 2, Ny + 1)
z = linspace(-lz / 2, lz / 2, Nz + 1)

# cell centers
xmid = 0.5 * (x[1:] + x[:-1])
ymid = 0.5 * (y[1:] + y[:-1])
zmid = 0.5 * (z[1:] + z[:-1])

### VTK STUFF ###

import vtk

xpoints = vtk.vtkFloatArray()
ypoints = vtk.vtkFloatArray()
zpoints = vtk.vtkFloatArray()

xpoints.SetNumberOfComponents(1)
ypoints.SetNumberOfComponents(1)
zpoints.SetNumberOfComponents(1)

grid = vtk.vtkRectilinearGrid()

if centered == 'point':
    xpoints.SetNumberOfTuples(Nx)
    for i in xrange(Nx):
        xpoints.SetTuple1(i, xmid[i])

    ypoints.SetNumberOfTuples(Ny)
Esempio n. 51
0
    def testLinePlot(self):
        "Test if colored scatter plots can be built with python"

        # Set up a 2D scene, add an XY chart to it
        view = vtk.vtkContextView()
        view.GetRenderer().SetBackground(1.0, 1.0, 1.0)
        view.GetRenderWindow().SetSize(400, 300)

        chart = vtk.vtkChartXY()
        chart.SetShowLegend(True)
        view.GetScene().AddItem(chart)

        # Create a table with some points in it
        arrX = vtk.vtkFloatArray()
        arrX.SetName("XAxis")

        arrC = vtk.vtkFloatArray()
        arrC.SetName("Cosine")

        arrS = vtk.vtkFloatArray()
        arrS.SetName("Sine")

        arrS2 = vtk.vtkFloatArray()
        arrS2.SetName("Tan")

        numPoints = 40
        inc = 7.5 / (numPoints - 1)

        for i in range(numPoints):
            arrX.InsertNextValue(i * inc)
            arrC.InsertNextValue(math.cos(i * inc) + 0.0)
            arrS.InsertNextValue(math.sin(i * inc) + 0.0)
            arrS2.InsertNextValue(math.tan(i * inc) + 0.5)

        table = vtk.vtkTable()
        table.AddColumn(arrX)
        table.AddColumn(arrC)
        table.AddColumn(arrS)
        table.AddColumn(arrS2)

        # Generate a black-to-red lookup table with fixed alpha
        lut = vtk.vtkLookupTable()
        lut.SetValueRange(0.2, 1.0)
        lut.SetSaturationRange(1, 1)
        lut.SetHueRange(0, 0)
        lut.SetRampToLinear()
        lut.SetRange(-1, 1)
        lut.SetAlpha(0.75)
        lut.Build()

        # Generate a black-to-blue lookup table with alpha range
        lut2 = vtk.vtkLookupTable()
        lut2.SetValueRange(0.2, 1.0)
        lut2.SetSaturationRange(1, 1)
        lut2.SetHueRange(0.6667, 0.6667)
        lut2.SetAlphaRange(0.4, 0.8)
        lut2.SetRampToLinear()
        lut2.SetRange(-1, 1)
        lut2.Build()

        # Add multiple line plots, setting the colors etc
        points0 = chart.AddPlot(vtk.vtkChart.POINTS)
        points0.SetInput(table, 0, 1)
        points0.SetColor(0, 0, 0, 255)
        points0.SetWidth(1.0)
        points0.SetMarkerStyle(vtk.vtkPlotPoints.CROSS)

        points1 = chart.AddPlot(vtk.vtkChart.POINTS)
        points1.SetInput(table, 0, 2)
        points1.SetColor(0, 0, 0, 255)
        points1.SetMarkerStyle(vtk.vtkPlotPoints.DIAMOND)
        points1.SetScalarVisibility(1)
        points1.SetLookupTable(lut)
        points1.SelectColorArray(1)

        points2 = chart.AddPlot(vtk.vtkChart.POINTS)
        points2.SetInput(table, 0, 3)
        points2.SetColor(0, 0, 0, 255)
        points2.ScalarVisibilityOn()
        points2.SetLookupTable(lut2)
        points2.SelectColorArray("Cosine")
        points2.SetWidth(4.0)

        view.GetRenderWindow().SetMultiSamples(0)
        view.GetRenderWindow().Render()

        img_file = "TestScatterPlotColors.png"
        vtk.test.Testing.compareImage(
            view.GetRenderWindow(),
            vtk.test.Testing.getAbsImagePath(img_file),
            threshold=25)
        vtk.test.Testing.interact()
Esempio n. 52
0
def main():
    colors = vtk.vtkNamedColors()

    numTuples = 12

    bitter = vtk.vtkFloatArray()
    bitter.SetNumberOfTuples(numTuples)

    crispy = vtk.vtkFloatArray()
    crispy.SetNumberOfTuples(numTuples)

    crunchy = vtk.vtkFloatArray()
    crunchy.SetNumberOfTuples(numTuples)

    salty = vtk.vtkFloatArray()
    salty.SetNumberOfTuples(numTuples)

    oily = vtk.vtkFloatArray()
    oily.SetNumberOfTuples(numTuples)

    rand_seq = vtk.vtkMinimalStandardRandomSequence()
    rand_seq.SetSeed(1)

    for i in range(numTuples):
        bitter.SetTuple1(i, rand_seq.GetRangeValue(1, 10))
        rand_seq.Next()
        crispy.SetTuple1(i, rand_seq.GetRangeValue(-1, 1))
        rand_seq.Next()
        crunchy.SetTuple1(i, rand_seq.GetRangeValue(1, 100))
        rand_seq.Next()
        salty.SetTuple1(i, rand_seq.GetRangeValue(0, 10))
        rand_seq.Next()
        oily.SetTuple1(i, rand_seq.GetRangeValue(5, 25))
        rand_seq.Next()

    dobj = vtk.vtkDataObject()
    dobj.GetFieldData().AddArray(bitter)
    dobj.GetFieldData().AddArray(crispy)
    dobj.GetFieldData().AddArray(crunchy)
    dobj.GetFieldData().AddArray(salty)
    dobj.GetFieldData().AddArray(oily)

    actor = vtk.vtkSpiderPlotActor()
    actor.SetInputData(dobj)
    actor.SetTitle("Spider Plot")
    actor.SetIndependentVariablesToColumns()
    actor.GetPositionCoordinate().SetValue(0.05, 0.1, 0.0)
    actor.GetPosition2Coordinate().SetValue(0.95, 0.85, 0.0)
    actor.GetProperty().SetColor(colors.GetColor3d('Bisque'))

    actor.SetAxisLabel(0, "Bitter")
    actor.SetAxisRange(0, 1, 10)

    actor.SetAxisLabel(1, "Crispy")
    actor.SetAxisRange(1, -1, 1)

    actor.SetAxisLabel(2, "Crunchy")
    actor.SetAxisRange(2, 1, 100)

    actor.SetAxisLabel(3, "Salty")
    actor.SetAxisRange(3, 0, 10)

    actor.SetAxisLabel(4, "Oily")
    actor.SetAxisRange(4, 5, 25)
    actor.GetLegendActor().SetNumberOfEntries(numTuples)

    for i in range(numTuples):
        r = rand_seq.GetValue()
        rand_seq.Next()
        g = rand_seq.GetValue()
        rand_seq.Next()
        b = rand_seq.GetValue()
        rand_seq.Next()
        actor.SetPlotColor(i, r, g, b)

    actor.LegendVisibilityOn()

    actor.GetTitleTextProperty().SetColor(colors.GetColor3d('Yellow'))
    actor.GetLabelTextProperty().SetColor(colors.GetColor3d('OrangeRed'))

    ren1 = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren1)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    ren1.AddActor(actor)
    ren1.SetBackground(colors.GetColor3d('Black'))
    renWin.SetSize(800, 800)

    iren.Initialize()
    renWin.Render()
    iren.Start()
Esempio n. 53
0
    list_read_proc.extend(range(Z,Nprocs,ZLEN))

list_read_proc=scipy.array(list_read_proc)
zread_proc=len(list_read_proc)/(YLEN*XLEN) #Number of proc file you want to read in the z direction


Nzlocal=zread_proc*(shape[2]-1)+1
Fields_local = scipy.zeros((6,Nxc+1,Nyc+1,Nzlocal),dtype="float32")
# 6 for 6 components of the field
numproc=min(numproc,ZLEN) # To account for specific case where more processors are used here than in the Z direction of the simulation
if len(list_read_proc) > 0:
    numpoints = (Nxc+1)*(Nyc+1)*Nzlocal
    Xcoordinates = scipy.arange(Nxc+1).flatten().astype('float32')*dx
    Ycoordinates = scipy.arange(Nyc+1).flatten().astype('float32')*dy
    Zcoordinates = (scipy.arange(Nzlocal).flatten().astype('float32')+list_read_proc[0]*(shape[2]-1))*dz
    vtkXcoordinates = vtk.vtkFloatArray()
    vtkXcoordinates.SetNumberOfComponents(1)
    vtkXcoordinates.SetNumberOfTuples(Nxc+1)
    vtkXcoordinates.SetVoidArray(Xcoordinates,Nxc+1,1)
    vtkYcoordinates = vtk.vtkFloatArray()
    vtkYcoordinates.SetNumberOfComponents(1)
    vtkYcoordinates.SetNumberOfTuples(Nyc+1)
    vtkYcoordinates.SetVoidArray(Ycoordinates,Nyc+1,1)
    vtkZcoordinates = vtk.vtkFloatArray()
    vtkZcoordinates.SetNumberOfComponents(1)
    vtkZcoordinates.SetNumberOfTuples(Nzlocal)
    vtkZcoordinates.SetVoidArray(Zcoordinates,Nzlocal,1)

    ###########################################################################################
    ##                       FIELDS                                                         ##
    ###########################################################################################
Esempio n. 54
0
"""
vtk_cell_array = vtk.vtkCellArray()
vtk_cell_array.InsertNextCell(npts)
for i in range(npts):
    vtk_cell_array.InsertCellPoint(i)
"""
vtk.vtkFLoatArray(): A set of values associated with the initial
points, be it force magnitudes at the point or bending moments, can be
captured as a scalar array of floating point values with the
vtkFloatArray object. this is done by first declaring the number of
scalars with the vtk_float_array.SetNumberOfValues(npts) method and then
enumerating through the points and using the
vtk_float_array.SetValue(i, value) method.
"""
value = lambda i: math.fabs(math.sin(math.pi * i / 30.))
vtk_float_array = vtk.vtkFloatArray()
vtk_float_array.SetNumberOfValues(npts)
for i in range(npts):
    vtk_float_array.SetValue(i, value(i))
"""
vtk.vtkPolyData(): The point connectivity and scalar values can be
encapsulated in the vtkPolyData object this is done by using the,
vtk_poly_data.SetPoints(vtk_points), vtk_poly_data.SetLines(vtk_cell_array) and
vtk_poly_data.GetPointData().SetScalars(vtkFLoatArray) methods
"""
vtk_poly_data = vtk.vtkPolyData()
vtk_poly_data.SetPoints(vtk_points)
vtk_poly_data.SetLines(vtk_cell_array)
vtk_poly_data.GetPointData().SetScalars(vtk_float_array)
"""
vtk.vtkSplineFilter(): The data can be smoothly interpolated across a
def extract_slice_thickness_LVonly(nsubdivision, domain, verbose=True):

    refinedmesh = vtk.vtkLoopSubdivisionFilter()
    refinedmesh.SetNumberOfSubdivisions(nsubdivision)
    refinedmesh.SetInput(domain)
    refinedmesh.Update()

    bds = domain.GetBounds()
    ctr = [0, 0, 0]
    ctr[0] = 0.5 * (bds[0] + bds[1])
    ctr[1] = 0.5 * (bds[2] + bds[3])
    ctr[2] = 0.5 * (bds[4] + bds[5])

    featureEdges = vtk.vtkFeatureEdges()
    featureEdges.SetInput(refinedmesh.GetOutput())
    featureEdges.BoundaryEdgesOn()
    featureEdges.FeatureEdgesOff()
    featureEdges.ManifoldEdgesOff()
    featureEdges.NonManifoldEdgesOff()
    featureEdges.Update()

    connectfilter = vtk.vtkPolyDataConnectivityFilter()
    connectfilter.SetInput(featureEdges.GetOutput())
    connectfilter.SetExtractionModeToSpecifiedRegions()
    connectfilter.Update()

    epi = vtk.vtkPolyData()
    LVendo = vtk.vtkPolyData()

    connectfilter.SetExtractionModeToClosestPointRegion()
    connectfilter.SetClosestPoint(ctr[0], ctr[1] + 1000, ctr[2] + 1000)
    connectfilter.Update()
    epi.DeepCopy(connectfilter.GetOutput())
    epi = clean_pdata(epi)

    connectfilter.SetClosestPoint(ctr[0], ctr[1], ctr[2])
    connectfilter.Update()
    LVendo.DeepCopy(connectfilter.GetOutput())
    LVendo = clean_pdata(LVendo)

    epipointlocator = vtk.vtkPointLocator()
    epipointlocator.SetDataSet(epi)
    epipointlocator.BuildLocator()

    LVendopointlocator = vtk.vtkPointLocator()
    LVendopointlocator.SetDataSet(LVendo)
    LVendopointlocator.BuildLocator()

    epidistance = vtk.vtkFloatArray()
    epidistance.SetName("Thickness")

    for p in range(0, epi.GetNumberOfPoints()):
        pt = epi.GetPoints().GetPoint(p)

        LVendoid = LVendopointlocator.FindClosestPoint(pt)
        LVendopt = LVendo.GetPoints().GetPoint(LVendoid)

        disttoLVendo = math.sqrt(
            vtk.vtkMath.Distance2BetweenPoints(pt, LVendopt))

        epidistance.InsertNextValue(disttoLVendo)

    epi.GetPointData().SetActiveScalars("Thickness")
    epi.GetPointData().SetScalars(epidistance)

    return epi
Esempio n. 56
0
def anisotropic_smooth(inpd,
                       fiber_distance_threshold,
                       points_per_fiber=30,
                       n_jobs=2,
                       cluster_max=10):
    """ Average nearby fibers.
    
    The pairwise fiber distance matrix is computed, then fibers
    are averaged with their neighbors until an edge (>max_fiber_distance) is encountered.

    """

    # polydata to array conversion, fixed-length fiber representation
    current_fiber_array = fibers.FiberArray()
    current_fiber_array.points_per_fiber = points_per_fiber
    current_fiber_array.convert_from_polydata(inpd)
    original_number_of_fibers = current_fiber_array.number_of_fibers

    # fiber list data structure initialization for easy fiber averaging
    curr_count = list()
    curr_fibers = list()
    curr_indices = list()
    for lidx in range(0, current_fiber_array.number_of_fibers):
        curr_fibers.append(current_fiber_array.get_fiber(lidx))
        curr_count.append(1)
        curr_indices.append(list([lidx]))

    converged = False
    iteration_count = 0

    while not converged:
        print("<filter.py> ITERATION:", iteration_count, "SUM FIBER COUNTS:",
              numpy.sum(numpy.array(curr_count)))
        print("<filter.py> number indices", len(curr_indices))

        # fiber data structures for output of this iteration
        next_fibers = list()
        next_count = list()
        next_indices = list()

        # information for this iteration
        done = numpy.zeros(current_fiber_array.number_of_fibers)
        fiber_indices = list(range(0, current_fiber_array.number_of_fibers))

        # if the maximum number of fibers have been combined, stop averaging this fiber
        done[numpy.nonzero(numpy.array(curr_count) >= cluster_max)] = 1

        # pairwise distance matrix
        if USE_PARALLEL:
            distances = Parallel(n_jobs=n_jobs,
                                 verbose=1)(delayed(similarity.fiber_distance)(
                                     current_fiber_array.get_fiber(lidx),
                                     current_fiber_array, 0, 'Hausdorff')
                                            for lidx in fiber_indices)
            distances = numpy.array(distances)
        else:
            distances = \
                numpy.zeros(
                (current_fiber_array.number_of_fibers,
                 current_fiber_array.number_of_fibers))
            for lidx in fiber_indices:
                distances[lidx, :] = \
                    similarity.fiber_distance(
                        current_fiber_array.get_fiber(lidx),
                        current_fiber_array, 0, 'Hausdorff')

        # distances to self are not of interest
        for lidx in fiber_indices:
            distances[lidx, lidx] = numpy.inf

        # sort the pairwise distances.
        distances_flat = distances.flatten()
        pair_order = numpy.argsort(distances_flat)

        print("<filter.py> DISTANCE MIN:", distances_flat[pair_order[0]], \
            "DISTANCE COUNT:", distances.shape)

        # if the smallest distance is greater or equal to the
        # threshold, we have converged
        if distances_flat[pair_order[0]] >= fiber_distance_threshold:
            converged = True
            print("<filter.py> CONVERGED")
            break
        else:
            print("<filter.py> NOT CONVERGED")

        # loop variables
        idx = 0
        pair_idx = pair_order[idx]
        number_of_fibers = distances.shape[0]
        number_averages = 0

        # combine nearest neighbors unless done, until hit threshold
        while distances_flat[pair_idx] < fiber_distance_threshold:
            # find the fiber indices corresponding to this pairwise distance
            # use div and mod
            f_row = pair_idx / number_of_fibers
            f_col = pair_idx % number_of_fibers

            # check if this neighbor pair can be combined
            combine = (not done[f_row]) and (not done[f_col])
            if combine:
                done[f_row] += 1
                done[f_col] += 1
                # weighted average of the fibers (depending on how many each one represents)
                next_fibers.append(
                    (curr_fibers[f_row] * curr_count[f_row] + \
                     curr_fibers[f_col] *curr_count[f_col]) / \
                    (curr_count[f_row] + curr_count[f_col]))
                # this was the regular average
                #next_fibers.append((curr_fibers[f_row] + curr_fibers[f_col])/2)
                next_count.append(curr_count[f_row] + curr_count[f_col])
                number_averages += 1
                #next_indices.append(list([curr_indices[f_row], curr_indices[f_col]]))
                next_indices.append(
                    list(curr_indices[f_row] + curr_indices[f_col]))

            # increment for the loop
            idx += 1
            pair_idx = pair_order[idx]

        # copy through any unvisited (already converged) fibers
        unvisited = numpy.nonzero(done == 0)[0]
        for fidx in unvisited:
            next_fibers.append(curr_fibers[fidx])
            next_count.append(curr_count[fidx])
            next_indices.append(curr_indices[fidx])

        # set up for next iteration
        curr_fibers = next_fibers
        curr_count = next_count
        curr_indices = next_indices
        iteration_count += 1

        # set up array for next iteration distance computation
        current_fiber_array = fibers.FiberArray()
        current_fiber_array.number_of_fibers = len(curr_fibers)
        current_fiber_array.points_per_fiber = points_per_fiber
        dims = [
            current_fiber_array.number_of_fibers,
            current_fiber_array.points_per_fiber
        ]
        # fiber data
        current_fiber_array.fiber_array_r = numpy.zeros(dims)
        current_fiber_array.fiber_array_a = numpy.zeros(dims)
        current_fiber_array.fiber_array_s = numpy.zeros(dims)
        curr_fidx = 0
        for curr_fib in curr_fibers:
            current_fiber_array.fiber_array_r[curr_fidx] = curr_fib.r
            current_fiber_array.fiber_array_a[curr_fidx] = curr_fib.a
            current_fiber_array.fiber_array_s[curr_fidx] = curr_fib.s
            curr_fidx += 1

        print("<filter.py> SUM FIBER COUNTS:",
              numpy.sum(numpy.array(curr_count)), "SUM DONE FIBERS:",
              numpy.sum(done))
        print("<filter.py> MAX COUNT:", numpy.max(numpy.array(curr_count)),
              "AVGS THIS ITER:", number_averages)

    # when converged, convert output to polydata
    outpd = current_fiber_array.convert_to_polydata()

    # color output by the number of fibers that each output fiber corresponds to
    outcolors = vtk.vtkFloatArray()
    outcolors.SetName('FiberTotal')
    for count in curr_count:
        outcolors.InsertNextTuple1(count)
    outpd.GetCellData().SetScalars(outcolors)

    # also color the input pd by output cluster number
    cluster_numbers = numpy.zeros(original_number_of_fibers)
    cluster_count = numpy.zeros(original_number_of_fibers)
    cluster_idx = 0
    for index_list in curr_indices:
        indices = numpy.array(index_list).astype(int)
        cluster_numbers[indices] = cluster_idx
        cluster_count[indices] = curr_count[cluster_idx]
        cluster_idx += 1
    outclusters = vtk.vtkFloatArray()
    outclusters.SetName('ClusterNumber')
    for cluster in cluster_numbers:
        outclusters.InsertNextTuple1(cluster)
    inpd.GetCellData().AddArray(outclusters)
    inpd.GetCellData().SetActiveScalars('ClusterNumber')

    return outpd, numpy.array(curr_count), inpd, cluster_numbers, cluster_count
Esempio n. 57
0
def spheres(centers,
            r=1,
            c='r',
            alpha=1,
            wire=False,
            legend=None,
            texture=None,
            res=8):
    '''
    Build a (possibly large) set of spheres at `centers` of radius `r`.

    Either `c` or `r` can be a list of RGB colors or radii.

    .. hint:: Example: `manyspheres.py <https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/manyspheres.py>`_
    
        .. image:: https://user-images.githubusercontent.com/32848391/46818673-1f566b80-cd82-11e8-9a61-be6a56160f1c.png
    '''

    cisseq = False
    if utils.isSequence(c):
        cisseq = True

    if cisseq:
        if len(centers) > len(c):
            colors.printc("Mismatch in spheres() colors",
                          len(centers),
                          len(c),
                          c=1)
            exit()
        if len(centers) != len(c):
            colors.printc("Warning: mismatch in spheres() colors",
                          len(centers), len(c))

    risseq = False
    if utils.isSequence(r):
        risseq = True

    if risseq:
        if len(centers) > len(r):
            colors.printc("Mismatch in spheres() radius",
                          len(centers),
                          len(r),
                          c=1)
            exit()
        if len(centers) != len(r):
            colors.printc("Warning: mismatch in spheres() radius",
                          len(centers), len(r))
    if cisseq and risseq:
        colors.printc("Limitation: c and r cannot be both sequences.", c=1)
        exit()

    src = vtk.vtkSphereSource()
    if not risseq:
        src.SetRadius(r)
    src.SetPhiResolution(res)
    src.SetThetaResolution(2 * res)
    src.Update()
    glyph = vtk.vtkGlyph3D()
    glyph.SetSourceConnection(src.GetOutputPort())

    psrc = vtk.vtkPointSource()
    psrc.SetNumberOfPoints(len(centers))
    psrc.Update()
    pd = psrc.GetOutput()
    vpts = pd.GetPoints()

    if cisseq:
        glyph.SetColorModeToColorByScalar()
        ucols = vtk.vtkUnsignedCharArray()
        ucols.SetNumberOfComponents(3)
        ucols.SetName("colors")
        for i, p in enumerate(centers):
            vpts.SetPoint(i, p)
            cc = np.array(colors.getColor(c[i])) * 255
            ucols.InsertNextTuple3(cc[0], cc[1], cc[2])
            pd.GetPointData().SetScalars(ucols)
            glyph.ScalingOff()
    elif risseq:
        glyph.SetScaleModeToScaleByScalar()
        urads = vtk.vtkFloatArray()
        urads.SetName("scales")
        for i, p in enumerate(centers):
            vpts.SetPoint(i, p)
            urads.InsertNextValue(r[i])
        pd.GetPointData().SetScalars(urads)
    else:
        for i, p in enumerate(centers):
            vpts.SetPoint(i, p)

    glyph.SetInputData(pd)
    glyph.Update()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(glyph.GetOutput())
    if cisseq:
        mapper.ScalarVisibilityOn()
    else:
        mapper.ScalarVisibilityOff()
    actor = Actor()  #vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetInterpolationToPhong()
    # check if color string contains a float, in this case ignore alpha
    al = colors._getAlpha(c)
    if al:
        alpha = al
    actor.GetProperty().SetOpacity(alpha)
    if not cisseq:
        if texture is not None:
            actor.texture(texture)
            mapper.ScalarVisibilityOff()
        else:
            actor.GetProperty().SetColor(colors.getColor(c))
    return actor
Esempio n. 58
0
    def testImagePlaneWidget(self):
        "A more rigorous test using the image plane widget."
        # This test is largely copied from
        # Widgets/Python/TestImagePlaneWidget.py

        # Load some data.
        v16 = vtk.vtkVolume16Reader()
        v16.SetDataDimensions(64, 64)
        v16.SetDataByteOrderToLittleEndian()
        v16.SetFilePrefix(os.path.join(VTK_DATA_ROOT,
                                       "Data", "headsq", "quarter"))
        v16.SetImageRange(1, 93)
        v16.SetDataSpacing(3.2, 3.2, 1.5)
        v16.Update()

        xMin, xMax, yMin, yMax, zMin, zMax = v16.GetExecutive().GetWholeExtent(v16.GetOutputInformation(0))
        img_data = v16.GetOutput()
        spacing = img_data.GetSpacing()
        sx, sy, sz = spacing

        origin = img_data.GetOrigin()
        ox, oy, oz = origin

        # An outline is shown for context.
        outline = vtk.vtkOutlineFilter()
        outline.SetInputData(img_data)

        outlineMapper = vtk.vtkPolyDataMapper()
        outlineMapper.SetInputConnection(outline.GetOutputPort())

        outlineActor = vtk.vtkActor()
        outlineActor.SetMapper(outlineMapper)

        # 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.SetInputData(img_data)
        planeWidgetX.SetPlaneOrientationToXAxes()
        planeWidgetX.SetSliceIndex(32)
        planeWidgetX.SetPicker(picker)
        planeWidgetX.SetKeyPressActivationValue("x")
        prop1 = planeWidgetX.GetPlaneProperty()
        prop1.SetColor(1, 0, 0)

        planeWidgetY = vtk.vtkImagePlaneWidget()
        planeWidgetY.DisplayTextOn()
        planeWidgetY.SetInputData(img_data)
        planeWidgetY.SetPlaneOrientationToYAxes()
        planeWidgetY.SetSliceIndex(32)
        planeWidgetY.SetPicker(picker)
        planeWidgetY.SetKeyPressActivationValue("y")
        prop2 = planeWidgetY.GetPlaneProperty()
        prop2.SetColor(1, 1, 0)
        planeWidgetY.SetLookupTable(planeWidgetX.GetLookupTable())

        # 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.DisplayTextOn()
        planeWidgetZ.SetInputData(img_data)
        planeWidgetZ.SetPlaneOrientationToZAxes()
        planeWidgetZ.SetSliceIndex(46)
        planeWidgetZ.SetPicker(picker)
        planeWidgetZ.SetKeyPressActivationValue("z")
        prop3 = planeWidgetZ.GetPlaneProperty()
        prop3.SetColor(0, 0, 1)
        planeWidgetZ.SetLookupTable(planeWidgetX.GetLookupTable())

        # Now create another actor with an opacity < 1 and with some
        # scalars.
        p = vtk.vtkPolyData()
        pts = vtk.vtkPoints()
        pts.InsertNextPoint((0,0,0))
        sc = vtk.vtkFloatArray()
        sc.InsertNextValue(1.0)
        p.SetPoints(pts)
        p.GetPointData().SetScalars(sc)
        m = vtk.vtkPolyDataMapper()
        m.SetInputData(p)
        # Share the lookup table of the widgets.
        m.SetLookupTable(planeWidgetX.GetLookupTable())
        m.UseLookupTableScalarRangeOn()
        dummyActor = vtk.vtkActor()
        dummyActor.SetMapper(m)
        dummyActor.GetProperty().SetOpacity(0.0)

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

        # Add the dummy actor.
        ren.AddActor(dummyActor)
        # Add the outline actor to the renderer, set the background
        # color and size
        ren.AddActor(outlineActor)
        renWin.SetSize(600, 600)
        ren.SetBackground(0.1, 0.1, 0.2)

        current_widget = planeWidgetZ
        mode_widget = planeWidgetZ

        # Set the interactor for the widgets
        iact = vtk.vtkRenderWindowInteractor()
        iact.SetRenderWindow(renWin)
        planeWidgetX.SetInteractor(iact)
        planeWidgetX.On()
        planeWidgetY.SetInteractor(iact)
        planeWidgetY.On()
        planeWidgetZ.SetInteractor(iact)
        planeWidgetZ.On()

        # Create an initial interesting view
        ren.ResetCamera();
        cam1 = ren.GetActiveCamera()
        cam1.Elevation(110)
        cam1.SetViewUp(0, 0, -1)
        cam1.Azimuth(45)
        ren.ResetCameraClippingRange()

        iact.Initialize()
        renWin.Render()
est_time_list_i = []
est_rad_pt_list_i = []

regression_output_folder_path = '/media/shong/IntHard1/4DAnalysis/IPMI2019/GeodesicRegressionResults/CMRep_Abstract_CTRL_Group_LC_NewCode_Linearized/'

for n in range(nTimePt):
    outFileName = 'CMRep_Abstract_Regression_CTRL_LC_' + str(n) + '.vtk'

    output_path = regression_output_folder_path + outFileName

    time_pt = (tN - t0) * n / (nTimePt - 1) + t0

    polyData_t = vtk.vtkPolyData()
    polyData_t.DeepCopy(meanPolyData)

    radiusArr_t_vtk = vtk.vtkFloatArray()
    radiusArr_t_vtk.SetNumberOfValues(polyData_t.GetNumberOfPoints())
    radiusArr_t_vtk.SetName('Radius')

    R2_posArr_t_vtk = vtk.vtkFloatArray()
    R2_posArr_t_vtk.SetNumberOfValues(polyData_t.GetNumberOfPoints())
    R2_posArr_t_vtk.SetName('R2_pos')

    R2_radArr_t_vtk = vtk.vtkFloatArray()
    R2_radArr_t_vtk.SetNumberOfValues(polyData_t.GetNumberOfPoints())
    R2_radArr_t_vtk.SetName('R2_rad')

    RMSE_posArr_t_vtk = vtk.vtkFloatArray()
    RMSE_posArr_t_vtk.SetNumberOfValues(polyData_t.GetNumberOfPoints())
    RMSE_posArr_t_vtk.SetName('RMSE_pos')
Esempio n. 60
-1
    def __init__(self, volume, level=None):
        self._surface_algorithm = None
        self._renderer = None
        self._actor = None
        self._mapper = None
        self._volume_array = None

        self._float_array = _vtk.vtkFloatArray()
        self._image_data = _vtk.vtkImageData()
        self._image_data.GetPointData().SetScalars(self._float_array)
        self._setup_data(_numpy.float32(volume))

        self._surface_algorithm = _vtk.vtkMarchingCubes()
        self._surface_algorithm.SetInputData(self._image_data)
        self._surface_algorithm.ComputeNormalsOn()

        if level is not None:
            try:
                self.set_multiple_levels(iter(level))
            except TypeError:
                self.set_level(0, level)

        self._mapper = _vtk.vtkPolyDataMapper()
        self._mapper.SetInputConnection(self._surface_algorithm.GetOutputPort())
        self._mapper.ScalarVisibilityOn() # new
        self._actor = _vtk.vtkActor()
        self._actor.SetMapper(self._mapper)