Exemple #1
0
def jaccard3D_pd(pd1,pd2):
    """
    computes the jaccard distance error for two polydata objects

    returns (error) float
    """
    union = vtk.vtkBooleanOperationPolyDataFilter()
    union.SetOperationToUnion()
    union.SetInputData(0,pd1)
    union.SetInputData(1,pd2)
    union.Update()
    u = union.GetOutput()
    massUnion = vtk.vtkMassProperties()
    massUnion.SetInputData(u)

    intersection = vtk.vtkBooleanOperationPolyDataFilter()
    intersection.SetOperationToIntersection()
    intersection.SetInputData(0,pd1)
    intersection.SetInputData(1,pd2)
    intersection.Update()
    i = intersection.GetOutput()
    massIntersection = vtk.vtkMassProperties()
    massIntersection.SetInputData(i)

    return 1 - massIntersection.GetVolume()/massUnion.GetVolume()
def obj(x,sF,devF,R,sv,mv,tv,material,spatial,rc,sc):
    nF = np.dot(R,x[0]*sF)+np.dot(R,x[1]*devF)
    #Make a copy of material configuration and deform this with nF
    nm = vtk.vtkPolyData()
    nm.DeepCopy(material)
    pcoords = vtk.vtkFloatArray()
    pcoords.SetNumberOfComponents(3)
    pcoords.SetNumberOfTuples(nm.GetNumberOfPoints())
    for i in xrange(nm.GetNumberOfPoints()):
        p = [0.,0.,0.]
        nm.GetPoint(i,p)
        p = np.dot(nF,p-rc)
        p.flatten()
        pcoords.SetTuple3(i,p[0]+sc[0],p[1]+sc[1],p[2]+sc[2])

    points = vtk.vtkPoints()
    points.SetData(pcoords)
    nm.SetPoints(points)
    nm.GetPoints().Modified()

    #calculate both the intersection and the union of the two polydata
    intersect = vtk.vtkBooleanOperationPolyDataFilter()
    intersect.SetOperation(1)
    intersect.SetInputData(0,nm)
    intersect.SetInputData(1,spatial)
    intersect.Update()

    union = vtk.vtkBooleanOperationPolyDataFilter()
    union.SetOperation(0)
    union.SetInputData(0,nm)
    union.SetInputData(1,spatial)
    union.Update()

    unionmass = vtk.vtkMassProperties()
    unionmass.SetInputConnection(union.GetOutputPort())
    vol_union = unionmass.GetVolume()

    if intersect.GetOutput().GetNumberOfPoints() > 0:
        intmass = vtk.vtkMassProperties()
        intmass.SetInputConnection(intersect.GetOutputPort())
        vol_int = intmass.GetVolume()
    else:
        #penalize with distance between centroids 
        w = sc.T-np.dot(nF,rc.T)
        c = np.linalg.norm(w)
        vol_int = c*vol_union 

    diff = max([abs(sv-vol_int),abs(sv-vol_union)])
    return diff
def obj(x, sF, devF, R, sv, mv, tv, material, spatial, rc, sc):
    nF = np.dot(R, x[0] * sF) + np.dot(R, x[1] * devF)
    #Make a copy of material configuration and deform this with nF
    nm = vtk.vtkPolyData()
    nm.DeepCopy(material)
    pcoords = vtk.vtkFloatArray()
    pcoords.SetNumberOfComponents(3)
    pcoords.SetNumberOfTuples(nm.GetNumberOfPoints())
    for i in xrange(nm.GetNumberOfPoints()):
        p = [0., 0., 0.]
        nm.GetPoint(i, p)
        p = np.dot(nF, p - rc)
        p.flatten()
        pcoords.SetTuple3(i, p[0] + sc[0], p[1] + sc[1], p[2] + sc[2])

    points = vtk.vtkPoints()
    points.SetData(pcoords)
    nm.SetPoints(points)
    nm.GetPoints().Modified()

    #calculate both the intersection and the union of the two polydata
    intersect = vtk.vtkBooleanOperationPolyDataFilter()
    intersect.SetOperation(1)
    intersect.SetInputData(0, nm)
    intersect.SetInputData(1, spatial)
    intersect.Update()

    union = vtk.vtkBooleanOperationPolyDataFilter()
    union.SetOperation(0)
    union.SetInputData(0, nm)
    union.SetInputData(1, spatial)
    union.Update()

    unionmass = vtk.vtkMassProperties()
    unionmass.SetInputConnection(union.GetOutputPort())
    vol_union = unionmass.GetVolume()

    if intersect.GetOutput().GetNumberOfPoints() > 0:
        intmass = vtk.vtkMassProperties()
        intmass.SetInputConnection(intersect.GetOutputPort())
        vol_int = intmass.GetVolume()
    else:
        #penalize with distance between centroids
        w = sc.T - np.dot(nF, rc.T)
        c = np.linalg.norm(w)
        vol_int = c * vol_union

    diff = max([abs(sv - vol_int), abs(sv - vol_union)])
    return diff
Exemple #4
0
def computeDiceDistance(mesh1Path, mesh2Path):
    if mesh1Path == mesh2Path:
        return 1.
    #Reading
    reader1 = vtkPolyDataReader()
    reader1.SetFileName(mesh1Path)
    reader1.Update()
    reader2 = vtkPolyDataReader()
    reader2.SetFileName(mesh2Path)
    reader2.Update()
    #First volume
    mass1 = vtkMassProperties()
    mass1.SetInputConnection(reader1.GetOutputPort())
    mass1.Update()
    volume1 = mass1.GetVolume()
    #Second volume
    mass2 = vtkMassProperties()
    mass2.SetInputConnection(reader2.GetOutputPort())
    mass2.Update()
    volume2 = mass2.GetVolume()
    #Intersection
    # intersectionOperation = vtkIntersectionPolyDataFilter()
    intersectionOperation = vtkBooleanOperationPolyDataFilter()
    intersectionOperation.SetOperationToIntersection()
    intersectionOperation.SetInputConnection(0, reader1.GetOutputPort())
    intersectionOperation.SetInputConnection(1, reader2.GetOutputPort())
    intersectionOperation.Update()
    #Volume of the intersection
    massInter = vtkMassProperties()
    massInter.SetInputConnection(intersectionOperation.GetOutputPort())
    massInter.Update()
    intersectionVolume = massInter.GetVolume()
    dice = 2 * intersectionVolume / (volume1 + volume2)
    assert 0 <= dice <= 1, "Warning : suspicious behavior detected in the intersection filter."
    return dice
Exemple #5
0
def boolean_vtk_polydata(poly1, poly2, keyword):
    """
    Apply VTK boolean operation on two VTK PolyData

    Args:
        poly1: first VTK PolyData
        poly2: second VTK PolyData
        keywords: str union, intersection, difference
    Returns:
        poly: resulted VTK PolyData
    """

    boolean = vtk.vtkBooleanOperationPolyDataFilter()
    if keyword == "union":
        boolean.SetOperationToUnion()
    elif keyword == "intersection":
        boolean.SetOperationToIntersection()
    elif keyword == "difference":
        boolean.SetOperationToDifference()
    else:
        raise ValueError("Keyword option is not supporte.")

    boolean.SetInputData(0, poly1)
    boolean.SetInputData(1, poly2)
    boolean.Update()

    return boolean.GetOutput()
Exemple #6
0
    def BooleanCut(self, cut, tolerance=1E-5, inplace=False):
        """
        Performs a Boolean cut using another mesh.

        Parameters
        ----------
        cut : vtkInterface.PolyData
            Mesh making the cut

        inplace : bool, optional
            Updates mesh in-place while returning nothing.

        Returns
        -------
        mesh : vtkInterface.PolyData
            The cut mesh when inplace=False

        """
        bfilter = vtk.vtkBooleanOperationPolyDataFilter()
        bfilter.SetOperationToIntersection()
        bfilter.SetInputData(1, cut)
        bfilter.SetInputData(0, self)
        bfilter.ReorientDifferenceCellsOff()
        bfilter.SetTolerance(tolerance)
        bfilter.Update()

        if inplace:
            self.Overwrite(bfilter.GetOutput())
        else:
            return PolyData(bfilter.GetOutput())
