Exemplo n.º 1
0
def RMS(sourceSurfaceFile, targetSurfaceFile, VTKobj=False):
    # Reading surfaces
    if not VTKobj:
        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(sourceSurfaceFile)
        reader.Update()
        sourceSurface = reader.GetOutput()

        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(targetSurfaceFile)
        reader.Update()
        targetSurface = reader.GetOutput()
    else:
        sourceSurface = sourceSurfaceFile
        targetSurface = targetSurfaceFile

    cellLocator = vtk.vtkCellLocator()
    cellLocator.SetDataSet(targetSurface)
    cellLocator.BuildLocator()
    sourcePoints = vtk_to_numpy(sourceSurface.GetPoints().GetData())
    distances = np.zeros([np.size(sourcePoints, 0), 1])
    idx = 0
    for point in sourcePoints:
        closestPoint = [0, 0, 0]
        closestPointDist2 = vtk.reference(np.float64())
        cellId = vtk.reference(1)
        subId = vtk.reference(1)
        cellLocator.FindClosestPoint(point, closestPoint, cellId, subId,
                                     closestPointDist2)
        distances[idx] = closestPointDist2
        idx += 1

    RMS = np.sqrt((distances).mean())
    return RMS
def addMappingFromPointsToCells(ugrid_points, ugrid_cells, verbose=True):

    if (verbose): print '*** addMappingFromPointsToCells ***'

    nb_points = ugrid_points.GetNumberOfPoints()
    nb_cells = ugrid_cells.GetNumberOfCells()
    print "nb_points = " + str(nb_points)
    print "nb_cells = " + str(nb_cells)

    cell_locator = vtk.vtkCellLocator()
    cell_locator.SetDataSet(ugrid_cells)
    cell_locator.Update()

    closest_point = [0.] * 3
    generic_cell = vtk.vtkGenericCell()
    num_cell = vtk.mutable(0)
    subId = vtk.mutable(0)
    dist = vtk.mutable(0.)

    iarray_num_cell = createIntArray("num_cell", 1, nb_points)

    for num_point in range(nb_points):
        point = ugrid_points.GetPoint(num_point)

        cell_locator.FindClosestPoint(point, closest_point, generic_cell,
                                      num_cell, subId, dist)
        #num_cell = cell_locator.FindCell(point)

        iarray_num_cell.InsertTuple(num_point, [num_cell])
        #print "num_point = " + str(num_point)
        #print "num_cell = " + str(num_cell)

    ugrid_points.GetPointData().AddArray(iarray_num_cell)
Exemplo n.º 3
0
    def search_callback(self, xyz):
        ide = -1

        if self.data1.get('fielddomain') == 'cell':

            # no existe el método FindCell !!!
            #tol2 = 1
            #subId = 0
            #pcoords = [0.0, 0.0, 0.0]
            #weights = [0.0, 0.0, 0.0]
            #print 'cell', self.src.GetOutput().FindCell(pos, None, -1, tol2, subId, pcoords, weights)

            if self.locator is None:
                self.locator = vtk.vtkCellLocator()
                self.locator.SetDataSet(self.src.GetOutput())

            # no existe el método FindCell !!!
            ide = self.locator.FindCell(xyz)

        else:

            ide = self.src.GetOutput().FindPoint(xyz)

        self.picked(ide)

        if ide < 0:
            self.window.errormsg('Could not locate ' +
                                 self.data1.get('fielddomain') +
                                 ' at given coordinates')
Exemplo n.º 4
0
    def getIntersections(self, grida, gridb):

        cellBToCellAList = {}
        cellLocator = vtk.vtkCellLocator()
        cellLocator.SetDataSet(grida)
        cellLocator.BuildLocator()
        ptIds = vtk.vtkIdList()
        p0 = numpy.zeros((3, ), numpy.float64)
        p1 = numpy.zeros((3, ), numpy.float64)
        cellAList = vtk.vtkIdList()
        # iterate over the gridb cells
        for iCellB in range(gridb.GetNumberOfCells()):
            cellb = gridb.GetCell(iCellB)
            # iterate over the edges of this cell
            for iEdgeb in range(cellb.GetNumberOfEdges()):
                edge = cellb.GetEdge(iEdgeb)
                # find the intersection of this edge with grida
                pts = edge.GetPoints()
                p0[:] = pts.GetPoint(0)
                p1[:] = pts.GetPoint(1)
                #print('start/end points: {} {}'.format(p0, p1))
                cellLocator.FindCellsAlongLine(p0, p1, self.TOL, cellAList)
                numCells = cellAList.GetNumberOfIds()
                if numCells > 0 and iCellB not in cellBToCellAList:
                    cellBToCellAList[iCellB] = set()
                for i in range(numCells):
                    #print('numCells = {} i = {} adding cell {}'.format(numCells, i, cellAList.GetId(i)))
                    cellBToCellAList[iCellB].add(cellAList.GetId(i))
        return cellBToCellAList
Exemplo n.º 5
0
    def get_cell_locator(self):
        '''
        Get a vtkCellLocator object used for ray casting.

        Returns:

            vtk.vtkCellLocator : VTK cell locator.
        '''

        # Don't return anything if we have no enabled geometry
        if len(self.get_enabled_features()) == 0:
            return None

        if self.cell_locator is None:

            appender = vtk.vtkAppendPolyData()

            for fname in self.get_enabled_features():
                appender.AddInputData(self.features[fname].get_polydata())

            appender.Update()

            self.cell_locator = vtk.vtkCellLocator()
            self.cell_locator.SetTolerance(1e-6)
            self.cell_locator.SetDataSet(appender.GetOutput())
            self.cell_locator.BuildLocator()

        return self.cell_locator
Exemplo n.º 6
0
 def __init__(self, points, val, vtkMesh):
     self.points = points
     self.val = val
     self.j = 0
     self.locator = vtk.vtkCellLocator()
     self.locator.SetDataSet(vtkMesh)
     self.locator.BuildLocator()
Exemplo n.º 7
0
def surface2surfacedistance(ref, target, arrayname):
    """Compute distance between two surfaces. Output is added as point array."""
    # adapted from vtkvmtkSurfaceDistance
    # initialise
    locator = vtk.vtkCellLocator()
    genericcell = vtk.vtkGenericCell()
    cellid = vtk.mutable(0)
    point = [0., 0., 0.]
    closestpoint = [0., 0., 0.]
    subid = vtk.mutable(0)
    distance2 = vtk.mutable(0)

    # create array
    distarray = vtk.vtkDoubleArray()
    distarray.SetName(arrayname)
    distarray.SetNumberOfTuples(target.GetNumberOfPoints())
    target.GetPointData().AddArray(distarray)

    # build locator
    locator.SetDataSet(ref)
    locator.BuildLocator()

    # compute distance
    for i in range(target.GetNumberOfPoints()):
        point = target.GetPoint(i)
        locator.FindClosestPoint(point, closestpoint, genericcell, cellid,
                                 subid, distance2)
        distance = math.sqrt(distance2)
        # add value to array
        distarray.SetValue(i, distance)

    target.Update()
    return target
Exemplo n.º 8
0
    def get_external_surface(self):
        print('getting external surface')
        _center = np.zeros(3)
        _bounds = np.zeros(6)
        _ray_start = np.zeros(3)
        cell_id = vtk.mutable(-1)
        xyz = np.zeros(3)
        pcoords = np.zeros(3)
        t = vtk.mutable(0)
        sub_id = vtk.mutable(0)
        _surf = 1.1

        self.mesh.GetOutput().GetCenter(_center)
        self.mesh.GetOutput().GetPoints().GetBounds(_bounds)
        for j in range(3):
            _ray_start[j] = _bounds[2 * j + 1] * _surf

        cell_locator = vtk.vtkCellLocator()
        cell_locator.SetDataSet(self.mesh.GetOutput())
        cell_locator.BuildLocator()
        cell_locator.IntersectWithLine(_ray_start, _center, 0.0001, t, xyz,
                                       pcoords, sub_id, cell_id)

        connectivity_filter = vtk.vtkConnectivityFilter()
        connectivity_filter.SetInputConnection(self.mesh.GetOutputPort())
        connectivity_filter.SetExtractionModeToCellSeededRegions()
        connectivity_filter.InitializeSeedList()
        connectivity_filter.AddSeed(cell_id)
        connectivity_filter.Update()
        self.mesh = connectivity_filter  # UnstructuredGrid
Exemplo n.º 9
0
    def get_external_surface(_mesh, external=True):
        _center = np.zeros(3)
        _bounds = np.zeros(6)
        _ray_start = np.zeros(3)
        cell_id = vtk.mutable(-1)
        xyz = np.zeros(3)
        pcoords = np.zeros(3)
        t = vtk.mutable(0)
        sub_id = vtk.mutable(0)
        if external:
            surf = 1.1
        else:
            surf = -1.1

        _mesh.GetOutput().GetCenter(_center)
        _mesh.GetOutput().GetPoints().GetBounds(_bounds)
        for j in range(3):
            _ray_start[j] = _bounds[2 * j + 1] * surf

        cell_locator = vtk.vtkCellLocator()
        cell_locator.SetDataSet(_mesh.GetOutput())
        cell_locator.BuildLocator()
        cell_locator.IntersectWithLine(_ray_start, _center, 0.0001, t, xyz,
                                       pcoords, sub_id, cell_id)
        print('ID of the cell on the outer surface: {}'.format(cell_id))

        connectivity_filter = vtk.vtkConnectivityFilter()
        connectivity_filter.SetInputConnection(_mesh.GetOutputPort())
        connectivity_filter.SetExtractionModeToCellSeededRegions()
        connectivity_filter.InitializeSeedList()
        connectivity_filter.AddSeed(cell_id)
        connectivity_filter.Update()
        return connectivity_filter
Exemplo n.º 10
0
def alignPolyToReferencePoly(poly, polyRef):
    '''
    For each point in poly, locate closest in reference poly and write new poly
    -- Find Closest Point non disponible en Python
    '''
    from math import sqrt

    # cell locator
    cellLocator = vtk.vtkCellLocator()
    cellLocator.SetDataSet(polyRef)
    cellLocator.BuildLocator()

    #
    clospoint = [0, 0, 0]

    poi = poly.GetPoints()
    #vtkPoints
    polys = poly.GetPolys()
    #vtkCellArray
    npoints = poly.GetNumberOfPoints()
    for i in range(0, npoints):
        # find closest point
        cellLocator.FindClosestPoint(poi.GetPoint(i), clospoint, cellId, subId,
                                     dist)
        # Modify the Surface: Replace the poi with new coordinates.
        poi.SetPoint(i, clospoint)
Exemplo n.º 11
0
def CloudMeanDist(source, target):
    # Source contains few points, target contains many
    locator = vtk.vtkCellLocator()
    locator.SetDataSet(target)
    locator.SetNumberOfCellsPerBucket(1)
    locator.BuildLocator()

    nPoints = source.GetNumberOfPoints()
    closestp = vtk.vtkPoints()
    closestp.SetNumberOfPoints(nPoints)

    subId = vtk.reference(0)
    dist2 = vtk.reference(0.0)
    cellId = vtk.reference(0)  # mutable <-> reference
    outPoint = [0.0, 0.0, 0.0]

    for i in range(nPoints):
        locator.FindClosestPoint(source.GetPoint(i), outPoint, cellId, subId,
                                 dist2)
        closestp.SetPoint(i, outPoint)

    totaldist = 0.0
    p1 = [0.0, 0.0, 0.0]
    p2 = [0.0, 0.0, 0.0]

    for i in range(nPoints):
        # RMS
        totaldist = totaldist + vtk.vtkMath.Distance2BetweenPoints(
            source.GetPoint(i), closestp.GetPoint(i))
    return totaldist / nPoints
Exemplo n.º 12
0
def cell_average(model, bucket):
    """ Calculate a volume fraction estimate at the level of the grid."""

    ugrid = vtk.vtkUnstructuredGrid()
    ugrid.DeepCopy(model)

    locator = vtk.vtkCellLocator()
    locator.SetDataSet(ugrid)
    locator.BuildLocator()

    volfrac = numpy.zeros(ugrid.GetNumberOfCells())
    volume = numpy.zeros(ugrid.GetNumberOfCells())
    temperature = numpy.zeros(ugrid.GetNumberOfCells())
    velocity = numpy.zeros((ugrid.GetNumberOfCells(),3))

    for particle in bucket.particles:
        cell_id = locator.FindCell(particle.pos)
        volume[cell_id] += particle.volume
        velocity[cell_id, :] += particle.volume*particle.vel

    for _ in range(ugrid.GetNumberOfCells()):
        if volume[_] >1.0e-12:
            velocity[_, :] /= volume[_]
        volfrac[_] = volume[_] / get_measure(ugrid.GetCell(_))

    for particle in bucket.particles:
        cell_id = locator.FindCell(particle.pos)
        temperature[cell_id] += particle.volume*distance2(particle.vel,velocity[cell_id, :])

    for _ in range(ugrid.GetNumberOfCells()):
         if volume[_] >1.0e-12:
             temperature[_] /= volume[_]
        
    data = [vtk.vtkDoubleArray()]
    data[0].SetName('SolidVolumeFraction')
    data.append(vtk.vtkDoubleArray())
    data[1].SetName('SolidVolumeVelocity')
    data[1].SetNumberOfComponents(3)
    data.append(vtk.vtkDoubleArray())
    data[2].SetName('GranularTemperature')
#    data.append(vtk.vtkDoubleArray())
#    data[3].SetName('SolidPressure')

    for _ in range(ugrid.GetNumberOfCells()):
        data[0].InsertNextValue(volume[_])
        data[1].InsertNextTuple3(*(velocity[_]))
        data[2].InsertNextValue(temperature[_])
#        data[3].InsertNextValue(solid_pressure[_])

    pdata = vtk.vtkDoubleArray()
    pdata.SetName('Time')
    
    for _ in range(ugrid.GetNumberOfPoints()):
        pdata.InsertNextValue(bucket.time)

    for _ in data:
        ugrid.GetCellData().AddArray(_)
    ugrid.GetPointData().AddArray(pdata)
        
    return ugrid
Exemplo n.º 13
0
def createCellLocator(a_FileName, a_LocatorType=None, a_Legacy='vtp'):
    if a_FileName.endswith('vtu'):
        reader = vtk.vtkXMLUnstructuredGridReader()
    elif a_FileName.endswith('vtp'):
        reader = vtk.vtkXMLPolyDataReader()
    elif a_FileName.endswith('.vtk'):
        if a_Legacy == 'none':
            print("Need To Specify Data Type For Legacy Files")
            sys.exit()
        elif a_Legacy == 'vtu':
            reader = vtk.vtkUnstructuredGridReader()
        elif a_Legacy == 'vtp':
            reader = vtk.vtkPolyDataReader()
    else:
        print("Unsupported File Extension")
        sys.exit()

    reader.SetFileName(a_FileName)
    reader.Update()

    if a_LocatorType is None:
        locator = vtk.vtkCellTreeLocator()
    else:
        if a_LocatorType == 'oct':
            locator = vtk.vtkCellLocator()
        elif a_LocatorType == 'tre':
            locator = vtk.vtkCellTreeLocator()
        elif a_LocatorType == 'bsp':
            locator = vtk.vtkModifiedBSPTree()

    locator.SetDataSet(reader.GetOutput())
    locator.BuildLocator()

    return locator