Exemple #7
0
def booleanOperation(actor1, actor2, operation='plus', c=None, alpha=1,
                     wire=False, bc=None, legend=None, texture=None):
    '''Volumetric union, intersection and subtraction of surfaces.

    [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/boolean.py)        
    '''
    try:
        bf = vtk.vtkBooleanOperationPolyDataFilter()
    except AttributeError:
        vc.printc('Boolean operation only possible for vtk version >= 8', c='r')
        return None
    poly1 = actor1.polydata(True)
    poly2 = actor2.polydata(True)
    if operation.lower() == 'plus':
        bf.SetOperationToUnion()
    elif operation.lower() == 'intersect':
        bf.SetOperationToIntersection()
    elif operation.lower() == 'minus':
        bf.SetOperationToDifference()
        bf.ReorientDifferenceCellsOn()
    bf.SetInputData(0, poly1)
    bf.SetInputData(1, poly2)
    bf.Update()
    actor = Actor(bf.GetOutput(), c, alpha, wire, bc, legend, texture)
    return actor
Exemple #8
0
  def run(self, inputModel1, inputModel2, outputModel, operationIndex):
    """
    Run the actual algorithm
    """

    if not self.isValidInputOutputData(inputModel1, inputModel2, outputModel):
      slicer.util.errorDisplay('Input volume is the same as output volume. Choose a different output volume.')
      return False

    logging.info('Processing started')

    triangleFilter1 = vtk.vtkTriangleFilter()
    triangleFilter1.SetInputData(inputModel1.GetPolyData())
    triangleFilter1.Update()
    triangleFilter2 = vtk.vtkTriangleFilter()
    triangleFilter2.SetInputData(inputModel2.GetPolyData())
    triangleFilter2.Update()
    booleanFilter = vtk.vtkBooleanOperationPolyDataFilter()
    if operationIndex == 0:
      booleanFilter.SetOperationToIntersection()
    elif operationIndex == 1:
      booleanFilter.SetOperationToDifference()
    elif operationIndex == 2:
      booleanFilter.SetOperationToUnion()
    booleanFilter.SetInputData(0, triangleFilter1.GetOutput())
    booleanFilter.SetInputData(1, triangleFilter2.GetOutput())
    booleanFilter.Update()
    outputModel.SetAndObservePolyData(booleanFilter.GetOutput())
    outputModel.CreateDefaultDisplayNodes()
    logging.info('Processing completed')

    return True
Exemple #9
0
    def BooleanUnion(self, mesh, inplace=False):
        """
        Returns the mesh in common between the current mesh and the input mesh.

        Parameters
        ----------
        mesh : vtkInterface.PolyData
            The mesh to perform a union against.

        inplace : bool, optional
            Updates mesh in-place while returning nothing.

        Returns
        -------
        union : vtkInterface.PolyData
            The union mesh when inplace=False.

        """
        bfilter = vtk.vtkBooleanOperationPolyDataFilter()
        bfilter.SetOperationToUnion()
        bfilter.SetInputData(1, mesh)
        bfilter.SetInputData(0, self)
        bfilter.ReorientDifferenceCellsOff()
        bfilter.Update()

        if inplace:
            self.Overwrite(vtkappend.GetOutput())
        else:
            return PolyData(vtkappend.GetOutput())
Exemple #10
0
def booleanOperation(actor1,
                     actor2,
                     operation='plus',
                     c=None,
                     alpha=1,
                     wire=False,
                     bc=None,
                     edges=False,
                     legend=None,
                     texture=None):
    '''Volumetric union, intersection and subtraction of surfaces'''
    try:
        bf = vtk.vtkBooleanOperationPolyDataFilter()
    except AttributeError:
        vio.printc('Boolean operation only possible for vtk version >= 8', 'r')
        return None
    poly1 = vu.polydata(actor1, True)
    poly2 = vu.polydata(actor2, True)
    if operation.lower() == 'plus':
        bf.SetOperationToUnion()
    elif operation.lower() == 'intersect':
        bf.SetOperationToIntersection()
    elif operation.lower() == 'minus':
        bf.SetOperationToDifference()
        bf.ReorientDifferenceCellsOn()
    if vu.vtkMV:
        bf.SetInputData(0, poly1)
        bf.SetInputData(1, poly2)
    else:
        bf.SetInputConnection(0, poly1.GetProducerPort())
        bf.SetInputConnection(1, poly2.GetProducerPort())
    bf.Update()
    actor = vu.makeActor(bf.GetOutput(), c, alpha, wire, bc, edges, legend,
                         texture)
    return actor
Exemple #11
0
def booldifference(surface1, surface2):
    """Create surface that is the difference between the two input surfaces."""
    boolfilter = vtk.vtkBooleanOperationPolyDataFilter()
    boolfilter.SetOperationToDifference()
    boolfilter.SetInput(0, surface1)
    boolfilter.SetInput(1, surface2)
    boolfilter.Update()
    return boolfilter.GetOutput()
Exemple #12
0
def booldifference(surface1, surface2):
    """Create surface that is the difference between the two input surfaces."""
    boolfilter = vtk.vtkBooleanOperationPolyDataFilter()
    boolfilter.SetOperationToDifference()
    boolfilter.SetInput(0, surface1)
    boolfilter.SetInput(1, surface2)
    boolfilter.Update()
    return boolfilter.GetOutput()
Exemple #13
0
def _calculateVolumeByBoolean(vtkDataSet1,vtkDataSet2,iV):
    """
    Function to calculate the volumes of a cell intersecting a mesh.

    Uses a boolean polydata filter to calculate the intersection,
    a general implementation but slow.

    """
    import numpy as np, SimPEG as simpeg, vtk
    import vtk.util.numpy_support as npsup

    from telluricpy import vtkTools

    # Triangulate polygon and calc normals
    baseC = vtkTools.dataset.getCell2vtp(vtkDataSet2,iV)
    baseVol = vtkTools.polydata.calculateVolume(baseC)
    # print iV, baseVol
    # Extract cells from the first mesh that intersect the base cell
    extractCells = vtkTools.extraction.extractDataSetWithPolygon(vtkDataSet1,baseC,extInside=True,extBoundaryCells=True,extractBounds=True)
    extInd = npsup.vtk_to_numpy(extractCells.GetCellData().GetArray('id'))
    # print extInd
    # Assert if there are no cells cutv
    assert extractCells.GetNumberOfCells() > 0, 'No cells in the clip, cell id {:d}'.format(iV)
    # Calculate the volumes of the clipped cells and insert to the matrix
    volL = []
    for nrCC,iR in enumerate(extInd):
        tempCell = vtkTools.dataset.thresholdCellId2vtp(extractCells,iR)
        # Find the intersection of the 2 cells
        boolFilt = vtk.vtkBooleanOperationPolyDataFilter()
        boolFilt.SetInputData(0,tempCell)
        boolFilt.SetInputData(1,baseC)
        boolFilt.SetOperationToIntersection()
        # If they intersect, calculate the volumes
        if boolFilt.GetOutput().GetNumberOfPoints() > 0:
            cleanInt = vtkTools.polydata.cleanPolyData(boolFilt.GetOutputPort())
            del3dFilt = vtk.vtkDelaunay3D()
            del3dFilt.SetInputData(cleanInt)
            del3dFilt.Update()
            # Get the output
            intC = vtkTools.extraction.vtu2vtp(del3dFilt.GetOutput())
            intVol = vtkTools.polydata.calculateVolume(tempCell)
            # Calculate the volume
            volVal = intVol/baseVol
            # print iR, intVol, volVal
            # Insert the value
            if volVal > 0.0:
                volL.append(volVal)
    return extInd,np.array(volL)
Exemple #14
0
def boolean_stl(input_file1, input_file2, output_file, transform_file, operation, visualize, overwrite, func):

  if os.path.isfile(output_file) and not overwrite:
    result = input('File \"{}\" already exists. Overwrite? [y/n]: '.format(output_file))
    if result.lower() not in ['y', 'yes']:
      print('Not overwriting. Exiting...')
      os.sys.exit()
  
  im1 = vtk.vtkSTLReader()
  im1.SetFileName(input_file1)
  im1.Update()
  im1 = cleanPolyData( im1.GetOutput() )
  
  im2 = vtk.vtkSTLReader()
  im2.SetFileName(input_file2)
  im2.Update()
  im2 = cleanPolyData( im2.GetOutput() )
  
  im2 = applyTransform(transform_file, im2)
  
  if (visualize):
    mat4x4 = visualize_actors( im2.GetOutputPort(), im1.GetOutputPort() )
  else:
    mat4x4 = vtk.vtkMatrix4x4()

  transform = vtk.vtkTransform()
  transform.SetMatrix(mat4x4)
  
  transformFilter = vtk.vtkTransformFilter()
  transformFilter.SetInputConnection( im2.GetOutputPort() )
  transformFilter.SetTransform( transform )
  transformFilter.Update()

  booleanOperation = vtk.vtkBooleanOperationPolyDataFilter()
  booleanOperation.SetInputData( 0, im1.GetOutput() )
  booleanOperation.SetInputData( 1, transformFilter.GetOutput() )
  if "union" in operation:
    booleanOperation.SetOperationToUnion()
  elif "intersection" in operation:
    booleanOperation.SetOperationToIntersection()
  elif "difference" in operation:
    booleanOperation.SetOperationToDifference()
  else:
    raise ValueError('Invalid boolean operation: ' + operation)
  booleanOperation.Update()
    
  write_stl( booleanOperation.GetOutputPort(), output_file, vtk.vtkMatrix4x4() )