Exemplo n.º 14
0
    def __init__(self, target_mesh):
        self.point_locator = vtk.vtkPointLocator()
        self.point_locator.SetDataSet(target_mesh)
        self.point_locator.BuildLocator()

        self.cell_locator = vtk.vtkCellLocator()
        self.cell_locator.SetDataSet(target_mesh)
        self.cell_locator.SetTolerance(0.0001)
        self.cell_locator.BuildLocator()

        edge_filter = vtk.vtkFeatureEdges()
        edge_filter.SetInputData(target_mesh)
        edge_filter.BoundaryEdgesOn()
        edge_filter.FeatureEdgesOn()
        edge_filter.SetFeatureAngle(90)
        edge_filter.ManifoldEdgesOff()
        edge_filter.NonManifoldEdgesOff()
        edge_filter.Update()
        edge_points = edge_filter.GetOutput().GetPoints()

        self.edge_point_ids = []
        for i in range(edge_points.GetNumberOfPoints()):
            point_id = self.point_locator.FindClosestPoint(
                edge_points.GetPoint(i))
            self.edge_point_ids.append(point_id)
Exemplo n.º 15
0
    def __init__(self, pd, val, alpha=0):
        self.loc = vtk.vtkCellLocator()
        self.loc = vtk.vtkModifiedBSPTree()

        arr_crd_2d = pd.GetPointData().GetArray('2Dcrds')

        pts = vtk.vtkPoints()
        for kp in range(pd.GetNumberOfPoints()):
            p = pd.GetPoint(kp)
            crd_2D = arr_crd_2d.GetTuple(kp)
            pts.InsertNextPoint(crd_2D[0], crd_2D[1], 0)
        pd.SetPoints(pts)

        del2d = vtk.vtkDelaunay2D()
        del2d.SetInputData(pd)
        del2d.SetTolerance(0)
        if alpha > 0:
            del2d.SetAlpha(alpha)
        del2d.Update()
        self.pd2 = del2d.GetOutput()
        ##        w = vtk.vtkXMLPolyDataWriter()
        ##        w.SetFileName('del.vtp')
        ##        w.SetInputData(self.pd2)
        ##        w.Write()
        ##        sys.exit(0)

        self.loc.SetDataSet(self.pd2)
        self.loc.BuildLocator()
        self.values = val
Exemplo n.º 16
0
def findZofXYOnPolydata(points,vtkPolydata):

	# Make the cell locator
	cellLocator = vtk.vtkCellLocator()
	cellLocator.SetDataSet(vtkPolydata)
	cellLocator.BuildLocator()
	# Find the min/max of the polydata.
	lbot, ltop = np.array(vtkPolydata.GetBounds())[4::]

	# Loop over all the locations.
	intersectList = []
	try:
		for nr, loc in enumerate(points):
			# Make line
			p1 = np.hstack((loc[0:2],ltop))
			p2 = np.hstack((loc[0:2],lbot))
			# Pre define variables as in C++
			t = vtk.mutable(0)
			pIntSect = [0.0, 0.0, 0.0]
			pcoords = [0.0, 0.0, 0.0]
			sub_id = vtk.mutable(0)
			cellLocator.IntersectWithLine(p1,p2,1e-6,t,pIntSect,pcoords,sub_id)
			intersectList.append(pIntSect)
	except KeyboardInterrupt as k:
		print 'Stopped at iteration {:d} in the for loop.'.format(nr)
		raise k

	# Return the intersects
	return np.array(intersectList)
Exemplo n.º 17
0
    def particle_in_system(self, particle_list, time, rank):
        """ Check that the particles of X are inside the system data """

        out = []

        if self.temporal_cache is None:
            out[:] = True
            return out

        obj = self.temporal_cache(time)[0][0][2]
        loc=vtk.vtkCellLocator()

        if obj.IsA('vtkUnstructuredGrid'):
            loc.SetDataSet(obj)
        else:
            loc.SetDataSet(obj.GetBlock(0))
        loc.BuildLocator()


        cell = vtk.vtkGenericCell()
        pcoords = [0.0,0.0,0.0]
        w=[0.0,0.0,0.0,0.0]


        for par in particle_list:
            out.append(loc.FindCell(par.pos)> -1)

        return out
Exemplo n.º 18
0
    def find_closest_cell(
            self, point: Union[int, np.ndarray]) -> Union[int, np.ndarray]:
        """Find index of closest cell in this mesh to the given point.

        Parameters
        ----------
        point : iterable(float) or np.ndarray
            Length 3 coordinate of the point to query or a ``numpy`` array
            of coordinates.

        Returns
        -------
        index : int or np.ndarray
            Index or indices of the cell in this mesh that is closest
            to the given point.

        Examples
        --------
        Find nearest cell to a point on a sphere

        >>> import pyvista
        >>> mesh = pyvista.Sphere()
        >>> index = mesh.find_closest_cell([0, 0, 0.5])
        >>> index
        59

        Find the nearest cells to several random points.  Note that
        ``-1`` indicates that the locator was not able to find a
        reasonably close cell.

        >>> import numpy as np
        >>> points = np.random.random((1000, 3))
        >>> indices = mesh.find_closest_cell(points)
        >>> print(indices.shape)
        (1000,)
        """
        if isinstance(point, collections.abc.Sequence):
            point = np.array(point)
        # check if this is an array of points
        if isinstance(point, np.ndarray):
            if point.ndim > 2:
                raise ValueError("Array of points must be 2D")
            if point.ndim == 2:
                if point.shape[1] != 3:
                    raise ValueError(
                        "Array of points must have three values per point")
            else:
                if point.size != 3:
                    raise ValueError("Given point must have three values")
                point = np.array([point])
        else:
            raise TypeError("Given point must be an iterable or an array.")

        locator = vtk.vtkCellLocator()
        locator.SetDataSet(self)
        locator.BuildLocator()
        closest_cells = np.array([locator.FindCell(node) for node in point])
        return int(
            closest_cells[0]) if len(closest_cells) == 1 else closest_cells
Exemplo n.º 19
0
def nearest_neighbor(matrix, array, stlpath):
    reader1 = vtk.vtkSTLReader()
    reader1.SetFileName(stlpath)
    reader1.Update()

    target_polydata = reader1.GetOutput()

    # ============ create source points ==============
    print("Creating source points...")
    sourcePoints = vtk.vtkPoints()
    sourceVertices = vtk.vtkCellArray()

    for i in range(array.shape[0]):
        sp_id = sourcePoints.InsertNextPoint(array[i][0], array[i][1],
                                             array[i][2])
        sourceVertices.InsertNextCell(1)
        sourceVertices.InsertCellPoint(sp_id)

    source = vtk.vtkPolyData()
    source.SetPoints(sourcePoints)
    source.SetVerts(sourceVertices)

    trans = vtk.vtkTransform()
    trans.SetMatrix(matrix)

    icpTransformFilter = vtk.vtkTransformPolyDataFilter()
    icpTransformFilter.SetInputData(source)

    icpTransformFilter.SetTransform(trans)
    icpTransformFilter.Update()

    transformedSource = icpTransformFilter.GetOutput()

    my_cell_locator = vtk.vtkCellLocator()
    my_cell_locator.SetDataSet(
        target_polydata)  # reverse.GetOutput() --> vtkPolyData
    my_cell_locator.BuildLocator()

    # ============ display transformed points ==============
    pointCount = array.shape[0]
    transform_array = np.zeros(shape=(pointCount, 3))
    for index in range(pointCount):
        point = [0, 0, 0]
        transformedSource.GetPoint(index, point)
        # print("transformed source point[%s] = [%.2f, %.2f, %.2f]" % (index, point[0], point[1], point[2]))

        cellId = vtk.reference(0)
        c = [0.0, 0.0, 0.0]
        subId = vtk.reference(0)
        d = vtk.reference(0.0)
        my_cell_locator.FindClosestPoint(point, c, cellId, subId, d)

        print("nearest neighbor point[%s] = [%.2f, %.2f, %.2f]" %
              (index, c[0], c[1], c[2]))
        transform_array[index] = c

    return transform_array
Exemplo n.º 20
0
def test_Picker_nearest():
    """Test the vtk_extras.Picker class"""
    locator = vtk.vtkCellLocator()
    locator.SetDataSet(ugrid)
    picker = vtk_extras.Picker()
    picker.name = "Velocity"
    picker.grid = ugrid
    picker.locator = locator

    out = picker.nearest((0.5, 0.5, 0.0))
Exemplo n.º 21
0
 def __init__(self, source_mesh):
     meshReader = vtk.vtkXMLUnstructuredGridReader()
     meshReader.SetFileName(source_mesh)
     meshReader.Update()
     self.grid = meshReader.GetOutput()
     self.cell_finder = vtk.vtkCellLocator()
     self.cell_finder.SetDataSet(self.grid)
     self.cell_finder.LazyEvaluationOn()
     cells = self.grid.GetCellData()
     self.volumes = cells.GetArray("Volume")
Exemplo n.º 22
0
 def __init__(self, source_mesh):
     meshReader = vtk.vtkXMLUnstructuredGridReader()
     meshReader.SetFileName(source_mesh)
     meshReader.Update()
     self.grid = meshReader.GetOutput()
     self.cell_finder = vtk.vtkCellLocator()
     self.cell_finder.SetDataSet(self.grid)
     self.cell_finder.LazyEvaluationOn()
     cells = self.grid.GetCellData()
     self.number_of_cells = meshReader.GetNumberOfCells()
Exemplo n.º 23
0
    def update_const(self, index, tcd):
        if not self.stat_init:
            print('Error: call initialize() before update()')
        else:
            # index = next(self.stat_numcalpts)
            # tcd = self.cds[index]
            hdf5_file_name = next(self.g)
            copyfile(self.base_file, hdf5_file_name)
            self.fastmech_change_cd(hdf5_file_name, tcd)
            self.fastmech_BCs(hdf5_file_name)
            for path in self.execute(["Fastmech.exe", hdf5_file_name]):
                print(path, end="")

            SGrid = vtk.vtkStructuredGrid()
            self.create_vtk_structured_grid(SGrid, hdf5_file_name)
            cellLocator2D = vtk.vtkCellLocator()
            cellLocator2D.SetDataSet(SGrid)
            # cellLocator2D.SetNumberOfCellsPerBucket(10);
            cellLocator2D.BuildLocator()

            WSE_2D = SGrid.GetPointData().GetScalars('WSE')
            IBC_2D = SGrid.GetPointData().GetScalars('IBC')
            Velocity_2D = SGrid.GetPointData().GetScalars('Velocity')
            simwse = np.zeros(self.meas_wse.shape[0])
            measwse = np.zeros(self.meas_wse.shape[0])
            for counter, line in enumerate(self.meas_wse):
                point2D = [line[0] - self.xoffset, line[1] - self.yoffset, 0.0]
                pt1 = [line[0] - self.xoffset, line[1] - self.yoffset, 10.0]
                pt2 = [line[0] - self.xoffset, line[1] - self.yoffset, -10]
                idlist1 = vtk.vtkIdList()
                cellLocator2D.FindCellsAlongLine(pt1, pt2, 0.0, idlist1)
                cellid = idlist1.GetId(0)
                # cellid = cellLocator2D.FindCell(point2D)
                # print (isCellWet(SGrid, point2D, cellid, IBC_2D))
                tmpwse = self.getCellValue(SGrid, point2D, cellid, WSE_2D)
                if tcd == self.cdmin:
                    self.meas_and_sim_wse[counter, 0] = line[2]
                #     print counter
                simwse[counter] = tmpwse
                measwse[counter] = line[2]
                # print(cellid, line[2], tmpwse)
            self.meas_and_sim_wse[:, index + 1] = simwse
            self.rmse_data[index] = self.rmse(simwse, measwse)
            self.cd_val[index] = tcd
            # print(self.rmse_data[index])
            # print(self.cd_val)
            # print(self.rmse_data)
            trmse = np.column_stack(
                (self.cd_val.flatten(), self.rmse_data.flatten()))
            # print(trmse)
            np.savetxt(self.rmse_file, trmse, delimiter=',')
            np.savetxt(self.meas_vs_sim_file,
                       self.meas_and_sim_wse,
                       delimiter=',')
            return trmse
Exemplo n.º 24
0
    def __init__(self, vtk_mesh):
        cell_locator = vtk.vtkCellLocator()
        cell_locator.SetDataSet(vtk_mesh)
        cell_locator.BuildLocator()
        self.cell_locator = cell_locator

        # prepare some private properties that will be filled in for us by VTK
        self._c_point = [0., 0., 0.]
        self._cell_id = vtk.mutable(0)
        self._sub_id = vtk.mutable(0)
        self._distance = vtk.mutable(0.0)
Exemplo n.º 25
0
	def __init__(self):
		self.source = None
		self.locator = vtk.vtkCellLocator()
		self.mapper = vtk.vtkPolyDataMapper()
		self.actor = vtk.vtkActor()
	 	self.density = 1.0
		self.transform = vtk.vtkTransform()
		self.transformFilter=vtk.vtkTransformPolyDataFilter()
		self.transformFilter.SetTransform(self.transform)
		self.tolerance = 0.00001
		self.tmut = vtk.mutable(0)
		self.subId = vtk.mutable(0)
Exemplo n.º 26
0
def treesOfNodes(*nodes):
    trees = []
    for node in nodes:
        mesh = vtk.vtkDiscreteMarchingCubes()
        mesh.SetInputData(node.GetImageData())
        mesh.Update()
        polyData = mesh.GetOutput()
        tree = vtk.vtkCellLocator()
        tree.SetDataSet(polyData)
        tree.BuildLocator()
        trees.append(tree)
    return trees