Exemple #15
0
def getBooleanOperationOnPolys(poly1, poly2, operation='union'):
    if operation == 'union':
        opVTK = vtk.VTK_UNION
    elif operation == 'intersection':
        opVTK = vtk.VTK_INTERSECTION
    elif operation == 'difference':
        opVTK = vtk.VTK_DIFFERENCE
    else:
        raise Exception(
            "getBooleanOperationOnPolys: unknown boolean operation type (known types are: 'union', 'intersection', and 'difference')"
        )
    boolFilter = vtk.vtkBooleanOperationPolyDataFilter()
    boolFilter.SetOperation(opVTK)
    boolFilter.SetInputConnection(0, poly1.GetProducerPort())
    boolFilter.SetInputConnection(1, poly2.GetProducerPort())
    boolFilter.Update()
    return boolFilter.GetOutput()
def apply_boolean_operation(polydata1, polydata2, operation="difference"):
    boolean_operator = vtk.vtkBooleanOperationPolyDataFilter()
    if operation == "union":
        boolean_operator.SetOperationToUnion()
    elif operation == "intersection":
        boolean_operator.SetOperationToIntersection()
    elif operation == "difference":
        boolean_operator.SetOperationToDifference()
    else:
        print("Unknow operation")
        sys.exit(0)

    boolean_operator.SetInputData(0, polydata1)
    boolean_operator.SetInputData(1, polydata2)
    boolean_operator.Update()

    return boolean_operator.GetOutput()
Exemple #17
0
def _calculateVolumeByBoolean(vtkDataSet1,vtkDataSet2,iV):
    """
    Function to calculate the volumes of a cell intersecting a mesh.

    Uses a boolean polydata filter to calculate the intersection,
    a general implementation but slow.

    """
    # Triangulate polygon and calc normals
    baseC = vtkTools.dataset.getCell2vtp(vtkDataSet2,iV)
    baseVol = vtkTools.polydata.calculateVolume(baseC)
    # print iV, baseVol
    # Extract cells from the first mesh that intersect the base cell
    extractCells = vtkTools.extraction.extractDataSetWithPolygon(vtkDataSet1,baseC,extInside=True,extBoundaryCells=True,extractBounds=True)
    extInd = npsup.vtk_to_numpy(extractCells.GetCellData().GetArray('id'))
    # print extInd
    # Assert if there are no cells cutv
    assert extractCells.GetNumberOfCells() > 0, 'No cells in the clip, cell id {:d}'.format(iV)
    # Calculate the volumes of the clipped cells and insert to the matrix
    volL = []
    for nrCC,iR in enumerate(extInd):
        tempCell = vtkTools.dataset.thresholdCellId2vtp(extractCells,iR)
        # Find the intersection of the 2 cells
        boolFilt = vtk.vtkBooleanOperationPolyDataFilter()
        boolFilt.SetInputData(0,tempCell)
        boolFilt.SetInputData(1,baseC)
        boolFilt.SetOperationToIntersection()
        # If they intersect, calculate the volumes
        if boolFilt.GetOutput().GetNumberOfPoints() > 0:
            cleanInt = vtkTools.polydata.cleanPolyData(boolFilt.GetOutputPort())
            del3dFilt = vtk.vtkDelaunay3D()
            del3dFilt.SetInputData(cleanInt)
            del3dFilt.Update()
            # Get the output
            intC = vtkTools.extraction.vtu2vtp(del3dFilt.GetOutput())
            intVol = vtkTools.polydata.calculateVolume(tempCell)
            # Calculate the volume
            volVal = intVol/baseVol
            # print iR, intVol, volVal
            # Insert the value
            if volVal > 0.0:
                volL.append(volVal)
    return extInd,np.array(volL)
  def polydataBoolean(self, polyData1, polyData2, operation, triangleFilter=True, loop=False, clean=True):
  # Subtract/add polyData2 from polyData1
    if (not polyData1) or (not polyData2):
      return polyData1
      
      
    booleanFilter = vtk.vtkBooleanOperationPolyDataFilter()
    if loop:
      booleanFilter = vtk.vtkLoopBooleanPolyDataFilter()
      
    if operation=="difference" or operation=="subtract":
      booleanFilter.SetOperationToDifference()
    elif operation=="union" or operation=="addition":
      booleanFilter.SetOperationToUnion()
    else:
      return None      
      
    if triangleFilter:
      triangleFilter1 = vtk.vtkTriangleFilter()
      triangleFilter1.SetInputData(polyData1)
      triangleFilter1.Update()
      
      triangleFilter2 = vtk.vtkTriangleFilter()
      triangleFilter2.SetInputData(polyData2)
      triangleFilter2.Update()

      booleanFilter.SetInputData(0, triangleFilter1.GetOutput())
      booleanFilter.SetInputData(1, triangleFilter2.GetOutput())
    else:
      booleanFilter.SetInputData(0, polyData1)
      booleanFilter.SetInputData(1, polyData2)
      
    booleanFilter.Update()
    
    if clean:
      cleanFilter = vtk.vtkCleanPolyData()
      cleanFilter.SetInputData(booleanFilter.GetOutput())
      cleanFilter.PointMergingOn()
      cleanFilter.Update()
      return cleanFilter.GetOutput()
    else:
      return booleanFilter.GetOutput()
def Union(gONE,gTWO):
    err0 = ErrorObserver()

    bOp = vtk.vtkBooleanOperationPolyDataFilter()
    bOp.AddObserver('ErrorEvent', err0)

    bOp.SetOperationToUnion()
    # bOp.SetOperationToIntersection()
    # bOp.SetOperationToDifference()
    if vtk.VTK_MAJOR_VERSION <= 5:
        bOp.SetInputConnection( 0, gONE.GetProducerPort() )
        bOp.SetInputConnection( 1, gTWO.GetProducerPort() )
    else:
        bOp.SetInputData( 0, gONE.GetOutput() )
        bOp.SetInputData( 1, gTWO.GetOutput() )

    bOp.Update()
    if err0.ErrorOccurred():
        return None

    return bOp
Exemple #20
0
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No Surface.')

        if self.Surface2 == None:
            self.PrintError('Error: No Surface2.')

        booleanOperationFilter = vtk.vtkBooleanOperationPolyDataFilter()
        booleanOperationFilter.SetInputData(0, self.Surface)
        booleanOperationFilter.SetInputData(1, self.Surface2)
        if self.Operation == 'union':
            booleanOperationFilter.SetOperationToUnion()
        elif self.Operation == 'intersection':
            booleanOperationFilter.SetOperationToIntersection()
        elif self.Operation == 'difference':
            booleanOperationFilter.SetOperationToDifference()
        booleanOperationFilter.SetTolerance(self.Tolerance)
        booleanOperationFilter.Update()

        self.Surface = booleanOperationFilter.GetOutput()
    def Execute(self):

        if self.Surface == None:
            self.PrintError('Error: No Surface.')

        if self.Surface2 == None:
            self.PrintError('Error: No Surface2.')

        booleanOperationFilter = vtk.vtkBooleanOperationPolyDataFilter()
        booleanOperationFilter.SetInputData(0,self.Surface)
        booleanOperationFilter.SetInputData(1,self.Surface2)
        if self.Operation == 'union':
            booleanOperationFilter.SetOperationToUnion()
        elif self.Operation == 'intersection':
            booleanOperationFilter.SetOperationToIntersection()
        elif self.Operation == 'difference':
            booleanOperationFilter.SetOperationToDifference()
        booleanOperationFilter.SetTolerance(self.Tolerance)
        booleanOperationFilter.Update()

        self.Surface = booleanOperationFilter.GetOutput()
Exemple #22
0
    def BooleanCut(self, cut):
        """
        Performs a Boolean cut using another mesh.

        Parameters
        ----------
        cut : vtkInterface.PolyData
            Mesh making the cut

        Returns
        -------
        mesh : vtkInterface.PolyData
            The cut mesh
        """
        bfilter = vtk.vtkBooleanOperationPolyDataFilter()
        bfilter.SetOperationToIntersection()
        bfilter.SetInputData(1, cut)
        bfilter.SetInputData(0, self)
        bfilter.ReorientDifferenceCellsOff()
        bfilter.Update()
        return PolyData(bfilter.GetOutput())
Exemple #23
0
    def BooleanUnion(self, mesh):
        """
        Returns the mesh in common between the current mesh and the input mesh.

        Parameters
        ----------
        mesh : vtkInterface.PolyData
            The mesh to perform a union against.

        Returns
        -------
        union : vtkInterface.PolyData
            The union mesh
        """
        bfilter = vtk.vtkBooleanOperationPolyDataFilter()
        bfilter.SetOperationToUnion()
        bfilter.SetInputData(1, mesh)
        bfilter.SetInputData(0, self)
        bfilter.ReorientDifferenceCellsOff()
        bfilter.Update()
        return PolyData(bfilter.GetOutput())
Exemple #24
0
def two_polydata_dice(polydata_0, polydata_1):
    """
    Calculates the DICE score for two polydata.
    Will probably struggle with complex topologies,
    but should be fine for vaguely spherical shape.
    This function uses vtk.vtkMassProperties() so does not
    convert polydata to image data

    :param polydata_0: vtkPolyData representing a 3D mesh
    :param polydata_1: vtkPolyData representing a 3D mesh

    :return dice: The DICE score
    :return volume_0: The enclosed volume of polydata_0
    :return volume_1: The enclosed volume of polydata_1
    :return volume_01: The enclosed volume of the intersection
    """
    measured_polydata = vtkMassProperties()
    measured_polydata.SetInputData(polydata_0)
    volume_0 = measured_polydata.GetVolume()

    measured_polydata.SetInputData(polydata_1)
    volume_1 = measured_polydata.GetVolume()

    intersector = vtkBooleanOperationPolyDataFilter()
    intersector.SetOperationToIntersection()

    intersector.SetInputData(0, polydata_0)
    intersector.SetInputData(1, polydata_1)

    if check_overlapping_bounds(polydata_0, polydata_1):
        intersector.Update()
        intersection = intersector.GetOutput()
        measured_polydata.SetInputData(intersection)
        volume_01 = measured_polydata.GetVolume()
    else:
        volume_01 = 0.0
        dice = 0.0

    dice = 2 * volume_01 / (volume_0 + volume_1)
    return dice, volume_0, volume_1, volume_01
Exemple #25
0
    def __init__(self, raysect_csg_primitive):

        # need to get the geometry source for each primitive
        self.raysect_primitive = raysect_csg_primitive

        primitive_a = map_raysect_element_to_vtk(
            raysect_csg_primitive.primitive_a)
        source_a_tris = vtk.vtkTriangleFilter()
        source_a_tris.SetInputData(primitive_a.transform_filter.GetOutput())
        self.source_a_tri_filter = source_a_tris

        primitive_b = map_raysect_element_to_vtk(
            raysect_csg_primitive.primitive_b)
        source_b_tris = vtk.vtkTriangleFilter()
        source_b_tris.SetInputData(primitive_b.transform_filter.GetOutput())
        self.source_b_tri_filter = source_b_tris

        boolean_operation = vtk.vtkBooleanOperationPolyDataFilter()
        self.boolean_operation = boolean_operation
        self._set_boolean_operation()
        boolean_operation.SetInputConnection(0, source_a_tris.GetOutputPort())
        boolean_operation.SetInputConnection(1, source_b_tris.GetOutputPort())
        boolean_operation.Update()

        transform_filter = vtk.vtkTransformPolyDataFilter()
        transform_filter.SetInputConnection(boolean_operation.GetOutputPort())
        transform_filter.SetTransform(
            convert_to_vtk_transform(raysect_csg_primitive.transform))
        transform_filter.Update()
        self.transform_filter = transform_filter

        booleanOperationMapper = vtk.vtkPolyDataMapper()
        booleanOperationMapper.SetInputConnection(
            transform_filter.GetOutputPort())
        booleanOperationMapper.ScalarVisibilityOff()
        self.mapper = booleanOperationMapper

        booleanOperationActor = vtk.vtkActor()
        booleanOperationActor.SetMapper(booleanOperationMapper)
        self.actor = booleanOperationActor
Exemple #26
0
def vtk_bool_operation(obj_1, obj_2, operation='intersection'):
    # Triangles
    tri_1 = vtk.vtkTriangleFilter()
    tri_1.SetInputConnection(obj_1.GetOutputPort())

    tri_2 = vtk.vtkTriangleFilter()
    tri_2.SetInputConnection(obj_2.GetOutputPort())

    # Create an intersection operation
    boolean_operation = vtk.vtkBooleanOperationPolyDataFilter()

    if operation is 'union':
        boolean_operation.SetOperationToUnion()
    elif operation is 'difference':
        boolean_operation.SetOperationToDifference()
    else:
        boolean_operation.SetOperationToIntersection()

    boolean_operation.SetInputConnection(0, tri_1.GetOutputPort())
    boolean_operation.SetInputConnection(1, tri_2.GetOutputPort())
    boolean_operation.Update()

    print('[  OK  ] %s was already performed' % operation.title())
    return boolean_operation
Exemple #27
0
input1Actor.SetMapper(input1Mapper)
input1Actor.GetProperty().SetColor(1, 0, 0)
input1Actor.SetPosition(input1.GetBounds()[1] - input1.GetBounds()[0], 0, 0)
input2Mapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
    input2Mapper.SetInputConnection(input2.GetProducerPort())
else:
    input2Mapper.SetInputData(input2)

input2Mapper.ScalarVisibilityOff()
input2Actor = vtk.vtkActor()
input2Actor.SetMapper(input2Mapper)
input2Actor.GetProperty().SetColor(0, 1, 0)
input2Actor.SetPosition(-(input2.GetBounds()[1] - input2.GetBounds()[0]), 0, 0)

booleanOperation = vtk.vtkBooleanOperationPolyDataFilter()
#booleanOperation.SetOperationToUnion()
booleanOperation.SetOperationToIntersection()
#booleanOperation.SetOperationToDifference()

if vtk.VTK_MAJOR_VERSION <= 5:
    booleanOperation.SetInputConnection(0, sphere1Tri.GetOutputPort())
    booleanOperation.SetInputConnection(1, sphere2Tri.GetOutputPort())
else:
    booleanOperation.SetInputData(0, sphere1Tri)
    booleanOperation.SetInputData(1, sphere2Tri)
booleanOperation.Update()

booleanOperationMapper = vtk.vtkPolyDataMapper()
booleanOperationMapper.SetInputConnection(booleanOperation.GetOutputPort())
booleanOperationMapper.ScalarVisibilityOff()
Exemple #28
0
def computeContactPoints(mesh):
    print "Computing contact points..."
    
    segments = mesh.segments
    components = mesh.components
    
    adjacency_info_2 = collections.defaultdict(dict)
    contact_slots_2 = collections.defaultdict(dict)
    for seg in components.keys():
        contact_slots_2[seg] = collections.defaultdict(list)
        adjacency_info_2[seg] = collections.defaultdict(int)
        
    polys   = {}
    for seg in components.keys():
        for c in components[seg]:
            if not c.segmentId in polys:
                polys[c.segmentId] = []
            pts, tris = arrayToPolydata(c.vertices, c.faces)
            poly = vtk.vtkPolyData()
            poly.SetPoints(pts)
            poly.SetPolys(tris)
            poly.Update()
            polys[c.segmentId].append(poly)
        
    s_keys = polys.keys()
    vertices = vtk.vtkCellArray()
    points = vtk.vtkPoints()
    for x in range(len(s_keys) - 1):
        for y in range(x+1, len(s_keys)):
            for id_x, c_x in enumerate(polys[s_keys[x]]):
                for id_y, c_y in enumerate(polys[s_keys[y]]):
                    b = vtk.vtkBooleanOperationPolyDataFilter()
                    b.SetOperationToIntersection()
                    b.SetTolerance(0.1)
                    b.SetInput(0, c_x)
                    b.SetInput(1, c_y)
                    b.Update()
            
                    p = b.GetOutput(1).GetPoints()
                    if (p.GetNumberOfPoints() > 0):
                        print "Found %d contact points between segment #%d-%d and segment #%d-%d" % (p.GetNumberOfPoints(), s_keys[x], id_x, s_keys[y], id_y)
                        for k in range(p.GetNumberOfPoints()):
                            id = points.InsertNextPoint(p.GetPoint(k))
                            vertices.InsertNextCell(1)
                            vertices.InsertCellPoint(id)
                        
                        res_points = numpy.array(polydataToArray(p))
                        
                        d_x = dict()
                        d_x['points'] = res_points
                        d_x['seg'] = s_keys[y]
                        d_x['comp'] = id_y
                        contact_slots_2[s_keys[x]][id_x].append(d_x)
                        d_y = dict()
                        d_y['points'] = res_points
                        d_y['seg'] = s_keys[x]
                        d_y['comp'] = id_x
                        contact_slots_2[s_keys[y]][id_y].append(d_y)

                        adjacency_info_2[s_keys[x]][s_keys[y]] += 1
                        adjacency_info_2[s_keys[y]][s_keys[x]] += 1
            
                    points.Modified()
                    vertices.Modified()
    
    print "Adjacency info"
    for k in s_keys:
        s = "\t %d | " % k
        for k_2 in s_keys:
            s += " %d |" % (adjacency_info_2[k][k_2])
        print s
    
    for s_k, s_v in contact_slots_2.items():
        print "Segment %d" % s_k
        for c_k, c_v in s_v.items():
            print "\t Component %d" % c_k
            for data in c_v:
                print "\t\t Seg: %d Comp: %d Points: %d" % (data['seg'], data['comp'], len(data['points']))
                
    return adjacency_info_2, contact_slots_2