Exemplo n.º 27
0
def get_spline_actor(surface_data, chassis_cg_path, surface_bounds):
    # Iterate over chassis CG points and create a spline which marks the driving path.
    # Return the spline as a vtkActor for being added later to the renderer.

    # Update the pipeline so that vtkCellLocator finds cells
    surface_data.Update()

    # Define a cellLocator to be able to compute intersections between lines
    # and the surface
    locator = vtkCellLocator()
    locator.SetDataSet(surface_data.GetOutput())
    locator.BuildLocator()

    tolerance = 0.01  # Set intersection searching tolerance

    # Make a list of points. Each point is the intersection of a vertical line
    # defined by p1 and p2 and the surface.
    points = vtkPoints()
    for chassis_cg in chassis_cg_path:
        p1 = [chassis_cg[0], chassis_cg[1], surface_bounds[4]]
        p2 = [chassis_cg[0], chassis_cg[1], surface_bounds[5]]

        t = mutable(0)
        pos = [0.0, 0.0, 0.0]
        pcoords = [0.0, 0.0, 0.0]
        subId = mutable(0)
        locator.IntersectWithLine(p1, p2, tolerance, t, pos, pcoords, subId)

        # Add a slight offset in z
        pos[2] += 0.05

        # Add the x, y, z position of the intersection
        points.InsertNextPoint(pos)

    # Create a spline and add the pointsoi
    spline = vtkParametricSpline()
    spline.SetPoints(points)
    spline_function = vtkParametricFunctionSource()
    spline_function.SetUResolution(len(chassis_cg_path))
    spline_function.SetParametricFunction(spline)

    # Map the spline
    spline_mapper = vtkPolyDataMapper()
    spline_mapper.SetInputConnection(spline_function.GetOutputPort())

    # Define the line actor
    spline_actor = vtkActor()
    spline_actor.SetMapper(spline_mapper)
    spline_actor.GetProperty().SetColor([0, 0.7, 0])
    spline_actor.GetProperty().SetLineWidth(10)

    return spline_actor
Exemplo n.º 28
0
    def open(self, k):
        """ Open a file for reading."""
        rdr = vtk.vtkXMLUnstructuredGridReader()

        print 'loading %s'%self.data[k][1]
        rdr.SetFileName(self.data[k][1])
        rdr.Update()

        self.data[k][2] = rdr.GetOutput()
        cloc = vtk.vtkCellLocator()
        cloc.SetDataSet(self.data[k][2])
        cloc.BuildLocator()
        self.data[k][3] = cloc
Exemplo n.º 29
0
 def __init__(self, block, time, dt, velocity_name='Velocity'):
     """ Initialise the cache. 
          block  -- The VTK multiblock object
          time   -- The (current) simulation time
          dt     -- The model timestep """
     self.block = block
     self.time = time
     self.delta_t = dt
     self.velocity_name = velocity_name
     self.cloc = vtk.vtkCellLocator()
     self.cloc.SetDataSet(self.block.GetBlock(0))
     self.cloc.SetTolerance(0.0)
     self.cloc.BuildLocator()
Exemplo n.º 30
0
    def get_vtkCellLocator(self):

        if len(self.get_enabled_features()) == 0:
            return None

        if self.vtkCellLocator is None:
            self.vtkCellLocator = vtk.vtkCellLocator()
            self.vtkCellLocator.SetTolerance(1e-6)

            self.vtkCellLocator.SetDataSet(self.get_combined_geometry())
            self.vtkCellLocator.BuildLocator()

        return self.vtkCellLocator
Exemplo n.º 31
0
    def __init__(self, data):
        self.polyData = data
        self.polyData.BuildCells()
        self.polyData.BuildLinks()
        self.tCoords = data.GetPointData().GetTCoords()
        self.points = data.GetPoints()

        self.npTCoords = np.empty((data.GetPolys().GetNumberOfCells(), 6))
        self.npPolys = np.empty((data.GetPolys().GetNumberOfCells(), 3),
                                dtype=np.uint16)

        nTuples = self.tCoords.GetNumberOfTuples()
        tCoordPoints = vtk.vtkFloatArray()
        tCoordPoints.SetNumberOfComponents(3)
        # tCoordPoints.SetNumberOfTuples(3)
        tCoordPoints.Allocate(nTuples * 3)
        tCoordPoints.SetNumberOfTuples(nTuples)
        tCoordPoints.CopyComponent(0, self.tCoords, 0)
        tCoordPoints.CopyComponent(1, self.tCoords, 1)
        tCoordPoints.FillComponent(2, 0)
        self.polyData2D = vtk.vtkPolyData()
        points = vtk.vtkPoints()
        points.SetData(tCoordPoints)
        self.polyData2D.SetPoints(points)
        self.polyData2D.SetPolys(data.GetPolys())
        self.polyData2D.BuildCells()
        self.polyData2D.BuildLinks()

        self.pointLocator = vtk.vtkCellLocator()
        self.pointLocator.SetDataSet(data)
        self.pointLocator.BuildLocator()

        self.pointLocator2D = vtk.vtkCellLocator()
        self.pointLocator2D.SetDataSet(self.polyData2D)
        self.pointLocator2D.BuildLocator()

        # Reused variables
        self._cell = vtk.vtkGenericCell()
        self._cell.SetCellTypeToTriangle()
Exemplo n.º 32
0
    def open(self, k):
        """ Open a file for reading."""
        rdr = vtk.vtkXMLGenericDataObjectReader()

        Debug.logger.info('loading %s', self.data[k][1])
        rdr.SetFileName(self.data[k][1])
        rdr.Update()

        self.data[k][2] = rdr.GetOutput()
        cloc = vtk.vtkCellLocator()
        cloc.SetDataSet(self.data[k][2])
        cloc.BuildLocator()
        self.data[k][3] = cloc
Exemplo n.º 33
0
def closestPoint(actor, pt, N=1, radius=None, returnIds=False):
    """
    Find the closest point on a polydata given an other point.
    The appropriate locator is built on the fly and cached for speed.
        If N>1, return a list of N ordered closest points.
        If radius is given, get all points within.
    """
    poly = polydata(actor, True)

    if N > 1 or radius:
        plocexists = hasattr(actor, 'point_locator')
        if not plocexists or (plocexists and actor.point_locator is None):
            point_locator = vtk.vtkPointLocator()
            point_locator.SetDataSet(poly)
            point_locator.BuildLocator()
            setattr(actor, 'point_locator', point_locator)

        vtklist = vtk.vtkIdList()
        if N > 1:
            actor.point_locator.FindClosestNPoints(N, pt, vtklist)
        else:
            actor.point_locator.FindPointsWithinRadius(radius, pt, vtklist)
        if returnIds:
            return [
                int(vtklist.GetId(k)) for k in range(vtklist.GetNumberOfIds())
            ]
        else:
            trgp = []
            for i in range(vtklist.GetNumberOfIds()):
                trgp_ = [0, 0, 0]
                vi = vtklist.GetId(i)
                poly.GetPoints().GetPoint(vi, trgp_)
                trgp.append(trgp_)
            return np.array(trgp)

    clocexists = hasattr(actor, 'cell_locator')
    if not clocexists or (clocexists and actor.cell_locator is None):
        cell_locator = vtk.vtkCellLocator()
        cell_locator.SetDataSet(poly)
        cell_locator.BuildLocator()
        setattr(actor, 'cell_locator', cell_locator)

    trgp = [0, 0, 0]
    cid = vtk.mutable(0)
    dist2 = vtk.mutable(0)
    subid = vtk.mutable(0)
    actor.cell_locator.FindClosestPoint(pt, trgp, cid, subid, dist2)
    if returnIds:
        return int(cid)
    else:
        return np.array(trgp)
Exemplo n.º 34
0
    def update_var(self, cnt, tcd, q=0):
        if not self.stat_init:
            print('Error: call initialize() before update()')
        else:
            # index = next(self.stat_numcalpts)
            # tcd = self.cds[index]
            hdf5_file_name = next(self.g)
            copyfile(self.base_file, hdf5_file_name)
            self.fastmech_change_var_cd2(hdf5_file_name, tcd)
            if q != 0:
                self.Q = q
            self.fastmech_BCs(hdf5_file_name)
            for path in self.execute(["Fastmech.exe", hdf5_file_name]):
                print(path, end="")

            SGrid = vtk.vtkStructuredGrid()
            self.create_vtk_structured_grid(SGrid, hdf5_file_name)
            cellLocator2D = vtk.vtkCellLocator()
            cellLocator2D.SetDataSet(SGrid)
            # cellLocator2D.SetNumberOfCellsPerBucket(10);
            cellLocator2D.BuildLocator()

            WSE_2D = SGrid.GetPointData().GetScalars('WSE')
            IBC_2D = SGrid.GetPointData().GetScalars('IBC')
            Velocity_2D = SGrid.GetPointData().GetScalars('Velocity')
            simwse = np.zeros(self.meas_wse.shape[0])
            measwse = np.zeros(self.meas_wse.shape[0])
            for counter, line in enumerate(self.meas_wse):
                point2D = [line[0] - self.xoffset, line[1] - self.yoffset, 0.0]
                pt1 = [line[0] - self.xoffset, line[1] - self.yoffset, 10.0]
                pt2 = [line[0] - self.xoffset, line[1] - self.yoffset, -10]
                idlist1 = vtk.vtkIdList()
                cellLocator2D.FindCellsAlongLine(pt1, pt2, 0.0, idlist1)
                cellid = idlist1.GetId(0)
                tmpwse = self.getCellValue(SGrid, point2D, cellid, WSE_2D)
                simwse[counter] = tmpwse
                measwse[counter] = line[2]
                print(cellid, line[2], tmpwse)
            self.resdf.loc[cnt, self.dfcols[0]] = cnt
            for key in tcd:
                self.resdf.loc[cnt, self.dfcols[int(key + 1)]] = tcd[key]
            self.resdf.loc[cnt, 'rmse'] = self.rmse(simwse, measwse)
            self.resdf.loc[cnt, 'Discharge'] = self.Q

            # trmse = np.column_stack((self.cd0_var_vals.flatten(), self.cd1_var_vals.flatten(), self.rmse_var_data.flatten()))
            # print(trmse)
            #
            # np.savetxt(self.rmse_file, trmse, delimiter=',')
            self.resdf.to_csv(self.rmse_file)
            # np.savetxt(self.meas_vs_sim_file, self.meas_and_sim_wse_var, delimiter=',')
            return self.resdf
Exemplo n.º 35
0
 def __init__(self, block, time, dt, velocity_name='Velocity'):
     """ Initialise the cache.
          block  -- The VTK multiblock object
          time   -- The (current) simulation time
          dt     -- The model timestep """
     self.block = block
     self.time = time
     self.delta_t = dt
     self.velocity_name = velocity_name
     self.cloc = vtk.vtkCellLocator()
     self.cloc.SetDataSet(self.block.GetBlock(0))
     self.cloc.SetTolerance(0.0)
     self.cloc.BuildLocator()
     self.cache = DataCache()
Exemplo n.º 36
0
    def fun(time):
        """Factory function to mock a temporal cache."""
        del time
        reader = vtk.vtkXMLUnstructuredGridReader()
        reader.SetFileName(ldir+'/'+fname)
        reader.Update()

        locator = vtk.vtkCellLocator()
        locator.SetDataSet(reader.GetOutput())
        locator.BuildLocator()

        return ([[0.0, fname, reader.GetOutput(), locator],
                 [1.0, fname, reader.GetOutput(), locator]], 0.0,
                [['Velocity', 'Pressure'], ['Velocity', 'Pressure']])
Exemplo n.º 37
0
def get_solid_velocity(bucket, data, volfrac):
    """Calculate the particle volume fraction using control volumes"""

    linear_data = IO.get_linear_block(data) 
    is2d = linear_data.GetCell(0).GetCellType()==vtk.VTK_TRIANGLE

    cvs = vtp.vtkShowCVs()
    cvs.SetContinuity(-1)
    if vtk.vtkVersion.GetVTKMajorVersion()<6:
        cvs.SetInput(linear_data)
    else:
        cvs.SetInputData(linear_data)
    cvs.Update()
    cv_data = cvs.GetOutput()

    locator = vtk.vtkCellLocator()
    locator.SetDataSet(cv_data)
    locator.BuildLocator()


    if is2d:
        dim=2
    else:
        dim=3
    output = numpy.zeros((linear_data.GetNumberOfPoints(),dim))
    volume = numpy.zeros(linear_data.GetNumberOfPoints())


    for par in bucket.particles:
        index = locator.FindCell(par.pos)
        if index<0:
            continue
        ele, l_id = divmod(index,linear_data.GetCell(0).GetNumberOfPoints())

        gid = linear_data.GetCell(ele).GetPointId(l_id)

                                                      
        if is2d:
            volume[gid] += par.parameters.get_area()
            output[gid,:] += par.parameters.get_area()*par.vel[:dim]
        else:
            volume[gid] += par.parameters.get_volume()
            output[gid,:] += par.parameters.get_volume()*par.vel[:dim]

    for _ in range(linear_data.GetNumberOfPoints()):
        if volume[_]>0.0:
            output[_,:] = output[_,:]/volume[_]

            
    return output
Exemplo n.º 38
0
    def get_impact(ugrid, start, direction, factor = 1000):
        cl = vtk.vtkCellLocator()
        ugrid = read_ugrid(ugrid)
        cl.SetDataSet(ugrid)

        mult = lambda f, x: map(lambda a: f*a, x)
        end = mult(1000, direction)


        points = vtk.vtkPoints()
        cells = vtk.vtkIdList()

        cl.intersectWithLine(start, end, points, cells)

        ugrid.GetCell(cells.getId(0))
Exemplo n.º 39
0
def get_cv_fraction(bucket, data):
    """Calculate the particle volume fraction using control volumes"""

    linear_data = IO.get_linear_block(data) 
    is2d = linear_data.GetCell(0).GetCellType()==vtk.VTK_TRIANGLE

    cvs = vtp.vtkShowCVs()
    cvs.SetContinuity(-1)
    if vtk.vtkVersion.GetVTKMajorVersion()<6:
        cvs.SetInput(linear_data)
    else:
        cvs.SetInputData(linear_data)
    cvs.Update()
    cv_data = cvs.GetOutput()

    locator = vtk.vtkCellLocator()
    locator.SetDataSet(cv_data)
    locator.BuildLocator()

    output = numpy.zeros(linear_data.GetNumberOfPoints())
    volume = numpy.zeros(linear_data.GetNumberOfPoints())

    for _ in range(linear_data.GetNumberOfCells()):
        
        cell = linear_data.GetCell(_)
        pntIds = cell.GetPointIds()
        cv_mass = IO.get_measure(cell)/cell.GetNumberOfPoints()

        for dummy_1 in range(pntIds.GetNumberOfIds()):
            volume[pntIds.GetId(dummy_1)] += cv_mass

    for par in bucket.particles:
        index = locator.FindCell(par.pos)
        if index<0:
            continue
        ele, l_id = divmod(index,linear_data.GetCell(0).GetNumberOfPoints())

        gid = linear_data.GetCell(ele).GetPointId(l_id)

                                                      
        if is2d:
            output[gid] += par.parameters.get_area()
        else:
            output[gid] += par.parameters.get_volume()
    


    return output/volume
Exemplo n.º 40
0
def getCellLocator(
        mesh,
        verbose=0):

    myVTK.myPrint(verbose, "*** getCellLocator ***")

    cell_locator = vtk.vtkCellLocator()
    cell_locator.SetDataSet(mesh)
    cell_locator.Update()

    closest_point = [0.]*3
    generic_cell = vtk.vtkGenericCell()
    k_cell = vtk.mutable(0)
    subId = vtk.mutable(0)
    dist = vtk.mutable(0.)

    return (cell_locator,
            closest_point,
            generic_cell,
            k_cell,
            subId,
            dist)