Exemple #29
0
    def test_vtk_example_with_my_cylinder(self):
        # sphereSource1 = vtk.vtkSphereSource()
        # sphereSource1.SetCenter(0.25, 0, 0)
        # sphereSource1.Update()
        # input1 = sphereSource1.GetOutput()
        input1 = teigen.tb_vtk.get_cylinder([0.25, 0, -.5], 0.9, 0.7,
                                            [0.0, .0, .0])
        sphere1tri = vtk.vtkTriangleFilter()
        sphere1tri.SetInputData(input1)

        # sphereSource2 = vtk.vtkSphereSource()
        # sphereSource2 = vtk.vtkCylinderSource()
        # sphereSource2.Update()
        # input2 = sphereSource2.GetOutput()
        direction = np.asarray([1., 1., 1.])
        direction /= np.linalg.norm(direction)
        input2 = teigen.tb_vtk.get_cylinder([0, .1, 0], 0.7, 0.5, direction)

        sphere2Tri = vtk.vtkTriangleFilter()
        sphere2Tri.SetInputData(input2)

        input1mapper = vtk.vtkPolyDataMapper()
        if vtk.VTK_MAJOR_VERSION <= 5:
            input1mapper.SetInputConnection(input1.GetProducerPort())
        else:
            input1mapper.SetInputData(input1)

        input1mapper.ScalarVisibilityOff()
        input1Actor = vtk.vtkActor()
        input1Actor.SetMapper(input1mapper)
        input1Actor.GetProperty().SetColor(1, 0, 0)
        input1Actor.SetPosition(input1.GetBounds()[1] - input1.GetBounds()[0],
                                0, 0)
        input2Mapper = vtk.vtkPolyDataMapper()
        if vtk.VTK_MAJOR_VERSION <= 5:
            input2Mapper.SetInputConnection(input2.GetProducerPort())
        else:
            input2Mapper.SetInputData(input2)

        input2Mapper.ScalarVisibilityOff()
        input2Actor = vtk.vtkActor()
        input2Actor.SetMapper(input2Mapper)
        input2Actor.GetProperty().SetColor(0, 1, 0)
        input2Actor.SetPosition(
            -(input2.GetBounds()[1] - input2.GetBounds()[0]), 0, 0)

        booleanOperation = vtk.vtkBooleanOperationPolyDataFilter()
        # booleanOperation.SetOperationToUnion()
        # booleanOperation.SetOperationToIntersection()
        booleanOperation.SetOperationToDifference()

        if vtk.VTK_MAJOR_VERSION <= 5:
            booleanOperation.SetInputConnection(0, sphere1tri.GetOutputPort())
            booleanOperation.SetInputConnection(1, sphere2Tri.GetOutputPort())
        else:
            sphere1tri.Update()
            sphere2Tri.Update()
            booleanOperation.SetInputData(0, sphere1tri.GetOutput())
            booleanOperation.SetInputData(1, sphere2Tri.GetOutput())
        booleanOperation.Update()

        boolean_peration_mapper = vtk.vtkPolyDataMapper()
        boolean_peration_mapper.SetInputConnection(
            booleanOperation.GetOutputPort())
        boolean_peration_mapper.ScalarVisibilityOff()

        booleanOperationActor = vtk.vtkActor()
        booleanOperationActor.SetMapper(boolean_peration_mapper)

        renderer = vtk.vtkRenderer()
        renderer.AddViewProp(input1Actor)
        renderer.AddViewProp(input2Actor)
        renderer.AddViewProp(booleanOperationActor)
        renderer.SetBackground(.1, .2, .3)
        renderWindow = vtk.vtkRenderWindow()
        renderWindow.AddRenderer(renderer)

        ren_win_interactor = vtk.vtkRenderWindowInteractor()
        ren_win_interactor.SetRenderWindow(renderWindow)

        renderWindow.Render()
        ren_win_interactor.Start()
Exemple #30
0
def SST_primary_mirror_plane():

    sphereSource1 = vtk.vtkSphereSource()
    sphereSource1.SetCenter(0.3, 0, 0)
    sphereSource1.SetRadius(cam_height)
    sphereSource1.SetThetaResolution(30)
    sphereSource1.SetPhiResolution(30)
    sphereSource1.Update()
    input1 = sphereSource1.GetOutput()
    sphere1Tri = vtk.vtkTriangleFilter()
    sphere1Tri.SetInputData(input1)

    sphereSource2 = vtk.vtkSphereSource()
    sphereSource2.SetRadius(cam_height)
    sphereSource2.SetThetaResolution(30)
    sphereSource2.SetPhiResolution(30)
    sphereSource2.Update()
    input2 = sphereSource2.GetOutput()
    sphere2Tri = vtk.vtkTriangleFilter()
    sphere2Tri.SetInputData(input2)

    booleanOperation = vtk.vtkBooleanOperationPolyDataFilter()
    # booleanOperation.SetOperationToUnion()
    # booleanOperation.SetOperationToIntersection()
    booleanOperation.SetOperationToDifference()

    booleanOperation.SetInputConnection(1, sphere1Tri.GetOutputPort())
    booleanOperation.SetInputConnection(0, sphere2Tri.GetOutputPort())
    booleanOperation.Update()

    bool_cylinder = vtk.vtkCylinderSource()
    bool_cylinder.SetCenter(0, 0, 0)
    bool_cylinder.SetRadius(primary_reflector_diameter / 2)
    bool_cylinder.SetHeight(cam_height * 2)
    bool_cylinder.SetResolution(40)
    # sphereSource3.SetResolution(20)
    bool_cylinder.Update()

    transform = vtk.vtkTransform()
    transform.Translate(-cam_height, 0, 0)
    transform.RotateZ(90)

    transformFilter = vtk.vtkTransformPolyDataFilter()
    transformFilter.SetTransform(transform)
    transformFilter.SetInputConnection(bool_cylinder.GetOutputPort())
    transformFilter.Update()

    input3 = transformFilter.GetOutput()
    cylinderTri = vtk.vtkTriangleFilter()
    cylinderTri.SetInputData(input3)

    booleanCylinderIntersect = vtk.vtkBooleanOperationPolyDataFilter()
    booleanCylinderIntersect.SetOperationToIntersection()
    # booleanCylinderIntersect.SetOperationToUnion()

    booleanCylinderIntersect.SetInputConnection(
        0, booleanOperation.GetOutputPort())
    booleanCylinderIntersect.SetInputConnection(1, cylinderTri.GetOutputPort())
    booleanCylinderIntersect.Update()

    booleanOperationMapper = vtk.vtkPolyDataMapper()
    booleanOperationMapper.SetInputConnection(
        booleanCylinderIntersect.GetOutputPort())
    booleanOperationMapper.ScalarVisibilityOff()

    booleanOperationActor = vtk.vtkActor()
    booleanOperationActor.SetMapper(booleanOperationMapper)
    booleanOperationActor.SetPosition(cam_height - 0.8, 0, 0)

    return booleanOperationActor
Exemple #31
0
tris1 = vtk.vtkTriangleFilter()
tris1.SetInputData(transform_filter.GetOutput())

cylinder_source2 = vtk.vtkCylinderSource()
cylinder_source2.SetRadius(1)
cylinder_source2.SetHeight(4.2)
cylinder_source2.SetResolution(50)
cylinder_source2.Update()
transform_filter = vtk.vtkTransformPolyDataFilter()
transform_filter.SetInputConnection(cylinder_source2.GetOutputPort())
transform_filter.SetTransform(convert_to_vtk_transform(rotate_z(90)))
transform_filter.Update()
tris2 = vtk.vtkTriangleFilter()
tris2.SetInputData(transform_filter.GetOutput())

booleanOperation1 = vtk.vtkBooleanOperationPolyDataFilter()
booleanOperation1.SetOperationToUnion()
booleanOperation1.SetInputConnection(0, tris1.GetOutputPort())
booleanOperation1.SetInputConnection(1, tris2.GetOutputPort())
booleanOperation1.Update()
bool_tris = vtk.vtkTriangleFilter()
bool_tris.SetInputData(booleanOperation1.GetOutput())

cylinder_source3 = vtk.vtkCylinderSource()
cylinder_source3.SetRadius(1)
cylinder_source3.SetHeight(4.2)
cylinder_source3.SetResolution(50)
cylinder_source3.Update()
tris3 = vtk.vtkTriangleFilter()
tris3.SetInputData(cylinder_source3.GetOutput())
Exemple #32
0
def computeContactPointsWithGUI(mesh):
    print "Computing contact points..."
    
    rand = random.Random()
    rand.seed(time())
    
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)
    
    segments = mesh.segments
    components = mesh.components
    
    adjacency_info = numpy.zeros (( len(components.keys()) , len(components.keys()) ), 'd') 
    contact_slots = {}
    adjacency_info_2 = collections.defaultdict(dict)
    contact_slots_2 = collections.defaultdict(dict)
    for seg in components.keys():
        contact_slots[seg] = [None, ] * len(components[seg])
        contact_slots_2[seg] = collections.defaultdict(list)
        adjacency_info_2[seg] = collections.defaultdict(int)
        
    polys   = {}
    for seg in components.keys():
        for c in components[seg]:
            if not c.segmentId in polys:
                polys[c.segmentId] = []
            pts, tris = arrayToPolydata(c.vertices, c.faces)
            poly = vtk.vtkPolyData()
            poly.SetPoints(pts)
            poly.SetPolys(tris)
            poly.Update()
            polys[c.segmentId].append(poly)
        
    legend = vtk.vtkLegendBoxActor()
    legend.SetNumberOfEntries( len(segments.keys()) )
    legendSphereSource = vtk.vtkSphereSource()
    legendSphere = legendSphereSource.GetOutput()
    leg = 0
    for segIdx in segments.keys():
        segColor = [rand.random(),0.2,rand.random()] 
        for c in polys[segIdx]:
            dataMapper = vtk.vtkPolyDataMapper()
            dataMapper.SetInput(c)
            model = vtk.vtkActor()
            model.SetMapper(dataMapper)
            model.GetProperty().SetColor(segColor)
            ren.AddActor(model)
            print "%d: V%d - P%d" % (segIdx, c.GetNumberOfPoints(), c.GetNumberOfPolys() )
        
        legend.SetEntry(leg, legendSphere, "Segment #" + str(segIdx), segColor)
        leg += 1
        
        
    s_keys = polys.keys()
    vertices = vtk.vtkCellArray()
    points = vtk.vtkPoints()
    for x in range(len(s_keys) - 1):
        for y in range(x+1, len(s_keys)):
            for id_x, c_x in enumerate(polys[s_keys[x]]):
                for id_y, c_y in enumerate(polys[s_keys[y]]):
                    b = vtk.vtkBooleanOperationPolyDataFilter()
                    b.SetOperationToIntersection()
                    b.SetTolerance(0.1)
                    b.SetInput(0, c_x)
                    b.SetInput(1, c_y)
                    b.Update()
            
                    p = b.GetOutput(1).GetPoints()
                    if (p.GetNumberOfPoints() > 0):
                        print "Found %d contact points between segment #%d-%d and segment #%d-%d" % (p.GetNumberOfPoints(), s_keys[x], id_x, s_keys[y], id_y)
                        for k in range(p.GetNumberOfPoints()):
                            id = points.InsertNextPoint(p.GetPoint(k))
                            vertices.InsertNextCell(1)
                            vertices.InsertCellPoint(id)
                        
                        res_points = numpy.array(polydataToArray(p))
                        contact_slots[s_keys[x]][id_x] = res_points
                        contact_slots[s_keys[y]][id_y] = res_points
                        
                        d_x = dict()
                        d_x['points'] = res_points
                        d_x['seg'] = s_keys[y]
                        d_x['comp'] = id_y
                        contact_slots_2[s_keys[x]][id_x].append(d_x)
                        
                        d_y = dict()
                        d_y['points'] = res_points
                        d_y['seg'] = s_keys[x]
                        d_y['comp'] = id_x
                        contact_slots_2[s_keys[y]][id_y].append(d_y)
                        
                        adjacency_info[x,y] += 1
                        adjacency_info[y,x] += 1
                        
                        adjacency_info_2[s_keys[x]][s_keys[y]] += 1
                        adjacency_info_2[s_keys[y]][s_keys[x]] += 1
            
                    points.Modified()
                    vertices.Modified()
    
    print "Adjacency info"
    for k in s_keys:
        s = "\t %d | " % k
        for k_2 in s_keys:
            s += " %d |" % (adjacency_info_2[k][k_2])
        print s
    
    for s_k, s_v in contact_slots_2.items():
        print "Segment %d" % s_k
        for c_k, c_v in s_v.items():
            print "\t Component %d" % c_k
            for data in c_v:
                print "\t\t Seg: %d Comp: %d Points: %d" % (data['seg'], data['comp'], len(data['points']))
                
    
    data = vtk.vtkPolyData()
    data.SetPoints(points)
    data.SetVerts(vertices)
    dataMapper = vtk.vtkPolyDataMapper()
    dataMapper.SetInput(data)
    
    model = vtk.vtkActor()
    model.SetMapper(dataMapper)
    model.GetProperty().SetColor(0.0, 1.0, 0.0)
    model.GetProperty().SetPointSize(8.0)
    ren.AddActor(model)
    
    ren.AddActor(legend)
    
    ren.SetBackground(0.1,0.2,0.4)
    renWin.SetSize(500,500)
    iren.Initialize()
    iren.Start()
Exemple #33
0
def get_tube_old(radius,
                 point,
                 direction,
                 length,
                 sphere_resolution,
                 cylinder_resolution,
                 cylinder_radius_compensation_factor=1.0,
                 sphere_radius_compensation_factor=1.0,
                 tube_shape=True):
    """ Create a tube with ending half-spherese in Z axis.

    :param radius:
    :param point:
    :param direction:
    :param length:
    :param sphere_resolution:
    :param cylinder_resolution:
    :param cylinder_radius_compensation_factor:
    :param sphere_radius_compensation_factor:
    :param tube_shape:
    :return:
    """
    cylinderTri = vtk.vtkTriangleFilter()
    sphere1Tri = vtk.vtkTriangleFilter()
    sphere2Tri = vtk.vtkTriangleFilter()
    boolean_operation1 = vtk.vtkBooleanOperationPolyDataFilter()
    boolean_operation2 = vtk.vtkBooleanOperationPolyDataFilter()
    boolean_operation1.SetOperationToUnion()
    boolean_operation2.SetOperationToUnion()

    # print(dbg_msg)
    cylinder_radius = radius * cylinder_radius_compensation_factor
    sphere_radius = radius * sphere_radius_compensation_factor
    retval = None

    if tube_shape:
        sphere1 = get_sphere(point,
                             sphere_radius,
                             resolution=sphere_resolution)
        sphere1Tri.SetInputData(sphere1)
        sphere1Tri.Update()
    if length > 0:
        cylinder = get_cylinder(point,
                                length,
                                cylinder_radius,
                                direction,
                                resolution=cylinder_resolution)

        cylinderTri.SetInputData(cylinder)
        cylinderTri.Update()
        direction /= nm.linalg.norm(direction)

        lv = point + direction * length
        if tube_shape:
            sphere2 = get_sphere(lv,
                                 sphere_radius,
                                 resolution=sphere_resolution)
            sphere2Tri.SetInputData(sphere2)
            sphere2Tri.Update()

            # booleanOperation.SetInputData(0, cyl)
            boolean_operation1.SetInputData(0, cylinderTri.GetOutput())
            boolean_operation1.SetInputData(1, sphere1Tri.GetOutput())
            boolean_operation1.Update()
            boolean_operation2.SetInputData(0, boolean_operation1.GetOutput())
            boolean_operation2.SetInputData(1, sphere2Tri.GetOutput())
            # booleanOperation.SetInputData(2, sph2)
            boolean_operation2.Update()
        else:
            boolean_operation2 = cylinderTri

        retval = boolean_operation2.GetOutput()
    else:
        if tube_shape:
            boolean_operation2 = sphere1Tri
            retval = boolean_operation2.GetOutput()
        else:
            # length == 0 but no spheres
            # so we are generating just flat shape
            # boolean_operation2 = cylinderTri

            # return empty space
            retval = vtk.vtkTriangleFilter().GetOutput()
            # something_to_add = False
    return retval