Exemplo n.º 41
0
    def in_system(self, points, time):
        """ Check that the points of X are inside the system data """

        out = empty(points.shape[0],bool)

        if self.temporal_cache is None or Parallel.is_parallel():
            out[:] = True
            return out

        obj = self.temporal_cache(time)[0][0][2]
        loc=vtk.vtkCellLocator()

        if obj.IsA('vtkUnstructuredGrid'):
            loc.SetDataSet(obj)
        else:
            loc.SetDataSet(obj.GetBlock(0))
        loc.BuildLocator()



        for k, point in enumerate(points):
            out[k] = loc.FindCell(point)> -1

        return out
Exemplo n.º 42
0
    def __init__(self, filename=None,bnd=None,outlet_ids=[], inlets=[], dist=None):
        """Class containing the information about the boundary of the domain.

        Args:
            filename (str): Name of the file containing the
            vtkUnstructuredGrid denoting the boundary of the domain."""

        self.reader = vtk.vtkXMLUnstructuredGridReader() 
        self.bndl = vtk.vtkCellLocator()
        self.geom_filter = vtk.vtkGeometryFilter()
        self.outlet_ids=outlet_ids
        self.inlets=inlets
        self.dist = dist

        open_ids = [] + self.outlet_ids
        for inlet in self.inlets:
            open_ids+=inlet.surface_ids

        if filename is not None:
            self.update_boundary_file(filename, open_ids)
        else:
            self.bnd=bnd
            if self.dist:
                self.phys_bnd = IO.move_boundary_through_normal(self.bnd,
                                                                ids = open_ids)
            else:
                self.phys_bnd = self.bnd

            if vtk.vtkVersion.GetVTKMajorVersion()<6:
                self.geom_filter.SetInput(self.phys_bnd)
            else:
                self.geom_filter.SetInputData(self.phys_bnd)
            self.geom_filter.Update()

            self.bndl.SetDataSet(self.geom_filter.GetOutput())
            self.bndl.BuildLocator()
Exemplo n.º 43
0
 def SurfacePicker(self):
     self.cortexLocator = vtk.vtkCellLocator()
     self.cortexLocator.SetDataSet(self.cortexExtractor.GetOutput())
     self.cortexLocator.LazyEvaluationOn()
def vtu_To_hf3inp_inc_MV_matIDs_Producer(inputfilename, surfaceMesh, outputfilename):
	# ======================================================================
	# Define matIDs --------------------------------------------------------
	ID_UP = 21 # preliminary result, which gets overwritten by ID_ANT and ID_POST.
	ID_DOWN = 20
	ID_ANT = 17
	ID_POST = 18
	
	# ======================================================================
	# get system arguments -------------------------------------------------
	valve3dFilename_ = inputfilename
	valve2dFilename_ = surfaceMesh
	outputFilename_ = outputfilename
	
	print " "
	print "==========================================================================================="
	print "=== Execute Python script to produce HiFlow3 inp file (incl. matIDs) for MVR-Simulation ==="
	print "==========================================================================================="
	print " "
	
	# ======================================================================
	# read in files: -------------------------------------------------------
	# read in 3d valve
	# NOTE: ensure that the precedent meshing algorithm (CGAL or similar)
	#       produces consistent/good results w.r.t. the 'normal glyphs'.
	vtureader = vtk.vtkXMLUnstructuredGridReader()
	vtureader.SetFileName(valve3dFilename_)
	vtureader.Update()
	valve3d_ = vtureader.GetOutput()
	
	# get surface mesh of valve3d_
	geometryFilter = vtk.vtkGeometryFilter()
	if vtk.vtkVersion().GetVTKMajorVersion() >= 6:
  	  geometryFilter.SetInputData(valve3d_)
	else:
  	  geometryFilter.SetInput(valve3d_)
	geometryFilter.Update()
	valve3dSurface_ = geometryFilter.GetOutput()
	
	# compute normals of surface mesh
	normalsSurface_ = vtk.vtkPolyDataNormals()
	if vtk.vtkVersion().GetVTKMajorVersion() >= 6:
  	  normalsSurface_.SetInputData(valve3dSurface_)
	else:
  	  normalsSurface_.SetInput(valve3dSurface_)
	normalsSurface_.SplittingOn()
	normalsSurface_.ConsistencyOn() # such that on a surface the normals are oriented either 'all' outward OR 'all' inward.
	normalsSurface_.AutoOrientNormalsOn() # such that normals point outward or inward.
	normalsSurface_.ComputePointNormalsOff() # adapt here. On/Off.
	normalsSurface_.ComputeCellNormalsOn()   # adapt here.
	normalsSurface_.FlipNormalsOff()
	normalsSurface_.NonManifoldTraversalOn()
	normalsSurface_.Update()
	
	# get cell normals
	normalsSurfaceRetrieved_ = normalsSurface_.GetOutput().GetCellData().GetNormals() # adapt here.
	
	# read in 2d valve -----------------------------------------------------
	vtpreader = vtk.vtkXMLPolyDataReader()
	vtpreader.SetFileName(valve2dFilename_)
	vtpreader.Update()
	valve2d_ = vtpreader.GetOutput()
	
	# compute normals of valve2d_
	normalsValve2d_ = vtk.vtkPolyDataNormals()
	if vtk.vtkVersion().GetVTKMajorVersion() >= 6:
  	  normalsValve2d_.SetInputData(valve2d_)
	else:
  	  normalsValve2d_.SetInput(valve2d_)
	normalsValve2d_.SplittingOn()
	normalsValve2d_.ConsistencyOn()
	normalsValve2d_.ComputePointNormalsOff() # adapt here.
	normalsValve2d_.ComputeCellNormalsOn()
	normalsValve2d_.FlipNormalsOff()
	normalsValve2d_.NonManifoldTraversalOn()
	normalsValve2d_.Update()
	
	# get cell normals
	normalsValve2dRetrieved_ = normalsValve2d_.GetOutput().GetCellData().GetNormals() # adapt here.
	
	print "Reading 3D and 2D-annotated input files: DONE."
	
	# ======================================================================
	# initialize cell locator for closest cell search ----------------------
	# (using vtk methods, that find the closest point in a grid for an arbitrary point in R^3)
	cellLocator = vtk.vtkCellLocator()
	cellLocator.SetDataSet(valve2d_)
	cellLocator.BuildLocator()
	
	# ======================================================================
	# allocate memory for cell_udlr_list_ (up-down-left-right) -------------
	cell_udlr_list_ = [0 for i in range(valve3dSurface_.GetNumberOfCells())]
	
	# ======================================================================
	# iterate over the cells of the surface and compare normals ------------
	for i in range(valve3dSurface_.GetNumberOfCells()):
  	  # get cellId of closest point
  	  iD = valve3dSurface_.GetCell(i).GetPointId(0) # NOTE: only one (test)point (0) of respective cell
  	  testPoint = valve3dSurface_.GetPoint(iD)
  	  closestPoint = np.zeros(3)
  	  closestPointDist2 = vtk.mutable(0)
  	  cellId = vtk.mutable(0)
  	  subId = vtk.mutable(0)
  	  cellLocator.FindClosestPoint(testPoint, closestPoint, cellId, subId, closestPointDist2)
      
  	  normalSurf_ = np.zeros(3)
  	  normalsSurfaceRetrieved_.GetTuple(i, normalSurf_)
  	  
  	  normalV2d_ = np.zeros(3)
  	  normalsValve2dRetrieved_.GetTuple(cellId, normalV2d_)
  	  
  	  # set cell_udlr_list_ entry to (preliminary) "1", if cell is on upper side of leaflet
  	  if np.dot(normalSurf_, normalV2d_) > 0.0:
  	    cell_udlr_list_[i] = 1 # NOTE: "cell_udlr_list_[i] = 1" means "cell on upside".
  	  
  	# ======================================================================
	# iterate over cells on the upper side of the leaflet surface, and set ids for left/right ------------------
	kDTree = vtk.vtkKdTreePointLocator()
	kDTree.SetDataSet(valve2d_)
	kDTree.BuildLocator()
	
	VertexIDs_ = valve2d_.GetPointData().GetArray('VertexIDs')
	
	# allocate memory for upCellList_ (indicating if cell is on left/right side)
	upCellList_ = [i for i in range(valve3dSurface_.GetNumberOfCells()) if cell_udlr_list_[i]]
	
	for i in upCellList_:
	  iD = valve3dSurface_.GetCell(i).GetPointId(0)
	  testPoint = valve3dSurface_.GetPoint(iD)
	  result_ = vtk.vtkIdList()
	  counter = 1
	  cond_ = True
	  while cond_:
	    kDTree.FindClosestNPoints(counter, testPoint, result_)
	    for j in range(result_.GetNumberOfIds()):
	      iD2 = result_.GetId(j)
	      if int(VertexIDs_.GetTuple1(iD2)) == ID_ANT:
		    cond_ = False
		    cell_udlr_list_[i] = 2 # NOTE: "cell_udlr_list_[i] = 2" means "cell on ANT upside".
	      if int(VertexIDs_.GetTuple1(iD2)) == ID_POST:
		    cond_ = False
		    cell_udlr_list_[i] = 3 # NOTE: "cell_udlr_list_[i] = 3" means "cell on POST upside".
	    counter += 1
	
	print "Computing hf3-inp MV matID information: DONE."
	
	# ======================================================================
	# write results to inp file --------------------------------------------
	f = open(outputFilename_, 'w')
	
	# write first line
	s = str(valve3d_.GetNumberOfPoints()) + ' ' + str(valve3dSurface_.GetNumberOfCells()+valve3d_.GetNumberOfCells()) + ' 0 0 0\n'
	f.write(s)
	
	# write point coordinates
	for i in range(valve3d_.GetNumberOfPoints()):
	  pt = valve3d_.GetPoint(i)
	  s = str(i) + ' ' + str(pt[0]) + ' ' + str(pt[1]) + ' ' + str(pt[2]) + '\n'
	  f.write(s)
	
	# write connectivity information of triangles
	# integer, material id, vertex point ids
	for i in range(valve3dSurface_.GetNumberOfCells()):
	  cell = valve3dSurface_.GetCell(i)
	  iDs = cell.GetPointIds()
	  if cell_udlr_list_[i] == 2:     # NOTE: "cell_udlr_list_[i] = 2" means "cell on ANT upside".
	    matId = ID_ANT
	  elif cell_udlr_list_[i] == 3:   # NOTE: "cell_udlr_list_[i] = 3" means "cell on POST upside".
	    matId = ID_POST
	  else:                           # NOTE: "cell_udlr_list_[i] = 0" means "cell on downside".
	    matId = ID_DOWN
	  s = str(0) + ' ' + str(matId) + ' tri ' + str(iDs.GetId(0)) + ' ' + str(iDs.GetId(1)) + ' ' + str(iDs.GetId(2)) + '\n'
	  f.write(s)
	
	# write connectivity information of tetrahedrons
	# integer, material id, vertex point ids
	for i in range(valve3d_.GetNumberOfCells()):
	  cell = valve3d_.GetCell(i)
	  iDs = cell.GetPointIds()
	  matId = 10
	  s = str(0) + ' ' + str(matId) + ' tet ' + str(iDs.GetId(0)) + ' ' + str(iDs.GetId(1)) + ' ' + str(iDs.GetId(2)) + ' ' + str(iDs.GetId(3)) + '\n'
	  f.write(s)
	
	# close stream
	f.close()
	
	# ======================================================================
	print "Writing HiFlow3 inp output file (incl. MV matIDs): DONE."
	print "========================================================"
	print " "