Exemple #34
0
def gen_tree(tree_data,
             cylinder_resolution=10,
             sphere_resolution=10,
             polygon_radius_selection_method="inscribed",
             cylinder_radius_compensation_factor=1.0,
             sphere_radius_compensation_factor=1.0,
             tube_shape=True):
    """

    :param polygon_radius_selection_method:
        "inscribed":
        "compensation factors"
        "cylinder volume"
        "cylinder surface"
    :param tree_data:
    :param cylinder_resolution:
    :param sphere_resolution:
    :param cylinder_radius_compensation_factor: is used to change radius of cylinder and spheres
    :return:
    """
    import vtk
    # appendFilter = vtk.vtkAppendPolyData()
    appended_data = None
    if vtk.VTK_MAJOR_VERSION <= 5:
        logger.error("VTK 6 required")
    factors = polygon_radius_compensation_factos(
        polygon_radius_selection_method, cylinder_radius_compensation_factor,
        sphere_radius_compensation_factor, cylinder_resolution,
        sphere_resolution)

    cylinder_radius_compensation_factor, sphere_radius_compensation_factor,\
    cylinder_radius_compensation_factor_long, sphere_radius_compensation_factor_long = factors

    # import ipdb; ipdb.set_trace()
    for br in tree_data:
        # import ipdb;
        # ipdb.set_trace()
        something_to_add = True
        radius = br['radius']
        length = br["length"]
        direction = br["direction"]
        uv = br['upperVertex']

        dbg_msg = "generating edge with length: " + str(br["length"])
        logger.debug(dbg_msg)

        # tube = get_tube_old(radius, uv, direction, length,
        if length == 0:
            tube = get_sphere(uv, radius * sphere_radius_compensation_factor,
                              sphere_resolution)
        else:
            tube = get_tube(radius,
                            uv,
                            direction,
                            length,
                            sphere_resolution,
                            cylinder_resolution,
                            cylinder_radius_compensation_factor=
                            cylinder_radius_compensation_factor_long,
                            sphere_radius_compensation_factor=
                            sphere_radius_compensation_factor_long,
                            tube_shape=tube_shape)
        # this is simple version
        # appendFilter.AddInputData(boolean_operation2.GetOutput())
        # print "object connected, starting addind to general space " + str(br["length"])
        if something_to_add:
            if appended_data is None:
                #appended_data = boolean_operation2.GetOutput()
                appended_data = tube
            else:
                boolean_operation3 = vtk.vtkBooleanOperationPolyDataFilter()
                boolean_operation3.SetOperationToUnion()
                boolean_operation3.SetInputData(0, appended_data)
                boolean_operation3.SetInputData(1, tube)
                boolean_operation3.Update()
                appended_data = boolean_operation3.GetOutput()

    # import ipdb; ipdb.set_trace()

    # del (cylinderTri)
    # del (sphere1Tri)
    # del (sphere2Tri)
    # del (boolean_operation1)
    # del (boolean_operation2)
    # del (boolean_operation3)
    logger.debug("konec gen_tree()")
    # appendFilter.Update()
    # appended_data = appendFilter.GetOutput()
    return appended_data
Exemple #35
0
def get_tube(radius=1.0,
             point=[0.0, 0.0, 0.0],
             direction=[0.0, 0.0, 1.0],
             length=1.0,
             sphere_resolution=10,
             cylinder_resolution=10,
             cylinder_radius_compensation_factor=1.0,
             sphere_radius_compensation_factor=1.0,
             tube_shape=True,
             axis=1,
             make_ladder_even=True):
    point1 = [0.0, 0.0, 0.0]
    center = [0.0, 0.0, 0.0]
    point2 = [0.0, 0.0, 0.0]

    center[axis] = length / 2.0
    point2[axis] = length

    cylinder_radius = radius * cylinder_radius_compensation_factor
    sphere_radius = radius * sphere_radius_compensation_factor

    direction /= nm.linalg.norm(direction)
    lv = point + direction * length

    cylinderTri = vtk.vtkTriangleFilter()
    sphere1Tri = vtk.vtkTriangleFilter()
    sphere2Tri = vtk.vtkTriangleFilter()

    cylinder = vtk.vtkCylinderSource()
    cylinder.SetCenter(center)
    cylinder.SetHeight(length)
    cylinder.SetRadius(cylinder_radius)
    cylinder.SetResolution(cylinder_resolution)
    cylinder.Update()
    cylinderTri.SetInputData(cylinder.GetOutput())
    cylinderTri.Update()

    # make ladder even
    if make_ladder_even:
        if sphere_resolution % 2 == 0:
            phi_resolution = sphere_resolution + 1
        else:
            phi_resolution = sphere_resolution

    if not tube_shape:
        tube = move_to_position(cylinderTri, point, direction, 2, 1, 0)
        return tube.GetOutput()

    sphere1 = get_sphere(
        center=point1,
        radius=sphere_radius,
        resolution=sphere_resolution,
        start_phi=0,
        #end_phi=90,
        end_phi=180,
        axis=1,
        phi_resolution=phi_resolution)
    # sphere1.Update()

    sphere1Tri.SetInputData(sphere1)
    sphere1Tri.Update()

    sphere2 = get_sphere(
        center=point2,
        # radius= 1. - (cylinder_radius - sphere_radius),
        radius=sphere_radius,
        resolution=sphere_resolution,
        start_phi=0,
        end_phi=180,
        axis=1,
        phi_resolution=phi_resolution)
    sphere2Tri.SetInputData(sphere2)
    sphere2Tri.Update()

    boolean_operation1 = vtk.vtkBooleanOperationPolyDataFilter()
    boolean_operation2 = vtk.vtkBooleanOperationPolyDataFilter()
    boolean_operation1.SetOperationToUnion()
    boolean_operation2.SetOperationToUnion()

    # booleanOperation.SetInputData(0, cyl)
    boolean_operation1.SetInputData(0, cylinderTri.GetOutput())
    boolean_operation1.SetInputData(1, sphere1Tri.GetOutput())
    boolean_operation1.Update()
    boolean_operation2.SetInputData(0, boolean_operation1.GetOutput())
    boolean_operation2.SetInputData(1, sphere2Tri.GetOutput())
    # booleanOperation.SetInputData(2, sph2)
    boolean_operation2.Update()
    # tube_in_base_position = boolean_operation2.GetOutput()

    #tube = move_to_position(boolean_operation2, point, direction, 1, 2)
    tube = move_to_position(boolean_operation2, point, direction, 2, 1, 0)
    return tube.GetOutput()
        filteredMeshes.append(clean.GetOutput())
        
        print "%d: %d - %d" % (k, clean.GetOutput().GetNumberOfPoints(), clean.GetOutput().GetNumberOfPolys(), )

        dataMapper = vtk.vtkPolyDataMapper()
        dataMapper.SetInput(clean.GetOutput())
        model = vtk.vtkActor()
        model.SetMapper(dataMapper)
        model.GetProperty().SetColor(rand.random(),0.2,rand.random())
        
        ren.AddActor(model)

print
print filteredMeshes

b = vtk.vtkBooleanOperationPolyDataFilter()
b.SetOperationToIntersection()
b.SetTolerance(0.1)
b.SetInput(0, filteredMeshes[2])
b.SetInput(1, filteredMeshes[1])
b.Update()

print b.GetOutput(1).GetPoints()
points = b.GetOutput(1).GetPoints()
vertices = vtk.vtkCellArray()

for x in range(points.GetNumberOfPoints()):
    vertices.InsertNextCell(1)
    vertices.InsertCellPoint(x)