Exemplo n.º 45
0
    def __loadData(self):
        ''' Handles setting paths for data and initializing new scene. '''
        #if self.active_vol is not None:
        #    self._contextView.GetScene().RemoveItem( self._vdata[str(self.active_vol)].chart )
        
        dpath = str( self._fileDialog.getFilePath( filter='Matlab files (*.mat)' ) )

        filename = dbsUtils.getPathLeaf( dpath )
        
        if filename in self._vdata.keys(): 
            QtGui.QMessageBox.warning( self, 'Warning', \
                                          'Dataset is already loaded. See tabs.' )
            return
        elif filename is '':
            return #no file selected
        else:
            try: 
                self.scores[filename] = dbsUtils.readAvgChangeMatrices(dpath)
            except:
                QtGui.QMessageBox.warning( self, 'Warning', \
                                          'File selected is invalid.' )
                return 
            
        # store electrode params for current data set
        if self.active_vol is not None:
            self._electrodeViewDialog.saveCurrentParams(self.active_vol, fresh_load = False)
            
        self.active_vol = filename
        actv = self.active_vol
        
        # create the newly loaded data set dialog parameters
        # self._electrodeViewDialog.saveCurrentParams(self.active_vol, fresh_load = True)
            
        self.__addNewRenderer()
        
        scores = np.copy(self.scores[actv])
        num_patients = scores.shape[1]
        self.scores[actv] = np.reshape(self.scores[actv], newshape=(120, 120, 120, \
            num_patients), order='C')
        
        # create new volume data object for new patient outcome data set
        self._vdata[actv] = vdata.VolumeData( scores, self._renderers[actv], self )
        #self._vdata[actv].createTransFuncChart()
        
        # newly loaded so the default dialog parameters are set
        self._electrodeViewDialog.updateWidgetValues(self.active_vol, default = True)
        
        self.__updateVTKObjects()
        
        scoresim = self._vdata[actv].imdata
        
        self.vol_qvtk_widgets[actv].setPlotting(scoresim=self._vdata[actv].images['Mean'], \
            scores=self.scores[actv], graph = self._sc, \
            pat_data = self._vdata[actv].pat_data_img_data_list)
        
        # locator is optional, but improves performance for large polydata
        vol = str(self._miscControlsDialog.vta_stats_combox.currentText())
        locator = vtk.vtkCellLocator()
        locator.SetDataSet(self._vdata[actv].images[vol])
        locator.LazyEvaluationOn()
        
        self._picker.AddLocator(locator)
        self.__prepareSceneForQVTKWidget()
        
        # update widgets
        self._miscControlsDialog.updateWidgetValues()
        self._para_coords.plot()
        self._patientSubsetSelectorDialog.updateWidgetValues(self._vdata[actv].num_patients, \
                                                             self._vdata[actv].pat_sub_group )
        
        # make the current loaded data set the *active* widget
        self.vol_tabs.setCurrentWidget(self.vol_qvtk_widgets[actv].parent())
  def __init__(self):
    self.toolTipToTool = slicer.util.getNode('toolTipToTool')
    if not self.toolTipToTool:
      self.toolTipToTool=slicer.vtkMRMLLinearTransformNode()
      self.toolTipToTool.SetName("toolTipToTool")
      m = vtk.vtkMatrix4x4()
      m.SetElement( 0, 0, 1 ) # Row 1
      m.SetElement( 0, 1, 0 )
      m.SetElement( 0, 2, 0 )
      m.SetElement( 0, 3, 0 )      
      m.SetElement( 1, 0, 0 )  # Row 2
      m.SetElement( 1, 1, 1 )
      m.SetElement( 1, 2, 0 )
      m.SetElement( 1, 3, 0 )       
      m.SetElement( 2, 0, 0 )  # Row 3
      m.SetElement( 2, 1, 0 )
      m.SetElement( 2, 2, 1 )
      m.SetElement( 2, 3, 0 )
      self.toolTipToTool.SetMatrixTransformToParent(m)
      slicer.mrmlScene.AddNode(self.toolTipToTool)

    self.toolToReference = slicer.util.getNode('toolToReference')
    if not self.toolToReference:
      self.toolToReference=slicer.vtkMRMLLinearTransformNode()
      self.toolToReference.SetName("toolToReference")
      matrixRef = vtk.vtkMatrix4x4()
      matrixRef.SetElement( 0, 0, 1 ) # Row 1
      matrixRef.SetElement( 0, 1, 0 )
      matrixRef.SetElement( 0, 2, 0 )
      matrixRef.SetElement( 0, 3, 0 )      
      matrixRef.SetElement( 1, 0, 0 )  # Row 2
      matrixRef.SetElement( 1, 1, 1 )
      matrixRef.SetElement( 1, 2, 0 )
      matrixRef.SetElement( 1, 3, 0 )       
      matrixRef.SetElement( 2, 0, 0 )  # Row 3
      matrixRef.SetElement( 2, 1, 0 )
      matrixRef.SetElement( 2, 2, 1 )
      matrixRef.SetElement( 2, 3, 0 )
      self.toolToReference.SetMatrixTransformToParent(matrixRef)
      slicer.mrmlScene.AddNode(self.toolToReference)
   
    self.tipFiducial = slicer.util.getNode('Tip')
    if not self.tipFiducial:
      self.tipFiducial = slicer.vtkMRMLMarkupsFiducialNode()  
      self.tipFiducial.SetName('Tip')
      self.tipFiducial.AddFiducial(0, 0, 0)
      self.tipFiducial.SetNthFiducialLabel(0, '')
      slicer.mrmlScene.AddNode(self.tipFiducial)
      self.tipFiducial.SetDisplayVisibility(True)
      self.tipFiducial.GetDisplayNode().SetGlyphType(1) # Vertex2D
      self.tipFiducial.GetDisplayNode().SetTextScale(1.3)
      self.tipFiducial.GetDisplayNode().SetSelectedColor(1,1,1)

    self.targetFiducial = slicer.util.getNode('Target')
    if not self.targetFiducial:
      self.targetFiducial = slicer.vtkMRMLMarkupsFiducialNode()  
      self.targetFiducial.SetName('Target')
      self.targetFiducial.AddFiducial(0, 0, 0)
      self.targetFiducial.SetNthFiducialLabel(0, '')
      slicer.mrmlScene.AddNode(self.targetFiducial)
      self.targetFiducial.SetDisplayVisibility(True)
      self.targetFiducial.GetDisplayNode().SetGlyphType(1) # Vertex2D
      self.targetFiducial.GetDisplayNode().SetTextScale(1.3)
      self.targetFiducial.GetDisplayNode().SetSelectedColor(1,1,1)
      
    self.line = slicer.util.getNode('Line')
    if not self.line:
      self.line = slicer.vtkMRMLModelNode()
      self.line.SetName('Line')
      linePolyData = vtk.vtkPolyData()
      self.line.SetAndObservePolyData(linePolyData)      
      modelDisplay = slicer.vtkMRMLModelDisplayNode()
      modelDisplay.SetSliceIntersectionVisibility(True)
      modelDisplay.SetColor(0,1,0)
      slicer.mrmlScene.AddNode(modelDisplay)      
      self.line.SetAndObserveDisplayNodeID(modelDisplay.GetID())      
      slicer.mrmlScene.AddNode(self.line)
      
    # VTK objects
    self.transformPolyDataFilter = vtk.vtkTransformPolyDataFilter()
    self.cellLocator = vtk.vtkCellLocator()
    
    # 3D View
    threeDWidget = slicer.app.layoutManager().threeDWidget(0)
    self.threeDView = threeDWidget.threeDView()
    
    self.callbackObserverTag = -1
    self.observerTag=None

    # Output Distance Label
    self.outputDistanceLabel=None

    import Viewpoint # Viewpoint Module must have been added to Slicer 
    self.viewpointLogic = Viewpoint.ViewpointLogic()

    # Camera transformations
    self.needleCameraToNeedle = slicer.util.getNode('needleCameraToNeedle')
    if not self.needleCameraToNeedle:
      self.needleCameraToNeedle=slicer.vtkMRMLLinearTransformNode()
      self.needleCameraToNeedle.SetName("needleCameraToNeedle")
      matrixNeedleCamera = vtk.vtkMatrix4x4()
      matrixNeedleCamera.SetElement( 0, 0, -0.05 ) # Row 1
      matrixNeedleCamera.SetElement( 0, 1, 0.09 )
      matrixNeedleCamera.SetElement( 0, 2, -0.99 )
      matrixNeedleCamera.SetElement( 0, 3, 60.72 )      
      matrixNeedleCamera.SetElement( 1, 0, -0.01 )  # Row 2
      matrixNeedleCamera.SetElement( 1, 1, 1 )
      matrixNeedleCamera.SetElement( 1, 2, 0.09 )
      matrixNeedleCamera.SetElement( 1, 3, 12.17 )       
      matrixNeedleCamera.SetElement( 2, 0, 1 )  # Row 3
      matrixNeedleCamera.SetElement( 2, 1, 0.01 )
      matrixNeedleCamera.SetElement( 2, 2, -0.05 )
      matrixNeedleCamera.SetElement( 2, 3, -7.26 )
      self.needleCameraToNeedle.SetMatrixTransformToParent(matrixNeedleCamera)
      slicer.mrmlScene.AddNode(self.needleCameraToNeedle)

    self.pointerCameraToPointer = slicer.util.getNode('pointerCameraToPointer')
    if not self.pointerCameraToPointer:
      self.pointerCameraToPointer=slicer.vtkMRMLLinearTransformNode()
      self.pointerCameraToPointer.SetName("pointerCameraToPointer")
      matrixPointerCamera = vtk.vtkMatrix4x4()
      matrixPointerCamera.SetElement( 0, 0, -0.05 ) # Row 1
      matrixPointerCamera.SetElement( 0, 1, 0.09 )
      matrixPointerCamera.SetElement( 0, 2, -0.99 )
      matrixPointerCamera.SetElement( 0, 3, 121.72 )      
      matrixPointerCamera.SetElement( 1, 0, -0.01 )  # Row 2
      matrixPointerCamera.SetElement( 1, 1, 1 )
      matrixPointerCamera.SetElement( 1, 2, 0.09 )
      matrixPointerCamera.SetElement( 1, 3, 17.17 )       
      matrixPointerCamera.SetElement( 2, 0, 1 )  # Row 3
      matrixPointerCamera.SetElement( 2, 1, 0.01 )
      matrixPointerCamera.SetElement( 2, 2, -0.05 )
      matrixPointerCamera.SetElement( 2, 3, -7.26 )
      self.pointerCameraToPointer.SetMatrixTransformToParent(matrixPointerCamera)
      slicer.mrmlScene.AddNode(self.pointerCameraToPointer)
Exemplo n.º 47
0
 def register(self, fixedData, movingData, index = -1, discard = False, delta = 0, fov = 9999999.0,
         down_fix = 1, down_mov = 1, occ = 9999999.0, op = False, useMask = False, isTime = False, MaxRate = 0.2,
         aug = False, distance_fix = 0.3, distance_mov = 0.1, w_wrong = 1.5, truth_mov = None):
     time1 = time.time()
     if index == -1:
         index = self.gui.getDataIndex({'Contour': 0, 'Centerline': 1}, 'Select the object')
     if index is None:
         return None, None, None
     if index == 0:
         fixed_points = fixedData.getPointSet('Contour').copy()
         moving_points = movingData.getPointSet('Contour').copy()
     else:
         fixed_points = fixedData.getPointSet('Centerline').copy()
         moving_points = movingData.getPointSet('Centerline').copy()
     if truth_mov is None:
         truth_mov = moving_points.copy()
     
     fixed_bif = db.getBifurcation(fixed_points)
     moving_bif = db.getBifurcation(moving_points)
     
     if useMask:
         mask_points = movingData.getPointSet('Mask')
         for point in mask_points:
             moving_points = npy.delete(moving_points, npy.where((npy.abs(moving_points[:, 2] - point[2]) < 0.0001) & (npy.round(moving_points[:, -1]) == point[3])), axis = 0)
         
     fixed_res = fixedData.getResolution().tolist()
     moving_res = movingData.getResolution().tolist()
     fixed_points = fixed_points[npy.where(fixed_points[:, 0] >= 0)]
     moving_points = moving_points[npy.where(moving_points[:, 0] >= 0)]
     
     # Use the bifurcation as the initial position
     if (fixed_bif < 0) or (moving_bif < 0):
         fixed_min = 0
     
     # Augmentation of pointset
     fixed = fixed_points.copy()
     moving = moving_points.copy()
     
     if index == 1 and aug:
         fixed = util.augmentCenterline(fixed, 1, 10)
         moving = util.augmentCenterline(moving, 1, 10)
         fix_dis = util.getAxisSin(fixed, 3 / fixed_res[2]) * distance_fix
         mov_dis = util.getAxisSin(moving, 3 / moving_res[2]) * distance_mov
         fixed = util.resampleCenterline(fixed, fix_dis / fixed_res[2])
         moving = util.resampleCenterline(moving, mov_dis / moving_res[2])
     
     fixed = fixed[npy.cast[npy.int32](npy.abs(fixed[:, 2] - fixed_bif)) % down_fix == 0]
     moving = moving[npy.cast[npy.int32](npy.abs(moving[:, 2] - moving_bif)) % down_mov == 0]
     
     fixed[:, :3] *= fixed_res[:3]
     moving[:, :3] *= moving_res[:3]
     
     new_trans_points = truth_mov
     result_center_points = movingData.getPointSet('Centerline').copy()
     new_trans_points = new_trans_points[new_trans_points[:, 3] >= 0]
     result_center_points = result_center_points[result_center_points[:, 3] >= 0]
     new_trans_points[:, :3] *= moving_res[:3]
     result_center_points[:, :3] *= moving_res[:3]
     
     if (fixed_bif >= 0) and (moving_bif >= 0):
         fixed[:, 2] -= (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta)
     
     # Prepare for ICP
     
     MaxIterNum = 50
     #MaxNum = 600
     MaxNum = int(MaxRate * moving.shape[0] + 0.5)
     
     targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()]
     targetVertices = [vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray()]
     target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()]
     Locator = [vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator()]
     
     for i in range(3):
         for x in fixed[npy.round(fixed[:, 3]) == i]:
             id = targetPoints[i].InsertNextPoint(x[0], x[1], x[2])
             targetVertices[i].InsertNextCell(1)
             targetVertices[i].InsertCellPoint(id)
         target[i].SetPoints(targetPoints[i])
         target[i].SetVerts(targetVertices[i])
         
         Locator[i].SetDataSet(target[i])
         Locator[i].SetNumberOfCellsPerBucket(1)
         Locator[i].BuildLocator()
     
     step = 1
     if moving.shape[0] > MaxNum:
         ind = moving[:, 2].argsort()
         moving = moving[ind, :]
         step = moving.shape[0] / MaxNum
     nb_points = moving.shape[0] / step
     
     points1 = vtk.vtkPoints()
     points1.SetNumberOfPoints(nb_points)
     
     label = npy.zeros([MaxNum * 2], dtype = npy.int8)
     
     j = 0
     for i in range(nb_points):
         points1.SetPoint(i, moving[j][0], moving[j][1], moving[j][2])
         label[i] = moving[j][3]
         j += step
     
     closestp = vtk.vtkPoints()
     closestp.SetNumberOfPoints(nb_points)
     points2 = vtk.vtkPoints()
     points2.SetNumberOfPoints(nb_points)
     
     id1 = id2 = vtk.mutable(0)
     dist = vtk.mutable(0.0)
     outPoint = [0.0, 0.0, 0.0]
     p1 = [0.0, 0.0, 0.0]
     p2 = [0.0, 0.0, 0.0]
     iternum = 0
     a = points1
     b = points2
     if (op and index == 0) or (not op and index == 1):
         w_mat = [[1, w_wrong, w_wrong], [w_wrong, 1, 99999999], [w_wrong, 99999999, 1]]
     else:
         w_mat = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
     
     accumulate = vtk.vtkTransform()
     accumulate.PostMultiply()
     LandmarkTransform = vtk.vtkLandmarkTransform()
     LandmarkTransform.SetModeToRigidBody()
     
     while True:
         for i in range(nb_points):
             min_dist = 99999999
             min_outPoint = [0.0, 0.0, 0.0]
             for j in range(3):
                 Locator[j].FindClosestPoint(a.GetPoint(i), outPoint, id1, id2, dist)
                 dis = npy.sqrt(npy.sum((npy.array(outPoint) - a.GetPoint(i)) ** 2))
                 if dis * w_mat[label[i]][j] < min_dist:
                     min_dist = dis * w_mat[label[i]][j]
                     min_outPoint = copy.deepcopy(outPoint)
                 
             closestp.SetPoint(i, min_outPoint)
             
         LandmarkTransform.SetSourceLandmarks(a)
         LandmarkTransform.SetTargetLandmarks(closestp)
         LandmarkTransform.Update()
         accumulate.Concatenate(LandmarkTransform.GetMatrix())
             
         iternum += 1
         
         for i in range(nb_points):
             a.GetPoint(i, p1)
             LandmarkTransform.InternalTransformPoint(p1, p2)
             b.SetPoint(i, p2)
         b, a = a, b
         
         if iternum >= MaxIterNum:
             break
     
     matrix = accumulate.GetMatrix()
     
     T = ml.mat([matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3)]).T
     R = ml.mat([[matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2)], 
                 [matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2)], 
                 [matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2)]]).I
     result_center_points[:, :3] = util.applyTransformForPoints(result_center_points[:, :3], npy.array([1.0, 1, 1]), npy.array([1.0, 1, 1]), R, T, ml.zeros([3, 1], dtype = npy.float32))
     new_trans_points[:, :3] = util.applyTransformForPoints(new_trans_points[:, :3], npy.array([1.0, 1, 1]), npy.array([1.0, 1, 1]), R, T, ml.zeros([3, 1], dtype = npy.float32))
     
     LandmarkTransform = vtk.vtkThinPlateSplineTransform()
     LandmarkTransform.SetBasisToR()
     iternum = 0
     # Non-rigid
     while True:
         for i in range(nb_points):
             min_dist = 99999999
             min_outPoint = [0.0, 0.0, 0.0]
             for j in range(3):
                 Locator[j].FindClosestPoint(a.GetPoint(i), outPoint, id1, id2, dist)
                 dis = npy.sqrt(npy.sum((npy.array(outPoint) - a.GetPoint(i)) ** 2))
                 if dis * w_mat[label[i]][j] < min_dist:
                     min_dist = dis * w_mat[label[i]][j]
                     min_outPoint = copy.deepcopy(outPoint)
                 
             closestp.SetPoint(i, min_outPoint)
             
         LandmarkTransform.SetSourceLandmarks(a)
         LandmarkTransform.SetTargetLandmarks(closestp)
         LandmarkTransform.Update()
         
         '''
         for i in range(result_center_points.shape[0]):
             LandmarkTransform.InternalTransformPoint([result_center_points[i, 0], result_center_points[i, 1], result_center_points[i, 2]], p2)
             result_center_points[i, :3] = p2
         '''
         for i in range(new_trans_points.shape[0]):
             LandmarkTransform.InternalTransformPoint([new_trans_points[i, 0], new_trans_points[i, 1], new_trans_points[i, 2]], p2)
             new_trans_points[i, :3] = p2
             
         iternum += 1
         if iternum >= 1:
             break
         
         for i in range(nb_points):
             a.GetPoint(i, p1)
             LandmarkTransform.InternalTransformPoint(p1, p2)
             b.SetPoint(i, p2)
         b, a = a, b
     
     time2 = time.time()
     
     if (fixed_bif >= 0) and (moving_bif >= 0):
         new_trans_points[:, 2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta)
         result_center_points[:, 2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta)
     new_trans_points[:, :3] /= fixed_res[:3]
     result_center_points[:, :3] /= fixed_res[:3]
     resultImage = movingData.getData().copy()
     
     sa = SurfaceErrorAnalysis(None)
     dataset = db.BasicData(npy.array([[[0]]]), fixedData.getInfo(), {'Contour': new_trans_points, 'Centerline': result_center_points})
     mean_dis, mean_whole, max_dis, max_whole = sa.analysis(dataset, point_data_fix = fixedData.getPointSet('Contour').copy(), useResult = True)
     del dataset
     print mean_dis
     print mean_whole
     
     if isTime:
         return resultImage, {'Contour': new_trans_points, 'Centerline': result_center_points}, [mean_dis, mean_whole], time2 - time1
     return resultImage, {'Contour': new_trans_points, 'Centerline': result_center_points}, [mean_dis, mean_whole]
  def __init__(self):
    self.toolTipToTool = slicer.util.getNode('toolTipToTool')
    self.pointerTipToReference = None
    self.targetCreatedTransformed = False
    self.firstFiducial = True

    if not self.toolTipToTool:
      self.toolTipToTool=slicer.vtkMRMLLinearTransformNode()
      self.toolTipToTool.SetName("toolTipToTool")
      m = vtk.vtkMatrix4x4()
      m.SetElement( 0, 0, 1 ) # Row 1
      m.SetElement( 0, 1, 0 )
      m.SetElement( 0, 2, 0 )
      m.SetElement( 0, 3, 0 )      
      m.SetElement( 1, 0, 0 )  # Row 2
      m.SetElement( 1, 1, 1 )
      m.SetElement( 1, 2, 0 )
      m.SetElement( 1, 3, 0 )       
      m.SetElement( 2, 0, 0 )  # Row 3
      m.SetElement( 2, 1, 0 )
      m.SetElement( 2, 2, 1 )
      m.SetElement( 2, 3, 0 )
      self.toolTipToTool.SetMatrixTransformToParent(m)
      slicer.mrmlScene.AddNode(self.toolTipToTool)

         
    self.line = slicer.util.getNode('Line')
    if not self.line:
      self.line = slicer.vtkMRMLModelNode()
      self.line.SetName('Line')
      linePolyData = vtk.vtkPolyData()
      self.line.SetAndObservePolyData(linePolyData)      
      modelDisplay = slicer.vtkMRMLModelDisplayNode()
      modelDisplay.SetSliceIntersectionVisibility(True)
      modelDisplay.SetColor(0,1,0)
      slicer.mrmlScene.AddNode(modelDisplay)      
      self.line.SetAndObserveDisplayNodeID(modelDisplay.GetID())      
      slicer.mrmlScene.AddNode(self.line)
      
    # VTK objects
    self.transformPolyDataFilter = vtk.vtkTransformPolyDataFilter()
    self.cellLocator = vtk.vtkCellLocator()

    # 3D View
    threeDWidget = slicer.app.layoutManager().threeDWidget(0)
    self.threeDView = threeDWidget.threeDView()
    
    self.callbackObserverTag = -1
    self.observerTag=None

    # Output Distance Label
    self.outputDistanceLabel=None

    
    import Viewpoint # Viewpoint Module must have been added to Slicer 
    self.viewpointLogic = Viewpoint.ViewpointLogic()

    # Camera transformations
    self.needleCameraToNeedle = slicer.util.getNode('needleCameraToNeedle')
    if not self.needleCameraToNeedle:
      self.needleCameraToNeedle=slicer.vtkMRMLLinearTransformNode()
      self.needleCameraToNeedle.SetName("needleCameraToNeedle")
      matrixNeedleCamera = vtk.vtkMatrix4x4()
      matrixNeedleCamera.SetElement( 0, 0, -0.05 ) # Row 1
      matrixNeedleCamera.SetElement( 0, 1, 0.09 )
      matrixNeedleCamera.SetElement( 0, 2, -0.99 )
      matrixNeedleCamera.SetElement( 0, 3, 60.72 )      
      matrixNeedleCamera.SetElement( 1, 0, -0.01 )  # Row 2
      matrixNeedleCamera.SetElement( 1, 1, 1 )
      matrixNeedleCamera.SetElement( 1, 2, 0.09 )
      matrixNeedleCamera.SetElement( 1, 3, 12.17 )       
      matrixNeedleCamera.SetElement( 2, 0, 1 )  # Row 3
      matrixNeedleCamera.SetElement( 2, 1, 0.01 )
      matrixNeedleCamera.SetElement( 2, 2, -0.05 )
      matrixNeedleCamera.SetElement( 2, 3, -7.26 )
      self.needleCameraToNeedle.SetMatrixTransformToParent(matrixNeedleCamera)
      slicer.mrmlScene.AddNode(self.needleCameraToNeedle)

    self.pointerCameraToPointer = slicer.util.getNode('pointerCameraToPointer')
    if not self.pointerCameraToPointer:
      self.pointerCameraToPointer=slicer.vtkMRMLLinearTransformNode()
      self.pointerCameraToPointer.SetName("pointerCameraToPointer")
      matrixPointerCamera = vtk.vtkMatrix4x4()
      matrixPointerCamera.SetElement( 0, 0, -0.05 ) # Row 1
      matrixPointerCamera.SetElement( 0, 1, 0.09 )
      matrixPointerCamera.SetElement( 0, 2, -0.99 )
      matrixPointerCamera.SetElement( 0, 3, 121.72 )      
      matrixPointerCamera.SetElement( 1, 0, -0.01 )  # Row 2
      matrixPointerCamera.SetElement( 1, 1, 1 )
      matrixPointerCamera.SetElement( 1, 2, 0.09 )
      matrixPointerCamera.SetElement( 1, 3, 17.17 )       
      matrixPointerCamera.SetElement( 2, 0, 1 )  # Row 3
      matrixPointerCamera.SetElement( 2, 1, 0.01 )
      matrixPointerCamera.SetElement( 2, 2, -0.05 )
      matrixPointerCamera.SetElement( 2, 3, -7.26 )
      self.pointerCameraToPointer.SetMatrixTransformToParent(matrixPointerCamera)
      slicer.mrmlScene.AddNode(self.pointerCameraToPointer)

    # Tranformations to fix models orientation
    self.needleModelToNeedleTip = slicer.util.getNode('needleModelToNeedleTip')
    if not self.needleModelToNeedleTip:
      self.needleModelToNeedleTip=slicer.vtkMRMLLinearTransformNode()
      self.needleModelToNeedleTip.SetName("needleModelToNeedleTip")
      matrixNeedleModel = vtk.vtkMatrix4x4()
      matrixNeedleModel.SetElement( 0, 0, -1 ) # Row 1
      matrixNeedleModel.SetElement( 0, 1, 0 )
      matrixNeedleModel.SetElement( 0, 2, 0 )
      matrixNeedleModel.SetElement( 0, 3, 0 )      
      matrixNeedleModel.SetElement( 1, 0, 0 )  # Row 2
      matrixNeedleModel.SetElement( 1, 1, 1 )
      matrixNeedleModel.SetElement( 1, 2, 0 )
      matrixNeedleModel.SetElement( 1, 3, 0 )       
      matrixNeedleModel.SetElement( 2, 0, 0 )  # Row 3
      matrixNeedleModel.SetElement( 2, 1, 0 )
      matrixNeedleModel.SetElement( 2, 2, -1 )
      matrixNeedleModel.SetElement( 2, 3, 0 )
      self.needleModelToNeedleTip.SetMatrixTransformToParent(matrixNeedleModel)
      slicer.mrmlScene.AddNode(self.needleModelToNeedleTip)

    self.pointerModelToPointerTip = slicer.util.getNode('pointerModelToPointerTip')
    if not self.pointerModelToPointerTip:
      self.pointerModelToPointerTip=slicer.vtkMRMLLinearTransformNode()
      self.pointerModelToPointerTip.SetName("pointerModelToPointerTip")
      matrixPointerModel = vtk.vtkMatrix4x4()
      matrixPointerModel.SetElement( 0, 0, 0 ) # Row 1
      matrixPointerModel.SetElement( 0, 1, 0 )
      matrixPointerModel.SetElement( 0, 2, 1 )
      matrixPointerModel.SetElement( 0, 3, 0 )      
      matrixPointerModel.SetElement( 1, 0, 0 )  # Row 2
      matrixPointerModel.SetElement( 1, 1, 1 )
      matrixPointerModel.SetElement( 1, 2, 0 )
      matrixPointerModel.SetElement( 1, 3, 0 )       
      matrixPointerModel.SetElement( 2, 0, -1 )  # Row 3
      matrixPointerModel.SetElement( 2, 1, 0 )
      matrixPointerModel.SetElement( 2, 2, 0 )
      matrixPointerModel.SetElement( 2, 3, 0 )
      self.pointerModelToPointerTip.SetMatrixTransformToParent(matrixPointerModel)
      slicer.mrmlScene.AddNode(self.pointerModelToPointerTip)


    self.fRBLToSLPR = slicer.util.getNode('FRBLToSLPR')    
    if not self.fRBLToSLPR:
      self.fRBLToSLPR = slicer.vtkMRMLLinearTransformNode()
      self.fRBLToSLPR.SetName('FRBLToSLPR')
      slicer.mrmlScene.AddNode(self.fRBLToSLPR)
      
    # Create fiducials to orientate model
    self.fiducialsFRBL = slicer.util.getNode('FiducialsFRBL')    
    if not self.fiducialsFRBL:
      self.fiducialsFRBL = slicer.vtkMRMLMarkupsFiducialNode()
      self.fiducialsFRBL.SetName('FiducialsFRBL')
      slicer.mrmlScene.AddNode(self.fiducialsFRBL)
      self.fiducialsFRBL.SetDisplayVisibility(False)
      
    self.fiducialsSLPR = slicer.util.getNode('FiducialsSLPR')    
    if not self.fiducialsSLPR:
      self.fiducialsSLPR = slicer.vtkMRMLMarkupsFiducialNode()
      self.fiducialsSLPR.SetName('FiducialsSLPR')
      self.fiducialsSLPR.AddFiducial(0, 100, 0)
      self.fiducialsSLPR.SetNthFiducialLabel(0, 'S')
      self.fiducialsSLPR.AddFiducial(-100, 0, 0)
      self.fiducialsSLPR.SetNthFiducialLabel(1, 'L')
      self.fiducialsSLPR.AddFiducial(0, -100, 0)
      self.fiducialsSLPR.SetNthFiducialLabel(2, 'P')
      self.fiducialsSLPR.AddFiducial(100, 0, 0)
      self.fiducialsSLPR.SetNthFiducialLabel(3, 'R')   
      slicer.mrmlScene.AddNode(self.fiducialsSLPR)
      self.fiducialsSLPR.SetDisplayVisibility(False)
Exemplo n.º 49
0
#---------------------------------------------------------
# Do the surface rendering
skinExtractor = vtk.vtkMarchingCubes()
skinExtractor.SetInputConnection(reader.GetOutputPort())
skinExtractor.SetValue(0,500)

skinNormals = vtk.vtkPolyDataNormals()
skinNormals.SetInputConnection(skinExtractor.GetOutputPort())
skinNormals.SetFeatureAngle(60.0)

skinStripper = vtk.vtkStripper()
skinStripper.SetMaximumLength(10)
skinStripper.SetInputConnection(skinNormals.GetOutputPort())

skinLocator = vtk.vtkCellLocator()
skinLocator.SetDataSet(skinStripper.GetOutput())
skinLocator.LazyEvaluationOn()

skinMapper = vtk.vtkPolyDataMapper()
skinMapper.SetInputConnection(skinStripper.GetOutputPort())
skinMapper.ScalarVisibilityOff()

skinProperty = vtk.vtkProperty()
skinProperty.SetColor(1.0,1.0,0.9)

skin = vtk.vtkActor()
skin.SetMapper(skinMapper)
skin.SetProperty(skinProperty)

#---------------------------------------------------------
Exemplo n.º 50
0
def renderIBC(filePrefix, imgLow, imgHigh):
    global picker, redCone, greenCone
    #
    # This example reads a volume dataset, extracts an isosurface that
    # represents the skin and displays it.
    #
    
    
    # The following reader is used to read a series of 2D slices (images)
    # that compose the volume. The slice dimensions are set, and the
    # pixel spacing. The data Endianness must also be specified. The reader
    # usese the FilePrefix in combination with the slice number to construct
    # filenames using the format FilePrefix.%d. (In this case the FilePrefix
    # is the root name of the file: quarter.)
    #vtkVolume16Reader v13R
    #  v13R SetDataDimensions 1388 1040
    #  v13R SetDataByteOrderToBigEndian 
    #  v13R SetFilePrefix  "IBC146h.R_s"
    #  v13R SetImageRange 0  44
    #  v13R SetDataSpacing  1 1 2
      
    # Image reader
    v13G = vtk.vtkTIFFReader()
    v13G.SetDataExtent(1, 1380, 1, 1030, imgLow, imgHigh)
    v13G.SetDataByteOrderToLittleEndian() 
    v13G.SetFilePrefix(filePrefix)
    v13G.SetDataSpacing(0.1, 0.1, 0.6)
    
    # Gaussian Smoothing
    gaus_v13G = vtk.vtkImageGaussianSmooth()
    gaus_v13G.SetDimensionality(3)
    gaus_v13G.SetStandardDeviation(1)
    gaus_v13G.SetRadiusFactors(1, 1, 1)
    gaus_v13G.SetInput(v13G.GetOutput())
    
    
    # Set up the volume rendering
    volumeMapper = vtk.vtkVolumeTextureMapper3D()
    volumeMapper.SetInput(v13G.GetOutput())
    
    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    
    
    # Surface rendering
    bactExtractor = vtk.vtkMarchingCubes()
    bactExtractor.SetInputConnection(gaus_v13G.GetOutputPort())
    bactExtractor.SetValue(0,20000)
    