points.Modified()
Exemple #37
0
    def write_boolean_operation(self, obj, position, rotation, operation):
        return None
        self.logger.debug("Writing Boolean Object {}".format(
            obj.__class__.__name__))
        self.logger.debug("First: {}".format(obj.first))
        self.logger.debug("Second: {}".format(obj.second))
        self.logger.debug("Rotation: {}".format(obj.rotation))
        self.logger.debug("Position: {}".format(obj.position))

        booleanFilter = vtk.vtkBooleanOperationPolyDataFilter()
        booleanFilter.SetOperation(operation)
        input1 = None
        input2 = None

        if isinstance(obj.first, Box):
            input1 = self.write_box(obj.first, [0, 0, 0], [0, 0, 0])
        elif isinstance(obj.first, Tube):
            input1 = self.write_tube(obj.first, [0, 0, 0], [0, 0, 0])
        elif isinstance(obj.first, Sphere):
            input1 = self.write_sphere(obj.first, [0, 0, 0], [0, 0, 0])
        elif isinstance(obj.first, Union):
            input1 = self.write_union(obj.first, [0, 0, 0], [0, 0, 0])
        elif isinstance(obj.first, Subtraction):
            input1 = self.write_intersection(obj.first, [0, 0, 0], [0, 0, 0])
        elif isinstance(obj.first, Intersection):
            input1 = self.write_union(obj.first, [0, 0, 0], [0, 0, 0])
        else:
            cls_name = obj.first.__class__.__name__
            self.logger.error("Encountered Unknown Type: " + cls_name)
            raise WritingError("Unkown Type Encountered in Boolean First")
        if input1 is None:
            cls_name = obj.first.__class__.__name__
            self.logger.warning("Input1 is Null for " + cls_name)
        if isinstance(obj.second, Box):
            input2 = self.write_box(obj.second, obj.position, obj.rotation)
        elif isinstance(obj.second, Tube):
            input2 = self.write_tube(obj.second, obj.position, obj.rotation)
        elif isinstance(obj.second, Sphere):
            input2 = self.write_sphere(obj.second, obj.position, obj.rotation)
        elif isinstance(obj.second, Union):
            input2 = self.write_union(obj.second, obj.position, obj.rotation)
        elif isinstance(obj.second, Subtraction):
            input2 = self.write_intersection(obj.second, obj.position,
                                             obj.rotation)
        elif isinstance(obj.second, Intersection):
            input2 = self.write_union(obj.second, obj.position, obj.rotation)
        else:
            self.logger.warning("Encountered Unknown Type: {}".format(
                obj.second.__class__.__name__))
            raise WritingError("Unknown Type Encoutered in Boolean Second")
        if input2 is None:
            self.logger.warning("Input2 is Null for " +
                                obj.second.__class__.__name__)

        if (input1 is None or input2 is None):
            return None

        tmp1 = vtk.vtkTriangleFilter()
        tmp1.SetInputConnection(input1.GetOutputPort())
        tmp1.Update()
        input1 = tmp1

        tmp2 = vtk.vtkTriangleFilter()
        tmp2.SetInputConnection(input2.GetOutputPort())
        tmp2.Update()
        input2 = tmp2

        self.appendpolydata.AddInputData(
            self.apply_transformations(input1.GetOutputPort(), rotation,
                                       position).GetOutput())
        self.appendpolydata.Update()
        self.appendpolydata.AddInputData(
            self.apply_transformations(input2.GetOutputPort(), rotation,
                                       position).GetOutput())
        self.appendpolydata.Update()
        return None

        booleanFilter.SetInputData(
            0,
            self.apply_transformations(input1.GetOutputPort(), rotation,
                                       position).GetOutput())
        booleanFilter.SetInputData(
            1,
            self.apply_transformations(input2.GetOutputPort(), rotation,
                                       position).GetOutput())

        if not self.check_intersection(input1, input2):
            self.logger.warning("Could NOT find intersection")
            return None
        self.logger.debug("Found Intersections")

        self.logger.debug("Applying Boolean Filter")
        try:
            booleanFilter.SetTolerance(1.e-12)
            booleanFilter.Update()
            self.logger.debug("Finished Creating Boolean Surface")
            return booleanFilter
        except:
            self.logger.warning("Failed")
            return None
def ComputeEdgeOfUnion(lnume, A, S, pz):
    use_function_callback = True
    colors = vtk.vtkNamedColors()
    colorsCell = ['AliceBlue', 'Green', 'Blue', 'Yellow', 'Magenta']
    # A renderer and render window
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('Silver'))

    # render window
    renwin = vtk.vtkRenderWindow()
    renwin.SetWindowName("CallBack")
    renwin.AddRenderer(renderer)

    # An interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renwin)

    # Start
    if use_function_callback:
        CloseWin.int = interactor
        interactor.AddObserver('EndInteractionEvent', CloseWin)

    # Create actors
    # create container Sphere
    sphere = vtk.vtkQuadric()
    sphere.SetCoefficients(S)
    sampleS = vtk.vtkSampleFunction()
    sampleS.SetImplicitFunction(sphere)
    # mapper
    mapperSphere = vtk.vtkPolyDataMapper()
    mapperSphere.SetInputConnection(sampleS.GetOutputPort())
    mapperSphere.ScalarVisibilityOff()
    #    actorSphere = vtk.vtkActor()
    #    actorSphere.SetMapper(mapperSphere)
    #    actorSphere.GetProperty().EdgeVisibilityOn()
    #    actorSphere.GetProperty().SetColor(colors.GetColor3d('AliceBlue'))
    #    actorSphere.GetProperty().SetEdgeColor(colors.GetColor3d('SteelBlue'))
    boundsC = np.array(sampleS.GetModelBounds())
    for k in range(3):
        boundsC[2 * k] = -1.1 * np.sqrt(-S[9])
        boundsC[2 * k + 1] = 1.1 * np.sqrt(-S[9])
    print(S[9])
    print(boundsC)
    sampleS.SetModelBounds(boundsC)

    #    surface.SetValue(0, 0.0)
    #
    contoursS = vtk.vtkContourFilter()
    contoursS.SetInputConnection(sampleS.GetOutputPort())
    contoursS.GenerateValues(1, 0.0, 1.2)

    contMapper = vtk.vtkPolyDataMapper()
    contMapper.SetInputConnection(contoursS.GetOutputPort())
    contMapper.SetScalarRange(0.0, 1.2)
    contActor = vtk.vtkActor()
    contActor.GetProperty().SetOpacity(0.1)
    contActor.SetMapper(contMapper)

    # create an ellipsoid using a implicit quadric
    quadric = [None] * len(lnume)
    mapper = [None] * len(lnume)
    actor = [None] * len(lnume)
    sample = [None] * len(lnume)
    contours = [None] * len(lnume)
    bounds = np.array(sampleS.GetModelBounds())
    booleanOperation = vtk.vtkBooleanOperationPolyDataFilter()
    booleanOperation.SetOperationToUnion()
    booleanOperationMapper = vtk.vtkPolyDataMapper()
    booleanOperationActor = vtk.vtkActor()
    for k in lnume:
        quadric[k] = vtk.vtkQuadric()
        quadric[k].SetCoefficients(A[lnume[k]])
        sample[k] = vtk.vtkSampleFunction()
        sample[k].SetImplicitFunction(quadric[k])
        for l in range(3):
            bounds[2 * l] = -1.2 * np.sqrt(-S[9])
            bounds[2 * l + 1] = 1.2 * np.sqrt(-S[9])

        sample[k].SetModelBounds(bounds)
        contours[k] = vtk.vtkContourFilter()
        contours[k].SetInputConnection(sample[k].GetOutputPort())
        # generation d'une valeur dans l'intervalle spécifié (le min et le max sont inclus)
        contours[k].GenerateValues(1, 0.0, 0.1)

        # mapper
        mapper[k] = vtk.vtkPolyDataMapper()
        mapper[k].SetInputConnection(contours[k].GetOutputPort())
        mapper[k].ScalarVisibilityOff()
        actor[k] = vtk.vtkActor()
        actor[k].SetMapper(mapper[k])
        #actor[k].GetProperty().EdgeVisibilityOn()
        actor[k].GetProperty().SetColor(
            colors.GetColor3d(colorsCell[k % len(colorsCell)]))
        actor[k].GetProperty().SetEdgeColor(colors.GetColor3d('SteelBlue'))
        Ellipsoid2Tri = vtk.vtkTriangleFilter()
        input2 = contours[k].GetOutput()
        Ellipsoid2Tri.SetInputData(input2)
        if k == lnume[0]:
            booleanOperationActor.SetMapper(mapper[lnume[0]])
            EllipsoidsTri = vtk.vtkTriangleFilter()
            input1 = booleanOperation.GetOutputPort().GetOutput()  # A revoir
            EllipsoidsTri.SetInputData(input1)
        else:
            booleanOperation.SetInputConnection(0,
                                                EllipsoidsTri.GetOutputPort())
            booleanOperation.SetInputConnection(1,
                                                Ellipsoid2Tri.GetOutputPort())
            booleanOperation.Update()
            booleanOperationMapper.SetInputConnection(
                booleanOperation.GetOutputPort())
            booleanOperationMapper.ScalarVisibilityOff()
            booleanOperationActor.GetProperty().SetDiffuseColor(
                colors.GetColor3d("Banana"))