#    bactNormals = vtk.vtkPolyDataNormals()
#    bactNormals.SetInputConnection(bactExtractor.GetOutputPort())
#    bactNormals.SetFeatureAngle(90.0)
#    
#    bactStripper = vtk.vtkStripper()
#    bactStripper.SetInputConnection(bactNormals.GetOutputPort())
#    
    bactLocator = vtk.vtkCellLocator()
    bactLocator.SetDataSet(bactExtractor.GetOutput())
    bactLocator.LazyEvaluationOn()
#    
#    bactMapper = vtk.vtkPolyDataMapper()
#    bactMapper.SetInputConnection(bactStripper.GetOutputPort())
#    bactMapper.ScalarVisibilityOff()
    
    
#    skinE_v13G = vtk.vtkContourFilter()
##    skinE_v13G = vtk.vtkMarchingCubes()
#    skinE_v13G.UseScalarTreeOn()
#    skinE_v13G.SetInput(gaus_v13G.GetOutput())
#    skinE_v13G.SetValue(0, 10000)
#    
    smooth_v13G = vtk.vtkSmoothPolyDataFilter()
    smooth_v13G.SetInput(bactExtractor.GetOutput())
    smooth_v13G.SetNumberOfIterations(50)
    
    deci_v13G = vtk.vtkDecimatePro()
    deci_v13G.SetInput(smooth_v13G.GetOutput())
    deci_v13G.SetTargetReduction(0.5)
    deci_v13G.PreserveTopologyOn()
    
    smoother_v13G = vtk.vtkSmoothPolyDataFilter()
    smoother_v13G.SetInput(deci_v13G.GetOutput())
    smoother_v13G.SetNumberOfIterations(50)
    
    skinNormals_v13G = vtk.vtkPolyDataNormals()
    skinNormals_v13G.SetInput(deci_v13G.GetOutput())
    skinNormals_v13G.SetFeatureAngle(60.0)
    
    
    skinStripper_v13G = vtk.vtkStripper()
    skinStripper_v13G.SetInput(skinNormals_v13G.GetOutput())
    
    
    skinMapper_v13G = vtk.vtkPolyDataMapper()
    skinMapper_v13G.SetInput(skinStripper_v13G.GetOutput())
    skinMapper_v13G.ScalarVisibilityOff()
    
    skin_v13G = vtk.vtkActor()
    skin_v13G.SetMapper(skinMapper_v13G)
    skin_v13G.GetProperty().SetDiffuseColor(0.2, 1, 0.2)
    skin_v13G.GetProperty().SetSpecular(.1)
    skin_v13G.GetProperty().SetSpecularPower(5)
    skin_v13G.GetProperty().SetOpacity(0.9)
    
    
    # It is convenient to create an initial view of the data. The FocalPoint
    # and Position form a vector direction. Later on (ResetCamera() method)
    # this vector is used to position the camera to look at the data in
    # this direction.
    aCamera = vtk.vtkCamera()
    aCamera.SetViewUp(0, 0, -1)
    aCamera.SetPosition(0, 1.1, 2)
    aCamera.SetFocalPoint(0, -0.25, 0)
    aCamera.ComputeViewPlaneNormal()
    
    
    
    # Actors are added to the renderer. An initial camera view is created.
    # The Dolly() method moves the camera towards the FocalPoint,
    # thereby enlarging the image.
    #aRenderer AddActor skin_v13R
    ren.AddActor(skin_v13G)
    ren.SetActiveCamera(aCamera)
    ren.ResetCamera() 
    aCamera.Dolly(1.0)
   
    
    # Note that when camera movement occurs (as it does in the Dolly()
    # method), the clipping planes often need adjusting. Clipping planes
    # consist of two planes: near and far along the view direction. The 
    # near plane clips out objects in front of the plane the far plane
    # clips out objects behind the plane. This way only what is drawn
    # between the planes is actually rendered.
    ren.ResetCameraClippingRange()
    
    
    # render
    renWin.Render()
    
    # CONE PICKER RENDER
    
    #---------------------------------------------------------
    # the cone points along the -x axis
    coneSource = vtk.vtkConeSource()
    coneSource.CappingOn()
    coneSource.SetHeight(2)
    coneSource.SetRadius(1)
    coneSource.SetResolution(11)
    coneSource.SetCenter(1,0,0)
    coneSource.SetDirection(-1,0,0)
    
    coneMapper = vtk.vtkDataSetMapper()
    coneMapper.SetInputConnection(coneSource.GetOutputPort())
    
    redCone = vtk.vtkActor()
    redCone.PickableOff()
    redCone.SetMapper(coneMapper)
    redCone.GetProperty().SetColor(1,0,0)
    
    greenCone = vtk.vtkActor()
    greenCone.PickableOff()
    greenCone.SetMapper(coneMapper)
    greenCone.GetProperty().SetColor(0,1,0)
    
    # Add the two cones (or just one, if you want)
    ren.AddViewProp(redCone)
    ren.AddViewProp(greenCone)
    
    #---------------------------------------------------------
    # the picker
    picker = vtk.vtkVolumePicker()
    picker.SetTolerance(1e-6)
    picker.SetVolumeOpacityIsovalue(0.1)
    # locator is optional, but improves performance for large polydata
    picker.AddLocator(bactLocator)
    
    #---------------------------------------------------------
    # custom interaction
    iren.AddObserver("MouseMoveEvent", MoveCursor)

    
    # END CONE PICKER RENDER
    
    # initialize and start the interactor
    iren.Initialize()
    iren.Start()
Exemplo n.º 51
0
 def register(self, fixedData, movingData, index = -1, discard = False, delta = 0, fov = 9999999.0,
         down_fix = 1, down_mov = 1, occ = 9999999.0, op = False, useMask = False, isTime = False, MaxRate = 0.2,
         aug = False, distance_fix = 0.3, distance_mov = 0.1):
     time1 = time.time()
     if index == -1:
         index = self.gui.getDataIndex({'Contour': 0, 'Centerline': 1}, 'Select the object')
     if index is None:
         return None, None, None
     if index == 0:
         fixed_points = fixedData.getPointSet('Contour').copy()
         moving_points = movingData.getPointSet('Contour').copy()
     else:
         fixed_points = fixedData.getPointSet('Centerline').copy()
         moving_points = movingData.getPointSet('Centerline').copy()
     
     fixed_bif = db.getBifurcation(fixed_points)
     moving_bif = db.getBifurcation(moving_points)
     
     if useMask:
         mask_points = movingData.getPointSet('Mask')
         for point in mask_points:
             moving_points = npy.delete(moving_points, npy.where((npy.abs(moving_points[:, 2] - point[2]) < 0.0001) & (npy.round(moving_points[:, -1]) == point[3])), axis = 0)
         
     fixed_res = fixedData.getResolution().tolist()
     moving_res = movingData.getResolution().tolist()
     fixed_points = fixed_points[npy.where(fixed_points[:, 0] >= 0)]
     moving_points = moving_points[npy.where(moving_points[:, 0] >= 0)]
     
     # Use the bifurcation as the initial position
     if (fixed_bif < 0) or (moving_bif < 0):
         fixed_min = 0
     
     # Augmentation of pointset
     fixed = fixed_points.copy()
     moving = moving_points.copy()
     
     if index == 1 and aug:
         fixed = util.augmentCenterline(fixed, 1, 10)
         moving = util.augmentCenterline(moving, 1, 10)
         fix_dis = util.getAxisSin(fixed, 3 / fixed_res[2]) * distance_fix
         mov_dis = util.getAxisSin(moving, 3 / moving_res[2]) * distance_mov
         fixed = util.resampleCenterline(fixed, fix_dis / fixed_res[2])
         moving = util.resampleCenterline(moving, mov_dis / moving_res[2])
     
     fixed = fixed[npy.cast[npy.int32](npy.abs(fixed[:, 2] - fixed_bif)) % down_fix == 0]
     moving = moving[npy.cast[npy.int32](npy.abs(moving[:, 2] - moving_bif)) % down_mov == 0]
     
     fixed[:, :3] *= fixed_res[:3]
     moving[:, :3] *= moving_res[:3]
     
     if (fixed_bif >= 0) and (moving_bif >= 0):
         fixed[:, 2] -= (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta)
     
     # Prepare for ICP
     LandmarkTransform = vtk.vtkLandmarkTransform()
     LandmarkTransform.SetModeToRigidBody()
     MaxIterNum = 50
     #MaxNum = 600
     MaxNum = int(MaxRate * moving.shape[0] + 0.5)
     
     targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()]
     targetVertices = [vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray()]
     target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()]
     Locator = [vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator()]
     if index == 0:
         if not op:
             label_dis = [3, 3, 3]
         else:
             label_dis = [3, 2, 1]
     else:
         if op:
             label_dis = [3, 3, 3]
         else:
             label_dis = [3, 2, 1]
         
     
     for i in range(3):
         for x in fixed[npy.round(fixed[:, 3]) != label_dis[i]]:
             id = targetPoints[i].InsertNextPoint(x[0], x[1], x[2])
             targetVertices[i].InsertNextCell(1)
             targetVertices[i].InsertCellPoint(id)
         target[i].SetPoints(targetPoints[i])
         target[i].SetVerts(targetVertices[i])
         
         Locator[i].SetDataSet(target[i])
         Locator[i].SetNumberOfCellsPerBucket(1)
         Locator[i].BuildLocator()
     
     step = 1
     if moving.shape[0] > MaxNum:
         ind = moving[:, 2].argsort()
         moving = moving[ind, :]
         step = moving.shape[0] / MaxNum
     nb_points = moving.shape[0] / step
     
     accumulate = vtk.vtkTransform()
     accumulate.PostMultiply()
     
     points1 = vtk.vtkPoints()
     points1.SetNumberOfPoints(nb_points)
     
     label = npy.zeros([MaxNum * 2], dtype = npy.int8)
     
     j = 0
     for i in range(nb_points):
         points1.SetPoint(i, moving[j][0], moving[j][1], moving[j][2])
         label[i] = moving[j][3]
         j += step
     
     closestp = vtk.vtkPoints()
     closestp.SetNumberOfPoints(nb_points)
     points2 = vtk.vtkPoints()
     points2.SetNumberOfPoints(nb_points)
     
     id1 = id2 = vtk.mutable(0)
     dist = vtk.mutable(0.0)
     outPoint = [0.0, 0.0, 0.0]
     p1 = [0.0, 0.0, 0.0]
     p2 = [0.0, 0.0, 0.0]
     iternum = 0
     a = points1
     b = points2
     
     '''
     path = sys.argv[0]
     if os.path.isfile(path):
         path = os.path.dirname(path)
     path += '/Data/Transform'
     wfile = open("%s/transform.txt" % path, 'w')
     
     matrix = accumulate.GetMatrix()
     T = ml.mat([matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3)]).T;
     R = ml.mat([[matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2)], 
                 [matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2)], 
                 [matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2)]]).I
     if (fixed_bif >= 0) and (moving_bif >= 0):
         T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta)
     saveTransform(wfile, T, R)
     '''
     
     while True:
         for i in range(nb_points):
             Locator[label[i]].FindClosestPoint(a.GetPoint(i), outPoint, id1, id2, dist)
             closestp.SetPoint(i, outPoint)
             
         LandmarkTransform.SetSourceLandmarks(a)
         LandmarkTransform.SetTargetLandmarks(closestp)
         LandmarkTransform.Update()
         
         accumulate.Concatenate(LandmarkTransform.GetMatrix())
         
         iternum += 1
         if iternum >= MaxIterNum:
             break
         
         dist_err = 0
         for i in range(nb_points):
             a.GetPoint(i, p1)
             LandmarkTransform.InternalTransformPoint(p1, p2)
             b.SetPoint(i, p2)
             dist_err += npy.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 + (p1[2] - p2[2]) ** 2)
         dist_err /= nb_points
         print "iter = %d: %f" % (iternum, dist_err)
         '''
         matrix = accumulate.GetMatrix()
         T = ml.mat([matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3)]).T;
         R = ml.mat([[matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2)], 
                     [matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2)], 
                     [matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2)]]).I;
         if (fixed_bif >= 0) and (moving_bif >= 0):
             T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2])
         saveTransform(wfile, T, R)
         '''
         b, a = a, b
     time2 = time.time()
     #wfile.close()
     # Get the result transformation parameters
     matrix = accumulate.GetMatrix()
     
     T = ml.mat([matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3)]).T
     R = ml.mat([[matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2)], 
                 [matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2)], 
                 [matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2)]]).I
     
     #T = ml.mat([0, 0, 0]).T
     #R = ml.mat([[1, 0, 0], [0, 1, 0], [0, 0, 1]]).T
     if (fixed_bif >= 0) and (moving_bif >= 0):
         T[2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta)
     
     # Resample the moving contour
     moving_points = movingData.getPointSet('Contour').copy()
     moving_center = movingData.getPointSet('Centerline').copy()
     #new_trans_points, result_center_points = util.resliceTheResultPoints(moving_points, moving_center, 20, moving_res, fixed_res, discard, R, T)
     new_trans_points, result_center_points = moving_points, moving_center
     result_center_points[:, :3] = util.applyTransformForPoints(result_center_points[:, :3], moving_res, fixed_res, R, T, ml.zeros([3, 1], dtype = npy.float32))
     new_trans_points[:, :3] = util.applyTransformForPoints(new_trans_points[:, :3], moving_res, fixed_res, R, T, ml.zeros([3, 1], dtype = npy.float32))
     T = -T
     T = R * T
     
     transform = sitk.Transform(3, sitk.sitkAffine)
     para = R.reshape(1, -1).tolist()[0] + T.T.tolist()[0]
     transform.SetParameters(para)
     
     movingImage = movingData.getSimpleITKImage()
     fixedImage = fixedData.getSimpleITKImage()
     resultImage = sitk.Resample(movingImage, fixedImage, transform, sitk.sitkLinear, 0, sitk.sitkFloat32)
     
     if isTime:
         return sitk.GetArrayFromImage(resultImage), {'Contour': new_trans_points, 'Centerline': result_center_points}, para + [0, 0, 0], time2 - time1
     return sitk.GetArrayFromImage(resultImage), {'Contour': new_trans_points, 'Centerline': result_center_points}, para + [0, 0, 0]
Exemplo n.º 52
0
 def analysis(self, data, point_data_fix = None):
     if point_data_fix is None:
         point_data_fix = self.gui.dataModel[data.getFixedIndex()].getPointSet('Centerline').copy()
     point_data_result = data.getPointSet('Centerline').copy()
     
     self.spacing = data.getResolution().tolist()
     point_data_fix = point_data_fix[point_data_fix[:, 0] >= 0]
     point_data_result = point_data_result[point_data_result[:, 0] >= 0]
     point_data_fix[:, :3] *= self.spacing[:3]
     point_data_result[:, :3] *= self.spacing[:3]
     
     ind = point_data_fix[:, 2].argsort()
     point_data_fix = point_data_fix[ind]
     
     Locator = [vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator()]
     targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()]
     targetVertices = [vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray()]
     target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()]
     
     for cnt in range(1, 3):
         resampled_points = point_data_fix[npy.where(npy.round(point_data_fix[:, -1]) != 3 - cnt)]
         
         count = resampled_points.shape[0]
         points = vtk.vtkPoints()
         for i in range(count):
             if i + 1 < count and resampled_points[i, 3] != resampled_points[i + 1, 3]: # bifurcation point
                 continue
             points.InsertPoint(i, resampled_points[i, 0], resampled_points[i, 1], resampled_points[i, 2])
 
         para_spline = vtk.vtkParametricSpline()
         para_spline.SetPoints(points)
         para_spline.ClosedOff()
         
         numberOfOutputPoints = count * 50
         
         for i in range(0, numberOfOutputPoints):
             t = i * 1.0 / numberOfOutputPoints
             pt = [0.0, 0.0, 0.0]
             para_spline.Evaluate([t, t, t], pt, [0] * 9)
             id = targetPoints[0].InsertNextPoint(pt[0], pt[1], pt[2])
             targetVertices[0].InsertNextCell(1)
             targetVertices[0].InsertCellPoint(id)
             id = targetPoints[cnt].InsertNextPoint(pt[0], pt[1], pt[2])
             targetVertices[cnt].InsertNextCell(1)
             targetVertices[cnt].InsertCellPoint(id)
     
     for i in range(3):
         target[i].SetPoints(targetPoints[i])
         target[i].SetVerts(targetVertices[i])
         
         Locator[i].SetDataSet(target[i])
         Locator[i].SetNumberOfCellsPerBucket(1)
         Locator[i].BuildLocator()
     
     id1 = id2 = vtk.mutable(0)
     dist = vtk.mutable(0.0)
     outPoint = [0.0, 0.0, 0.0]
     
     cnt_num = npy.array([0, 0, 0])
     mean_dis = npy.array([0.0, 0.0, 0.0])
     max_dis = npy.array([0.0, 0.0, 0.0])
     
     for pt in point_data_result:
         cnt = int(pt[-1] + 0.5)
         Locator[cnt].FindClosestPoint(pt[:3].tolist(), outPoint, id1, id2, dist)
         dis = npy.sqrt(npy.sum((npy.array(outPoint) - pt[:3]) ** 2))
         mean_dis[cnt] += dis
         max_dis[cnt] = npy.max([max_dis[cnt], dis])
         cnt_num[cnt] += 1
     
     cnt_total = npy.sum(cnt_num)
     mean_whole = npy.sum(mean_dis) / cnt_total
     mean_dis /= cnt_num
     mean_dis[mean_dis != mean_dis] = 0 # Replace the NAN in the mean distance
     max_whole = npy.max(max_dis)
     
     if self.gui is not None:
         message = "Error on Vessel 0: %0.2fmm (Total %d slices)\nError on Vessel 1: %0.2fmm (Total %d slices)\nError on Vessel 2: %0.2fmm (Total %d slices)\nWhole Error: %0.2fmm (Total %d slices)\n" \
             % (mean_dis[0], cnt_num[0], mean_dis[1], cnt_num[1], mean_dis[2], cnt_num[2], mean_whole, cnt_total) + \
             "-----------------------------------------------------------------------------\n" + \
             "Max Error on Vessel 0: %0.2fmm\nMax Error on Vessel 1: %0.2fmm\nMax Error on Vessel 2: %0.2fmm\nTotal Max Error: %0.2fmm" \
             % (max_dis[0], max_dis[1], max_dis[2], npy.max(max_dis));
         self.gui.showErrorMessage("Centerline Registration Error", message)
     return mean_dis, mean_whole, max_dis, max_whole
Exemplo n.º 53
0
    def analysis(self, data, point_data_fix = None, point_data_mov = None, point_data_mask = None, spacing_mov = None, useResult = False):
        if point_data_fix is None:
            point_data_fix = self.gui.dataModel[data.getFixedIndex()].getPointSet('Contour').copy()
            point_data_mov = self.gui.dataModel[data.getMovingIndex()].getPointSet('Contour').copy()
            point_data_mask = self.gui.dataModel[data.getMovingIndex()].getPointSet('Mask').copy()
            spacing_mov = self.gui.dataModel[data.getMovingIndex()].getResolution().tolist()
        
        self.spacing = data.getResolution().tolist()
        point_data_fix = point_data_fix[point_data_fix[:, 0] >= 0]
        bif = db.getBifurcation(point_data_fix)
        point_data_fix = util.augmentPointset(point_data_fix, 3, -1, bif, nn = 20)
        point_data_fix[:, :3] *= self.spacing[:3]
        if point_data_mov is not None:
            point_data_mov = point_data_mov[point_data_mov[:, 0] >= 0]

        if not useResult:
            para = npy.array(data.info.getData('transform')).flatten()
            point_data_result = point_data_mov.copy()
            for point in point_data_mask:
                point_data_result = npy.delete(point_data_result, npy.where((npy.abs(point_data_result[:, 2] - point[2]) < 0.0001) & (npy.round(point_data_result[:, -1]) == point[3])), axis = 0)
            point_data_result[:, :3] *= spacing_mov[:3]
            
            R = ml.mat(para[:9]).reshape(3, 3)
            T = ml.mat(para[9:12]).T
            if para.shape[0] > 12:
                C = ml.mat(para[12:]).T
            else:
                C = ml.zeros([3, 1], dtype = npy.float32)
            T = R.I * T
            T = -T
            point_data_result[:, :3] = util.applyTransformForPoints(point_data_result[:, :3], npy.array([1.0, 1, 1]), npy.array([1.0, 1, 1]), R, T, C)
        else:
            point_data_result = data.getPointSet('Contour').copy()
            point_data_result = point_data_result[point_data_result[:, -1] >= 0]
            point_data_result[:, :3] *= self.spacing[:3]
        
        targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()]
        targetVertices = [vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray()]
        target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()]
        Locator = [vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator()]
        
        label_dis = [3, 2, 1]
        
        for i in range(3):
            for x in point_data_fix[npy.round(point_data_fix[:, 3]) != label_dis[i]]:
                id = targetPoints[i].InsertNextPoint(x[0], x[1], x[2])
                targetVertices[i].InsertNextCell(1)
                targetVertices[i].InsertCellPoint(id)
            target[i].SetPoints(targetPoints[i])
            target[i].SetVerts(targetVertices[i])
            
            Locator[i].SetDataSet(target[i])
            Locator[i].SetNumberOfCellsPerBucket(1)
            Locator[i].BuildLocator()
        
        '''
        Locator = vtk.vtkCellLocator()
        targetPoints = vtk.vtkPoints()
        targetVertices = vtk.vtkCellArray()
        target = vtk.vtkPolyData()
        
        for x in point_data_fix:
            id = targetPoints.InsertNextPoint(x[0], x[1], x[2])
            targetVertices.InsertNextCell(1)
            targetVertices.InsertCellPoint(id)
        
        target.SetPoints(targetPoints)
        target.SetVerts(targetVertices)
        
        Locator.SetDataSet(target)
        Locator.SetNumberOfCellsPerBucket(1)
        Locator.BuildLocator()
        '''
        
        id1 = id2 = vtk.mutable(0)
        dist = vtk.mutable(0.0)
        outPoint = [0.0, 0.0, 0.0]
        
        cnt_num = npy.array([0, 0, 0])
        mean_dis = npy.array([0.0, 0.0, 0.0])
        max_dis = npy.array([0.0, 0.0, 0.0])
        
        for pt in point_data_result:
            cnt = int(pt[-1] + 0.5)
            Locator[cnt].FindClosestPoint(pt[:3].tolist(), outPoint, id1, id2, dist)
            dis = npy.sqrt(npy.sum((npy.array(outPoint) - pt[:3]) ** 2))
            mean_dis[cnt] += dis
            max_dis[cnt] = npy.max([max_dis[cnt], dis])
            cnt_num[cnt] += 1
        
        cnt_total = npy.sum(cnt_num)
        mean_whole = npy.sum(mean_dis) / cnt_total
        mean_dis /= cnt_num
        mean_dis[mean_dis != mean_dis] = 0 # Replace the NAN in the mean distance
        max_whole = npy.max(max_dis)
        
        if self.gui is not None:
            message = "Error on Vessel 0: %0.2fmm (Total %d slices)\nError on Vessel 1: %0.2fmm (Total %d slices)\nError on Vessel 2: %0.2fmm (Total %d slices)\nWhole Error: %0.2fmm (Total %d slices)\n" \
                % (mean_dis[0], cnt_num[0], mean_dis[1], cnt_num[1], mean_dis[2], cnt_num[2], mean_whole, cnt_total) + \
                "-----------------------------------------------------------------------------\n" + \
                "Max Error on Vessel 0: %0.2fmm\nMax Error on Vessel 1: %0.2fmm\nMax Error on Vessel 2: %0.2fmm\nTotal Max Error: %0.2fmm" \
                % (max_dis[0], max_dis[1], max_dis[2], npy.max(max_dis));
            self.gui.showErrorMessage("Centerline Registration Error", message)
        return mean_dis, mean_whole, max_dis, max_whole
volume.SetProperty(volumeProperty)

# ---------------------------------------------------------
# Do the surface rendering
boneExtractor = vtk.vtkMarchingCubes()
boneExtractor.SetInputConnection(reader.GetOutputPort())
boneExtractor.SetValue(0, 1150)

boneNormals = vtk.vtkPolyDataNormals()
boneNormals.SetInputConnection(boneExtractor.GetOutputPort())
boneNormals.SetFeatureAngle(60.0)

boneStripper = vtk.vtkStripper()
boneStripper.SetInputConnection(boneNormals.GetOutputPort())

boneLocator = vtk.vtkCellLocator()
boneLocator.SetDataSet(boneExtractor.GetOutput())
boneLocator.LazyEvaluationOn()

boneMapper = vtk.vtkPolyDataMapper()
boneMapper.SetInputConnection(boneStripper.GetOutputPort())
boneMapper.ScalarVisibilityOff()

boneProperty = vtk.vtkProperty()
boneProperty.SetColor(1.0, 1.0, 0.9)

bone = vtk.vtkActor()
bone.SetMapper(boneMapper)
bone.SetProperty(boneProperty)

# ---------------------------------------------------------
Exemplo n.º 55
0
    def Render(self, volumeReader):
        """
        This method attempts to tesselate the image data.
        
        :@type volumeReader: data.imageIO.base.VolumeImageReader
        :@param volumeReader: This object handles opening image data and 
                              passing it to the appropriate VTK image container
        :@rtype: 2-tuple
        :@return: The vtkActor created from tesselated image data and a 
                  vtkLocator for improving picking operations.
        """
        if self.imageSetID is None: return        
        
        self.volumeReader = volumeReader
        self.vtkReader = volumeReader.LoadVTKReader(self.dataSpacing)
        
        # Gaussian Smoothing
        self.gaussFilter = vtk.vtkImageGaussianSmooth()
        self.gaussFilter.SetDimensionality(3)
        self.gaussFilter.SetStandardDeviation(1)
        self.gaussFilter.SetRadiusFactors(1, 1, 1)
        self.gaussFilter.SetInput(self.vtkReader.GetOutput())
        
        # VOI Extractor
        self.voi = vtk.vtkExtractVOI()
        self.voi.SetInputConnection(self.gaussFilter.GetOutputPort())
#        self.voi.SetInputConnection(self.vtkReader.GetOutputPort())
        self.voi.SetVOI(self.volumeReader.VolumeExtents)
        
        # Surface rendering
        self.bactExtractor = vtk.vtkMarchingCubes()
        self.bactExtractor.GenerateValues(1, self.isocontourLevel)
        self.bactExtractor.ComputeNormalsOff()
        self.bactExtractor.SetInputConnection(self.voi.GetOutputPort())

        # surface rendering with dividing cubes
#        self.bactExtractor = vtk.vtkRecursiveDividingCubes()
#        self.bactExtractor.SetInputConnection(self.voi.GetOutputPort())
#        self.bactExtractor.SetValue(self.isocontourLevel[0])
#        self.bactExtractor.SetDistance(0.5)
#        self.bactExtractor.SetIncrement(2)

        # Smooth the mesh
        relaxedMesh = vtk.vtkSmoothPolyDataFilter()
        relaxedMesh.SetNumberOfIterations(50)
        relaxedMesh.SetInput(self.bactExtractor.GetOutput())

        # Calculate normals
        meshNormals = vtk.vtkPolyDataNormals()
        meshNormals.SetFeatureAngle(60.0)
        meshNormals.SetInput(relaxedMesh.GetOutput())

        # Restrip mesh after normal computation
        restrippedMesh = vtk.vtkStripper()
        restrippedMesh.SetInput(meshNormals.GetOutput())
        
        # Convert mesh to graphics primitives
        self.meshMapper = vtk.vtkPolyDataMapper()
        self.meshMapper.ScalarVisibilityOff()
        self.meshMapper.SetInput(restrippedMesh.GetOutput())
        
        # Finally create a renderable object "Actor" 
        # that can be passed to the render window
        self.ibcActor = vtk.vtkActor()
        self.ibcActor.SetMapper(self.meshMapper)
        ibcColor = DataStore.GetImageSet(self.imageSetID).color
        self.ibcActor.GetProperty().SetDiffuseColor(ibcColor.r, ibcColor.g, ibcColor.b)
        self.ibcActor.GetProperty().SetSpecular(.1)
        self.ibcActor.GetProperty().SetSpecularPower(5)
        self.ibcActor.GetProperty().SetOpacity(1)
        self.ibcActor.SetVisibility(boolInt(self.visible))
        
        self.renderer.AddActor(self.ibcActor)
        
        # Optional Locator to help the ray traced picker
        self.bactLocator = vtk.vtkCellLocator()
        self.bactLocator.SetDataSet(restrippedMesh.GetOutput())
        self.bactLocator.LazyEvaluationOn()
        
        return self.bactLocator