示例#1
0
    def addFiducials(self):
        shaderFiducials = slicer.util.getNode('shaderFiducials')
        if not shaderFiducials:
            displayNode = slicer.vtkMRMLMarkupsDisplayNode()
            slicer.mrmlScene.AddNode(displayNode)
            fiducialNode = slicer.vtkMRMLMarkupsFiducialNode()
            fiducialNode.SetName('shaderFiducials')
            slicer.mrmlScene.AddNode(fiducialNode)
            fiducialNode.SetAndObserveDisplayNodeID(displayNode.GetID())
            for ras in ((28.338526, 34.064367, 10), (-10, 0, -5)):
                fiducialNode.AddFiducial(*ras)
            import random
            fiducialCount = 10
            radius = 75
            for index in range(fiducialCount):
                uvw = [random.random(), random.random(), random.random()]
                ras = map(lambda e: radius * (2. * e - 1.), uvw)
                fiducialNode.AddFiducial(*ras)

            # make it active
            selectionNode = slicer.mrmlScene.GetNodeByID(
                "vtkMRMLSelectionNodeSingleton")
            if (selectionNode is not None):
                selectionNode.SetReferenceActivePlaceNodeID(
                    fiducialNode.GetID())
示例#2
0
 def createMovingLRSToFixedLRS(self, movingLRS = None):
   if movingLRS.GetNumberOfFiducials() < 3:
     logging.warning('Moving LRS fiducials list needs to contain at least three fiducials!')
     return False
     
   fixedLRS = slicer.util.getNode('FixedLRS')    
   if not fixedLRS:
     # Create FixedLRS markups node
     fixedLRS = slicer.vtkMRMLMarkupsFiducialNode()
     fixedLRS.SetName('FixedLRS')
     fixedLRS.AddFiducial(-100.0, 0.0, 0.0)
     fixedLRS.SetNthFiducialLabel(0, 'FixedL')
     fixedLRS.AddFiducial(100.0, 0.0, 0.0)
     fixedLRS.SetNthFiducialLabel(1, 'FixedR')
     fixedLRS.AddFiducial(0.0, 0.0, 100.0)
     fixedLRS.SetNthFiducialLabel(2, 'FixedS')
     slicer.mrmlScene.AddNode(fixedLRS)
     fixedLRS.SetDisplayVisibility(False)
  
   movingLRSToFixedLRS = slicer.util.getNode('MovingLRSToFixedLRS')    
   if not movingLRSToFixedLRS:
     # Create MovingLRSToFixedLRS transform node
     movingLRSToFixedLRS = slicer.vtkMRMLLinearTransformNode()
     movingLRSToFixedLRS.SetName('MovingLRSToFixedLRS')
     slicer.mrmlScene.AddNode(movingLRSToFixedLRS)
   
   self.fiducialRegistration(movingLRSToFixedLRS, fixedLRS, movingLRS, "Rigid")
   
   return True
示例#3
0
 def __init__( self, stepid ):
   self.initialize( stepid )
   self.setName( '5. Place Screws' )
   self.setDescription( 'Load screw models and change orientation using sliders' )
   self.screwPath = None
   self.screwName = None
   self.coords = [0,0,0]
   self.matrix1 = vtk.vtkMatrix3x3()
   self.matrix2 = vtk.vtkMatrix3x3()
   self.matrix3 = vtk.vtkMatrix3x3()
   self.matrixScrew = vtk.vtkMatrix4x4()
   self.fiduciallist = []
   self.screwSummary = []
   
   self.screwList = []
   self.currentFidIndex = 0
   self.currentFidLabel = None
             
   self.fidNode = slicer.vtkMRMLMarkupsFiducialNode()
   
   self.valueTemp1 = 0
   self.valueTemp2 = 0
   self.driveTemp = 0
   
   self.__loadScrewButton = None
   self.__parent = super( ScrewStep, self )
   
   self.timer = qt.QTimer()
   self.timer.setInterval(2)
   self.timer.connect('timeout()', self.driveScrew)
   self.timer2 = qt.QTimer()
   self.timer2.setInterval(2)
   self.timer2.connect('timeout()', self.reverseScrew)
   self.screwInsert = 0.0
示例#4
0
    def inputFiducialBtnClick(self, volumeType):
        # Create Fiducial Node for the cochlea location
        if (volumeType == "input"):
            print(" ..... getting cochlea location in the input image")
            # Reset global point label
            self.inputPoint = [0, 0, 0]
            self.inputPointEdt.setText("[0, 0, 0]")
            # Check if a volume is selected
            if not self.inputSelectorCoBx.currentNode():
                print >> sys.stderr, "You need to pick a input volume first."
                return -1
            try:
                self.inputNode = self.inputSelectorCoBx.currentNode()
            except:
                self.suppDICOM()
            #end try

        #  Display Coronal during locating the cochlea
        green_logic = slicer.app.layoutManager().sliceWidget(
            "Green").sliceLogic()
        green_cn = green_logic.GetSliceCompositeNode()
        green_cn.SetBackgroundVolumeID(self.inputNode.GetID())
        lm = slicer.app.layoutManager()
        lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutOneUpGreenSliceView)
        # Fit slice to window
        sliceNodes = slicer.util.getNodes('vtkMRMLSliceNode*')
        layoutManager = slicer.app.layoutManager()
        for sliceNode in sliceNodes.values():
            sliceWidget = layoutManager.sliceWidget(sliceNode.GetLayoutName())
            if sliceWidget:
                sliceWidget.sliceLogic().FitSliceToAll()

        # Remove old Fiducial nodes
        nodes = slicer.util.getNodesByClass('vtkMRMLMarkupsFiducialNode')
        for f in nodes:
            if ((f.GetName() == "CochleaLocation")):
                slicer.mrmlScene.RemoveNode(f)
        self.inputFiducialBtn.setStyleSheet(
            "QPushButton{ background-color: DarkSeaGreen  }")
        self.inputFiducialNode = slicer.vtkMRMLMarkupsFiducialNode()
        self.inputFiducialNode.SetName("CochleaLocation")
        slicer.mrmlScene.AddNode(self.inputFiducialNode)

        # Start Fiducial Placement Mode in Slicer
        placeModePersistance = 0
        slicer.modules.markups.logic().StartPlaceMode(placeModePersistance)

        # Observe scene for updates
        self.inputFiducialNode.AddObserver(
            self.inputFiducialNode.MarkupAddedEvent, self.convRAS2IJK)
        self.inputFiducialNode.AddObserver(
            self.inputFiducialNode.MarkupRemovedEvent, self.convRAS2IJK)
        self.inputFiducialNode.AddObserver(
            self.inputFiducialNode.PointModifiedEvent, self.updateIJK)

        self.inputFiducialBtn.setStyleSheet(
            "QPushButton{ background-color: White  }")
  def createTodoMarkup( self ):
    todoMarkup = slicer.mrmlScene.AddNode(slicer.vtkMRMLMarkupsFiducialNode())
    todoMarkup.SetHideFromEditors(1)
    todoMarkup.SetName('Interactive Segment Tubes To Do list')
    todoMarkup.SetDisplayVisibility(0)
    # Set None as an active list otherwise the user might add fiducial to todoMarkup
    self.setActivePlaceNodeID(None)

    return todoMarkup
示例#6
0
    def createTodoMarkup(self):
        todoMarkup = slicer.mrmlScene.AddNode(
            slicer.vtkMRMLMarkupsFiducialNode())
        todoMarkup.SetHideFromEditors(1)
        todoMarkup.SetName('Interactive Segment Tubes To Do list')
        todoMarkup.SetDisplayVisibility(0)
        # Set None as an active list otherwise the user might add fiducial to todoMarkup
        self.setActivePlaceNodeID(None)

        return todoMarkup
示例#7
0
    def onClippingModelSelect(self, node):

        if node != None and node != '':
            if node.GetID() not in self.__modelList:
                self.__modelList.append(node.GetID())
                new_clippingMarkupNode = slicer.vtkMRMLMarkupsFiducialNode()
                new_clippingMarkupNode.SetScene(slicer.mrmlScene)
                slicer.mrmlScene.AddNode(new_clippingMarkupNode)
                self.__markupList.append([node.GetID(), new_clippingMarkupNode.GetID(), 'Convex'])
            
            self.__clippingModelNode = node
            self.setAndObserveClippingMarkupNode(Helper.getNodeByID(self.__markupList[self.__modelList.index(node.GetID())][1]))
 def addFiducial(self,ras):
   if self.isNewContour == True:
     self.fiducials = slicer.vtkMRMLMarkupsFiducialNode()
     self.fiducials.SetScene( slicer.mrmlScene )
     slicer.mrmlScene.AddNode( self.fiducials )
     tag = self.fiducials.AddObserver(self.fiducials.PointModifiedEvent, lambda caller,event: self.onFiducialMoved(caller))
     print tag
     self.observerTags.append( (self.fiducials,tag) )
     self.isNewContour = False
   
   self.numberFiducials += 1    
   self.fiducials.AddFiducial(ras[0],ras[1],ras[2],str(self.numberFiducials))
    def SetDefaultValuesClicked(self):
        if (not self.toFids):
            self.toFids = slicer.vtkMRMLMarkupsFiducialNode()
            self.toFids.SetName('toFids')
        if (not self.fromFids):
            self.fromFids = slicer.vtkMRMLMarkupsFiducialNode()
            self.fromFids.SetName('fromFids')
        if self.inputSelector1.currentNode():
            segmentationNode = self.inputSelector1.currentNode()
            TransformNode = self.inputSelector4.currentNode()
            segmentation = segmentationNode.GetSegmentation()
            segment = segmentation.GetSegment(segmentation.GetNthSegmentID(0))
            segment.SetColor(0, 0, 1)
            segmentationNode.GetDisplayNode().Visibility2DFillOff()

            if TransformNode:
                segmentationNode.SetAndObserveTransformNodeID(
                    TransformNode.GetID())
                print("transform successful")
            print("color change successful")
        else:
            slicer.util.errorDisplay("No Segementation selected !")
示例#10
0
	def addFid(data, Dim=.5, nodName="N", lableName="1", color="red", GlyphType=1):
		"""add a larger point"""
		xyz = tuple(data)
		tipFiducial = slicer.mrmlScene.AddNode(slicer.vtkMRMLMarkupsFiducialNode())
		tipFiducial.SetName(nodName)
		tipFiducial.AddFiducial(xyz[0], xyz[1], xyz[2])
		tipFiducial.SetNthFiducialLabel(0, lableName)
		slicer.mrmlScene.AddNode(tipFiducial)
		tipFiducial.SetDisplayVisibility(True)
		tipFiducial.GetDisplayNode().SetGlyphType(GlyphType)  # Vertex2D
		tipFiducial.GetDisplayNode().SetGlyphScale(Dim * 10)
		tipFiducial.GetDisplayNode().SetTextScale(3)
		tipFiducial.GetDisplayNode().SetSelectedColor(Helper.myColor(color))
		'''	GlyphShapes {
    def run(self, numToAdd=100, rOffset=0, usefewerModifyCalls=0):
        """
    Run the actual algorithm
    """
        print('Running test to add %s fidicuals' % (numToAdd, ))
        print('Index\tTime to add fid\tDelta between adds')
        print "%(index)04s\t" % {'index': "i"}, "t\tdt'"
        r = rOffset
        a = 0
        s = 0
        t1 = 0
        t2 = 0
        t3 = 0
        t4 = 0
        timeToAddThisFid = 0
        timeToAddLastFid = 0

        testStartTime = time.clock()
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

        if usefewerModifyCalls == 1:
            print "Start modify"
            mod = fidNode.StartModify()

        # iterate over the number of fiducials to add
        for i in range(numToAdd):
            #    print "i = ", i, "/", numToAdd, ", r = ", r, ", a = ", a, ", s = ", s
            t1 = time.clock()
            fidNode.AddFiducial(r, a, s)
            t2 = time.clock()
            timeToAddThisFid = t2 - t1
            dt = timeToAddThisFid - timeToAddLastFid
            print '%(index)04d\t' % {'index': i}, timeToAddThisFid, "\t", dt
            r = r + 1.0
            a = a + 1.0
            s = s + 1.0
            timeToAddLastFid = timeToAddThisFid

        if usefewerModifyCalls == 1:
            fidNode.EndModify(mod)

        testEndTime = time.clock()
        testTime = testEndTime - testStartTime
        print "Total time to add ", numToAdd, " = ", testTime

        return True
示例#12
0
  def run(self,numToAdd=100,rOffset=0,usefewerModifyCalls=0):
    """
    Run the actual algorithm
    """
    print('Running test to add %s fidicuals' % (numToAdd,))
    print('Index\tTime to add fid\tDelta between adds')
    print "%(index)04s\t" % {'index': "i"}, "t\tdt'"
    r = rOffset
    a = 0
    s = 0
    t1 = 0
    t2 = 0
    t3 = 0
    t4 = 0
    timeToAddThisFid = 0
    timeToAddLastFid = 0

    testStartTime = time.clock()
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)
    fidNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(fidNode)
    fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

    if usefewerModifyCalls == 1:
      print "Start modify"
      mod = fidNode.StartModify()

    # iterate over the number of fiducials to add
    for i in range(numToAdd):
      #    print "i = ", i, "/", numToAdd, ", r = ", r, ", a = ", a, ", s = ", s
      t1 = time.clock()
      fidNode.AddFiducial(r,a,s)
      t2 = time.clock()
      timeToAddThisFid = t2 - t1
      dt = timeToAddThisFid - timeToAddLastFid
      print '%(index)04d\t' % {'index': i}, timeToAddThisFid, "\t", dt
      r = r + 1.0
      a = a + 1.0
      s = s + 1.0
      timeToAddLastFid = timeToAddThisFid

    if usefewerModifyCalls == 1:
      fidNode.EndModify(mod)

    testEndTime = time.clock()
    testTime = testEndTime - testStartTime
    print "Total time to add ",numToAdd," = ", testTime

    return True
示例#13
0
 def calculateFiducialDistance(self, modelNode, fiducial):
   closestFiducial = slicer.util.getNode('CP')
   if not closestFiducial:
     closestFiducial = slicer.vtkMRMLMarkupsFiducialNode()  
     closestFiducial.SetName('CP')
     closestFiducial.AddFiducial(0, 0, 0)
     closestFiducial.SetNthFiducialLabel(0, 'CP')
     slicer.mrmlScene.AddNode(closestFiducial)
     closestFiducial.SetDisplayVisibility(False)
       
   line = slicer.util.getNode('Line')
   if not line:
     line = slicer.vtkMRMLModelNode()
     line.SetName('Line')
     linePolyData = vtk.vtkPolyData()
     line.SetAndObservePolyData(linePolyData)      
     modelDisplay = slicer.vtkMRMLModelDisplayNode()
     modelDisplay.SetSliceIntersectionVisibility(True)
     modelDisplay.SetColor(0,1,0)
     slicer.mrmlScene.AddNode(modelDisplay)      
     line.SetAndObserveDisplayNodeID(modelDisplay.GetID())      
     slicer.mrmlScene.AddNode(line)
     
   cellLocator = vtk.vtkCellLocator()
   cellLocator.SetDataSet(modelNode.GetPolyData())
   cellLocator.BuildLocator()
   
   if fiducial.GetNumberOfFiducials() > 0:          
     ras = [0.0, 0.0, 0.0]
     closestPoint = [0.0, 0.0, 0.0]
     
     fiducial.GetNthFiducialPosition(0, ras)
     distanceSquared = vtk.mutable(0.0) 
     subId = vtk.mutable(0) 
     cellId = vtk.mutable(0) 
     cell = vtk.vtkGenericCell()
     
     cellLocator.FindClosestPoint(ras, closestPoint, cell, cellId, subId, distanceSquared);
     distance = math.sqrt(distanceSquared)
           
     closestFiducial.SetNthFiducialPosition(0,  closestPoint[0], closestPoint[1], closestPoint[2])
     closestFiducial.SetDisplayVisibility(True)
     
     self.drawLineBetweenPoints(line, ras, closestPoint)
     
     self.set3dViewConernerAnnotation('Distance = ' + "%.2f" % distance + 'mm')
   else:
     logging.warning('No fiducials in list!')     
    def getFiducialList(self):
        
        P = self.getFiducialListName()
        nodes = slicer.mrmlScene.GetNodesByClassByName('vtkMRMLMarkupsFiducialNode', P)

        if nodes.GetNumberOfItems() == 0:
            # The list does not exist so we create it

            fidNode = slicer.vtkMRMLMarkupsFiducialNode()
            fidNode.SetName(P)
            slicer.mrmlScene.AddNode(fidNode)
            
        else:
            #The list exists but the observers must be updated
            fidNode = nodes.GetItemAsObject(0)

        return fidNode
示例#15
0
    def getFiducialList(self):

        P = self.getFiducialListName()
        nodes = slicer.mrmlScene.GetNodesByClassByName(
            'vtkMRMLMarkupsFiducialNode', P)

        if nodes.GetNumberOfItems() == 0:
            # The list does not exist so we create it

            fidNode = slicer.vtkMRMLMarkupsFiducialNode()
            fidNode.SetName(P)
            slicer.mrmlScene.AddNode(fidNode)

        else:
            #The list exists but the observers must be updated
            fidNode = nodes.GetItemAsObject(0)

        return fidNode
示例#16
0
    def test_VolumeClipWithModel1(self):

        # Download MRHead from sample data
        import SampleData
        sampleDataLogic = SampleData.SampleDataLogic()
        self.delayDisplay("Getting MR Head Volume")
        inputVolume = sampleDataLogic.downloadMRHead()

        # Create empty model node
        clippingModel = slicer.vtkMRMLModelNode()
        slicer.mrmlScene.AddNode(clippingModel)

        # Create markup fiducials
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        inputMarkup = slicer.vtkMRMLMarkupsFiducialNode()
        inputMarkup.SetName('C')
        slicer.mrmlScene.AddNode(inputMarkup)
        inputMarkup.SetAndObserveDisplayNodeID(displayNode.GetID())
        inputMarkup.AddFiducial(35, -10, -10)
        inputMarkup.AddFiducial(-15, 20, -10)
        inputMarkup.AddFiducial(-25, -25, -10)
        inputMarkup.AddFiducial(-5, -60, -15)
        inputMarkup.AddFiducial(-5, 5, 60)
        inputMarkup.AddFiducial(-5, -35, -30)

        # Create output volume
        outputVolume = slicer.vtkMRMLScalarVolumeNode()
        slicer.mrmlScene.AddNode(outputVolume)

        # Clip volume
        logic = VolumeClipWithModelLogic()
        clipOutsideSurface = True
        fillOutsideValue = 0
        clipInsideSurface = True
        fillInsideValue = 255

        logic.updateModelFromMarkup(inputMarkup, clippingModel)
        logic.clipVolumeWithModel(inputVolume, clippingModel,
                                  clipOutsideSurface, fillOutsideValue,
                                  outputVolume)
        logic.showInSliceViewers(outputVolume, ["Red", "Yellow", "Green"])

        self.delayDisplay("Test passed!")
示例#17
0
  def section_MarkupRole(self):
    self.delayDisplay("Markup role",self.delayMs)

    # Create sample markups node
    markupsNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(markupsNode)
    markupsNode.SetName(self.sampleMarkupName)
    fiducialPosition = [100.0, 0.0, 0.0]
    markupsNode.AddFiducialFromArray(fiducialPosition)

    # Add markups to subject hierarchy
    from vtkSlicerSubjectHierarchyModuleMRML import vtkMRMLSubjectHierarchyNode

    patientNode = vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(slicer.mrmlScene, None, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelPatient(), 'Patient')
    studyNode = vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(slicer.mrmlScene, patientNode, self.studyName, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelStudy())
    markupsShNode = vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(slicer.mrmlScene, studyNode, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelSeries(), self.sampleMarkupName, markupsNode)

    self.assertTrue( markupsShNode != None )
    self.assertTrue( markupsShNode.GetParentNode() == studyNode )
    self.assertTrue( markupsShNode.GetOwnerPluginName() == 'Markups' )
  def section_MarkupRole(self):
    self.delayDisplay("Markup role",self.delayMs)

    # Create sample markups node
    markupsNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(markupsNode)
    markupsNode.SetName(self.sampleMarkupName)
    fiducialPosition = [100.0, 0.0, 0.0]
    markupsNode.AddFiducialFromArray(fiducialPosition)

    # Add markups to subject hierarchy
    from vtkSlicerSubjectHierarchyModuleMRML import vtkMRMLSubjectHierarchyNode

    patientNode = vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(slicer.mrmlScene, None, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelPatient(), 'Patient')
    studyNode = vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(slicer.mrmlScene, patientNode, self.studyName, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelStudy())
    markupsShNode = vtkMRMLSubjectHierarchyNode.CreateSubjectHierarchyNode(slicer.mrmlScene, studyNode, slicer.vtkMRMLSubjectHierarchyConstants.GetDICOMLevelSeries(), self.sampleMarkupName, markupsNode)

    self.assertTrue( markupsShNode != None )
    self.assertTrue( markupsShNode.GetParentNode() == studyNode )
    self.assertTrue( markupsShNode.GetOwnerPluginName() == 'Markups' )
    def test_AnglePlanes(self):
        
        self.delayDisplay('Starting the test')
        logic = AnglePlanesLogic()

        matrix = numpy.matrix([[0.572236,0.192876,0.797085,0],
                               [-0.819942,0.152968,0.551631,0],
                               [0.0155322,0.969226,-0.245681,0],
                               [0,0,0,1]])

        normalVector1 = logic.defineNormal(matrix)

        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(fidNode)

        r1=32
        a1=10
        s1=4

        r2=-9
        a2=7
        s2=19

        r3=9
        a3=-4
        s3=46

        fidNode.AddFiducial(r1,a1,s1)
        fidNode.AddFiducial(r2,a2,s2)
        fidNode.AddFiducial(r3,a3,s3)

        logic.planeLandmarks(1,2,3,1,1)

        GA = numpy.matrix([[5],[-2],[3]])
        GB = numpy.matrix([[6],[1],[9]])

        Normal = logic.normalLandmarks(GA, GB)

        logic.getAngle(normalVector1, Normal)

        self.delayDisplay('Test passed!')
示例#20
0
  def placeFiducials(self):

    # Create empty model node
    clippingModel = slicer.vtkMRMLModelNode()
    clippingModel.SetName('clipModelNode')
    slicer.mrmlScene.AddNode(clippingModel)

    # Create markup display fiducials - why do i need that?
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)

    # create markup fiducial node
    inputMarkup = slicer.vtkMRMLMarkupsFiducialNode()
    inputMarkup.SetName('inputMarkupNode')
    slicer.mrmlScene.AddNode(inputMarkup)
    inputMarkup.SetAndObserveDisplayNodeID(displayNode.GetID())

    # add Observer
    inputMarkup.AddObserver(vtk.vtkCommand.ModifiedEvent,self.updateModel)

    return True
示例#21
0
  def addFiducials(self):
    shaderFiducials = slicer.util.getNode('shaderFiducials')
    if not shaderFiducials:
      displayNode = slicer.vtkMRMLMarkupsDisplayNode()
      slicer.mrmlScene.AddNode(displayNode)
      fiducialNode = slicer.vtkMRMLMarkupsFiducialNode()
      fiducialNode.SetName('shaderFiducials')
      slicer.mrmlScene.AddNode(fiducialNode)
      fiducialNode.SetAndObserveDisplayNodeID(displayNode.GetID())
      for ras in ((28.338526, 34.064367, 10), (-10, 0, -5)):
        fiducialNode.AddFiducial(*ras)
      import random
      fiducialCount = 10
      radius = 75
      for index in range(fiducialCount):
        uvw = [random.random(), random.random(), random.random()]
        ras = map(lambda e: radius * (2. * e - 1.), uvw)
        fiducialNode.AddFiducial(*ras)

      # make it active
      selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
      if (selectionNode is not None):
        selectionNode.SetReferenceActivePlaceNodeID(fiducialNode.GetID())
  def runCaliper(self):

    inputVolume = self.inputSelector.currentNode()
    if not (inputVolume):
      qt.QMessageBox.critical(
          slicer.util.mainWindow(),
          'Deploy Caliper', 'Input volume is required for calculation.')
      return

# If coordinates modified, use for calculation

    if self.coordinatesWidgetModified:
      widgetPointsList = slicer.vtkMRMLMarkupsFiducialNode()
      widgetPointsList.SetName('WPL')

   #   widgetNode = slicer.util.getNode('WPL')
      slicer.mrmlScene.AddNode(widgetPointsList)
      
   #  Grab first widget coordinate and display
      print "PointNum1 is: "
      pointNum1Str = (str(self.c1Select.coordinates)).split(",")
      pointNum1 = [float(i) for i in pointNum1Str]
      print pointNum1

      widgetPointsList.AddFiducial(pointNum1[0], pointNum1[1], pointNum1[2], 'WP-1')

      
   #  Grab second widget coordinate and display
      print "PointNum2 is: "
      pointNum2Str = (str(self.c2Select.coordinates)).split(",")
      pointNum2 = [float(i) for i in pointNum2Str]
      print pointNum2
          
      widgetPointsList.AddFiducial(pointNum2[0], pointNum2[1], pointNum2[2], 'WP-2')
      
  #   Center the slices on Point 1
      slicer.modules.markups.logic().JumpSlicesToLocation(pointNum1[0], pointNum1[1], pointNum1[2], True)

  #   Calculate distance in mm and print to console
      distanceValue = math.sqrt( math.pow((pointNum1[0] - pointNum2[0]), 2) + math.pow((pointNum1[1] - pointNum2[1]), 2) + math.pow((pointNum1[2] - pointNum2[2]), 2))

      self.distUpdate.setText("Distance: %.2f mm" % distanceValue)

  #   Add a ruler
      rulerNode = slicer.vtkMRMLAnnotationRulerNode()
      rulerNode.SetDistanceAnnotationVisibility(1)
      rulerNode.SetPosition1(pointNum1[0], pointNum1[1], pointNum1[2])
      rulerNode.SetPosition2(pointNum2[0], pointNum2[1], pointNum2[2])
      rulerNode.SetName('Distance 1')
      rulerNode.SetDistanceAnnotationVisibility(False)
      rulerNode.Initialize(slicer.mrmlScene)

      self.coordinatesWidgetModified = False

    else:

  #   Get interactive coordinates, if any
      intNode1 = slicer.util.getNode('IP1')
      intNode2 = slicer.util.getNode('IP2')
      if ((intNode1.GetNumberOfFiducials() == 1) and (intNode2.GetNumberOfFiducials() == 1)):
        z3point1 = [0.0, 0.0, 0.0]
        z3point2 = [0.0, 0.0, 0.0]
        intNode1.GetNthFiducialPosition(0, z3point1)
        intNode2.GetNthFiducialPosition(0, z3point2)
        print "Interactive Point 1:"
        print z3point1
        print "Interactive Point 2:"
        print z3point2
        interactiveDistance = math.sqrt( math.pow((z3point1[0] - z3point2[0]), 2) + math.pow((z3point1[1] - z3point2[1]), 2) + math.pow((z3point1[2] - z3point2[2]), 2))    
        self.intDistUpdate.setText("Distance: %.2f mm" % interactiveDistance)

        intRulerNode = slicer.vtkMRMLAnnotationRulerNode()
        intRulerNode.SetDistanceAnnotationVisibility(1)
        intRulerNode.SetPosition1(z3point1[0], z3point1[1], z3point1[2])
        intRulerNode.SetPosition2(z3point2[0], z3point2[1], z3point2[2])
        intRulerNode.SetName('Distance 2')
        intRulerNode.SetDistanceAnnotationVisibility(False)
        intRulerNode.Initialize(slicer.mrmlScene)     

#   Blur if checkbox is checked
    if self.blur.isChecked():
      gauss = vtk.vtkImageGaussianSmooth()
      gauss.SetInputData(inputVolume.GetImageData())
      gauss.SetDimensionality(3)
      
      fwhmValue = .01 * distanceValue
      gauss.SetStandardDeviation(fwhmValue)
      gauss.Update()
      
      ijkToRAS = vtk.vtkMatrix4x4()
      inputVolume.GetIJKToRASMatrix(ijkToRAS)
      inputVolume.SetAndObserveImageData(gauss.GetOutput())
  def run(self,enableScreenshots=0,screenshotScaleFactor=1):
    """
    Run the actual algorithm
    """
    self.delayDisplay('Running test of the Neurosurgical Planning tutorial')

    self.enableScreenshots = enableScreenshots
    self.screenshotScaleFactor = screenshotScaleFactor

    # conventional layout
    lm = slicer.app.layoutManager()
    lm.setLayout(2)

    moduleSelector = slicer.util.mainWindow().moduleSelector()
    #
    # first load the data
    #
    if self.enableScreenshots == 1:
      # for the tutorial, do it through the welcome module
      moduleSelector.selectModule('Welcome')
      self.delayDisplay("Screenshot")
      self.takeScreenshot('NeurosurgicalPlanning-Welcome','Welcome module',-1)
    else:
      # otherwise show the sample data module
      moduleSelector.selectModule('SampleData')

    # use the sample data module logic to load data for the self test
    import SampleData
    sampleDataLogic = SampleData.SampleDataLogic()

    self.delayDisplay("Getting Baseline volume")
    baselineVolume = sampleDataLogic.downloadWhiteMatterExplorationBaselineVolume()

    self.delayDisplay("Getting DTI volume")
    dtiVolume = sampleDataLogic.downloadWhiteMatterExplorationDTIVolume()

    self.takeScreenshot('NeurosurgicalPlanning-Loaded','Data loaded',-1)

    #
    # link the viewers
    #

    if self.enableScreenshots == 1:
      # for the tutorial, pop up the linking control
      sliceController = slicer.app.layoutManager().sliceWidget("Red").sliceController()
      popupWidget = sliceController.findChild("ctkPopupWidget")
      if popupWidget != None:
        popupWidget.pinPopup(1)
        self.takeScreenshot('NeurosurgicalPlanning-Link','Link slice viewers',-1)
        popupWidget.pinPopup(0)

    sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
    compositeNode = sliceLogic.GetSliceCompositeNode()
    compositeNode.SetLinkedControl(1)

    #
    # baseline in the background
    #
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(baselineVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()

    self.takeScreenshot('NeurosurgicalPlanning-Baseline','Baseline in background',-1)

    #
    # adjust window level on baseline
    #
    moduleSelector.selectModule('Volumes')
    baselineDisplay = baselineVolume.GetDisplayNode()
    baselineDisplay.SetAutoWindowLevel(0)
    baselineDisplay.SetWindow(2600)
    baselineDisplay.SetLevel(1206)
    self.takeScreenshot('NeurosurgicalPlanning-WindowLevel','Set W/L on baseline',-1)

    #
    # switch to red slice only
    #
    lm.setLayout(6)
    self.takeScreenshot('NeurosurgicalPlanning-RedSliceOnly','Set layout to Red Slice only',-1)

    #
    # segmentation of tumour
    #

    #
    # create a label map and set it for editing
    #
    volumesLogic = slicer.modules.volumes.logic()
    baselineVolumeLabel =  volumesLogic.CreateAndAddLabelVolume( slicer.mrmlScene, baselineVolume, baselineVolume.GetName() + '-label' )
    baselineDisplayNode = baselineVolumeLabel.GetDisplayNode()
    baselineDisplayNode.SetAndObserveColorNodeID('vtkMRMLColorTableNodeFileGenericAnatomyColors.txt')
    selectionNode = slicer.app.applicationLogic().GetSelectionNode()
    selectionNode.SetReferenceActiveVolumeID(baselineVolume.GetID())
    selectionNode.SetReferenceActiveLabelVolumeID(baselineVolumeLabel.GetID())
    slicer.app.applicationLogic().PropagateVolumeSelection(0)

    #
    # editor module
    #
    moduleSelector.selectModule('Editor')
    self.takeScreenshot('NeurosurgicalPlanning-Editor','Showing Editor Module',-1)

    # set the slice offset so drawing is right
    sliceNode = sliceLogic.GetSliceNode()
    sliceOffset = 58.7
    sliceNode.SetSliceOffset(sliceOffset)

    #
    # paint
    #
    parameterNode = EditUtil.getParameterNode()
    paintEffect = EditorLib.PaintEffectOptions()
    paintEffect.setMRMLDefaults()
    paintEffect.__del__()
    sliceWidget = lm.sliceWidget('Red')
    paintTool = EditorLib.PaintEffectTool(sliceWidget)
    self.takeScreenshot('NeurosurgicalPlanning-Paint','Paint tool in Editor Module',-1)

    #
    # paint in cystic part of tumor, using converstion from RAS coords to
    # avoid slice widget size differences
    #
    EditUtil.setLabel(293)
    displayCoords = self.rasToDisplay(-7.4, 71, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    displayCoords = self.rasToDisplay(-11, 73, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    displayCoords = self.rasToDisplay(-12, 85, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    displayCoords = self.rasToDisplay(-13, 91, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    displayCoords = self.rasToDisplay(-15, 78, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    paintTool.paintApply()
    self.takeScreenshot('NeurosurgicalPlanning-PaintCystic','Paint cystic part of tumor',-1)

    #
    # paint in solid part of tumor
    #
    EditUtil.setLabel(7)
    displayCoords = self.rasToDisplay(-0.5 , 118.5, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    displayCoords = self.rasToDisplay(-7.4 , 116, sliceOffset)
    paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    paintTool.paintApply()
    self.takeScreenshot('NeurosurgicalPlanning-PaintSolid','Paint solid part of tumor',-1)

    #
    # paint around the tumor
    #
    EditUtil.setLabel(295)
    rMax = 25
    rMin = -50
    aMax = 145
    aMin = 50
    rasStep = 5

    # draw the top and bottom
    for r in range(rMin, rMax, rasStep):
      displayCoords = self.rasToDisplay(r, aMin, sliceOffset)
      paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
      displayCoords = self.rasToDisplay(r, aMax, sliceOffset)
      paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
    # draw the left and right
    for a in range(aMin, aMax, rasStep):
      displayCoords = self.rasToDisplay(rMin, a, sliceOffset)
      paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
      displayCoords = self.rasToDisplay(rMax, a, sliceOffset)
      paintTool.paintAddPoint(displayCoords[0], displayCoords[1])

    paintTool.paintApply()

    self.takeScreenshot('NeurosurgicalPlanning-PaintAround','Paint around tumor',-1)
    #
    # clean up after painting
    #
    paintTool.cleanup()
    paintTool = None

    #
    # Grow cut
    #
    growCutLogic = EditorLib.GrowCutEffectLogic(sliceWidget.sliceLogic())
    growCutLogic.growCut()
    self.takeScreenshot('NeurosurgicalPlanning-Growcut','Growcut',-1)

    #
    # Merge split volume
    #
    slicer.util.selectModule('Editor')
    slicer.util.findChildren(text='Split Merge Volume')[0].clicked()
    self.takeScreenshot('NeurosurgicalPlanning-SplitMerge','SplitMerge',-1)

    #
    # go to the data module
    #
    moduleSelector.selectModule('Data')
    self.takeScreenshot('NeurosurgicalPlanning-SplitMergeData','SplitMerge results in Data',-1)

    #
    # Ventricles Segmentation
    #

    moduleSelector.selectModule('Editor')
    #
    # select the label volume with the area around the tumor
    slicer.util.findChildren(name='PerStructureVolumesFrame')[0].collapsed = False
    treeView = slicer.util.findChildren(name='StructuresView')[0]
    selection = qt.QItemSelection()
    # selecting the last split volume in the third row
    row = 2
    rowStart = treeView.model().index(row,0)
    rowEnd = treeView.model().index(row,treeView.model().columnCount() - 1)
    # rowSel = qt.QItemSelection(rowStart, rowEnd)
    selection.select(rowStart, rowEnd)
    # backup: select the label map in the slice logic too
    baselinelabel295 = slicer.mrmlScene.GetFirstNodeByName("BaselineVolume-region 3-label")
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetLabelVolumeID(baselinelabel295.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()
    self.takeScreenshot('NeurosurgicalPlanning-SelOutside','Select outside region',-1)

    #
    # Threshold tool
    #
    slicer.modules.EditorWidget.toolsBox.selectEffect('ThresholdEffect')
    parameterNode = EditUtil.getParameterNode()
    parameterNode.SetParameter('ThresholdEffect,min', str(1700))
    slicer.modules.EditorWidget.toolsBox.currentTools[0].apply()
    self.takeScreenshot('NeurosurgicalPlanning-Ventricles','Ventricles segmentation',-1)

    #
    # Save Islands
    #
    slicer.modules.EditorWidget.toolsBox.selectEffect('SaveIslandEffect')
    saveIslandLogic = EditorLib.SaveIslandEffectLogic(sliceWidget.sliceLogic())
    displayCoords = self.rasToDisplay(25.3, 5.8, sliceOffset)
    xy = (displayCoords[0], displayCoords[1])
    saveIslandLogic.saveIsland(xy)
    self.takeScreenshot('NeurosurgicalPlanning-SaveIsland','Ventricles save island',-1)

    #
    # Merge and build
    #
    slicer.util.findChildren(text='Merge And Build')[0].clicked()

    #
    # switch to conventional layout
    #
    lm.setLayout(2)
    self.takeScreenshot('NeurosurgicalPlanning-MergeAndBuild','Merged and built models',-1)

    #
    # Tractography label map seeding
    #

    #
    # select label volume with label 293, in the second row
    #
    row = 1
    rowStart = treeView.model().index(row,0)
    rowEnd = treeView.model().index(row,treeView.model().columnCount() - 1)
    # rowSel = qt.QItemSelection(rowStart, rowEnd)
    selection.select(rowStart, rowEnd)
    # backup: select the label map in the slice logic too
    baselinelabel293 = slicer.mrmlScene.GetFirstNodeByName("BaselineVolume-region 1-label")
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetLabelVolumeID(baselinelabel293.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()
    self.takeScreenshot('NeurosurgicalPlanning-SelCystic','Select cystic region',-1)

    #
    # Dilate
    #
    slicer.modules.EditorWidget.toolsBox.selectEffect('DilateEffect')
    EditUtil.setLabel(293)
    self.takeScreenshot('NeurosurgicalPlanning-Dilate','Dilate tool',-1)
    # tutorial says to click apply three times
    for d in range (1,3):
      print d
      # slicer.util.findChildren(name='DilateEffectOptionsApply')[0].clicked()
      # slicer.modules.EditorWidget.toolsBox.currentTools[0].apply()
      slicer.modules.EditorWidget.toolsBox.currentOption.onApply()
    self.takeScreenshot('NeurosurgicalPlanning-Dilated','Dilated tumor',-1)

    #
    # Tractography Label Map Seeding module
    #
    moduleSelector.selectModule('TractographyLabelMapSeeding')
    self.takeScreenshot('NeurosurgicalPlanning-LabelMapSeedingModule','Showing Tractography Label Seeding Module',-1)
    tractographyLabelSeeding = slicer.modules.tractographylabelmapseeding
    parameters = {}
    parameters['InputVolume'] = dtiVolume.GetID()
    baselinelabel293 = slicer.mrmlScene.GetFirstNodeByName("BaselineVolume-region 1-label")
# VTK6 TODO - set 'InputROIPipelineInfo'
    parameters['InputROI'] = baselinelabel293.GetID()
    fibers = slicer.vtkMRMLFiberBundleNode()
    slicer.mrmlScene.AddNode(fibers)
    parameters['OutputFibers'] = fibers.GetID()
    parameters['UseIndexSpace'] = 1
    parameters['StoppingValue'] = 0.15
    parameters['ROIlabel'] = 293
    parameters['StoppingMode'] = 'FractionalAnisotropy'
    # defaults
    # parameters['ClTh'] = 0.3
    # parameters['MinimumLength'] = 20
    # parameters['MaximumLength'] = 800
    # parameters['StoppingCurvature'] = 0.7
    # parameters['IntegrationStepLength'] = 0.5
    # parameters['SeedSpacing'] = 2
    # and run it
    slicer.cli.run(tractographyLabelSeeding, None, parameters)
    self.takeScreenshot('NeurosurgicalPlanning-LabelMapSeeding','Showing Tractography Label Seeding Results',-1)

    #
    # tractography fiducial seeding
    #
    moduleSelector.selectModule('TractographyInteractiveSeeding')
    self.takeScreenshot('NeurosurgicalPlanning-TIS','Showing Tractography Interactive Seeding Module',-1)

    # DTI in background
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(dtiVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()

    # DTI visible in 3D
    sliceNode = sliceLogic.GetSliceNode()
    sliceLogic.StartSliceNodeInteraction(128)
    sliceNode.SetSliceVisible(1)
    sliceLogic.EndSliceNodeInteraction()

    self.takeScreenshot('NeurosurgicalPlanning-TIS-DTI','DTI volume with Tractography Interactive Seeding Module',-1)

    # place a fiducial
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)
    fidNode = slicer.vtkMRMLMarkupsFiducialNode()
    fidNode.SetName('F')
    slicer.mrmlScene.AddNode(fidNode)
    fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
    r = 28.338526
    a = 34.064367
    s = sliceOffset
    fidNode.AddFiducial(r,a,s)

    # make it active
    selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
    if (selectionNode != None):
      selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

    self.takeScreenshot('NeurosurgicalPlanning-TIS-Fid1','Fiducial in Tractography Interactive Seeding Module',-1)


    # set up the arguments
    wr = slicer.modules.tractographyinteractiveseeding.widgetRepresentation()
    wr.setDiffusionTensorVolumeNode(dtiVolume)
    # create a fiber bundle
    fiducialFibers = slicer.vtkMRMLFiberBundleNode()
    slicer.mrmlScene.AddNode(fiducialFibers)
    wr.setFiberBundleNode(fiducialFibers)
    wr.setSeedingNode(fidNode)
    wr.setMinimumPath(10)
    wr.setStoppingValue(0.15)

    self.takeScreenshot('NeurosurgicalPlanning-TIS-Args','Tractography Interactive Seeding arguments',-1)

    self.delayDisplay("Moving the fiducial")
    for y in range(-20, 100, 5):
      msg = "Moving the fiducial to y = " + str(y)
      self.delayDisplay(msg,250)
      fidNode.SetNthFiducialPosition(0, r, y, s)

    self.takeScreenshot('NeurosurgicalPlanning-TIS-Moved','Moved fiducial and did Tractography Interactive Seeding',-1)

    return True
  def setup(self):
    ScriptedLoadableModuleWidget.setup(self)
    # Instantiate and connect widgets ...

    logic = MyPythonModuleLogic()
    self.coordinatesWidgetModified = False
    
    interactivePoint1Node = slicer.vtkMRMLMarkupsFiducialNode()
    interactivePoint1Node.SetName('IP1')

    interactivePoint2Node = slicer.vtkMRMLMarkupsFiducialNode()
    interactivePoint2Node.SetName('IP2')
    
 #   slicer.mrmlScene.AddNode(widgetPointsList)
    slicer.mrmlScene.AddNode(interactivePoint1Node)
    slicer.mrmlScene.AddNode(interactivePoint2Node)
    
    self.CrosshairNode = slicer.mrmlScene.GetNthNodeByClass(0, 'vtkMRMLCrosshairNode')
    if self.CrosshairNode:
      self.CrosshairNodeObserverTag = self.CrosshairNode.AddObserver(slicer.vtkMRMLCrosshairNode.CursorPositionModifiedEvent, self.interactiveCaliper)
    else:
      print "Couldn't access crosshair."

# Volumes collapsible button
    self.volumeCButton = ctk.ctkCollapsibleButton()
    self.volumeCButton.text = "Volume"
    self.layout.addWidget(self.volumeCButton)

# Layout within the volumes collapsible button
    self.volumeCLayout = qt.QFormLayout(self.volumeCButton)

    #
    # the volume selectors
    #
    self.inputFrame = qt.QFrame(self.volumeCButton)
    self.inputFrame.setLayout(qt.QHBoxLayout())
    self.volumeCLayout.addWidget(self.inputFrame)
    self.inputSelector = qt.QLabel("Input Volume: ", self.inputFrame)
    self.inputFrame.layout().addWidget(self.inputSelector)
    self.inputSelector = slicer.qMRMLNodeComboBox(self.inputFrame)
    self.inputSelector.nodeTypes = ( ("vtkMRMLScalarVolumeNode"), "" )
    self.inputSelector.addEnabled = False
    self.inputSelector.removeEnabled = False
    self.inputSelector.setMRMLScene( slicer.mrmlScene )
    self.inputFrame.layout().addWidget(self.inputSelector)

#   Coordinates collapsible button set-up 
    self.coord = ctk.ctkCollapsibleButton()
    self.coord.text = "Manually input coordinates"
    self.layout.addWidget(self.coord)

    self.coordLayout = qt.QFormLayout(self.coord)

#   Coordinate 1 Label and widget
    self.c1 = qt.QFrame(self.coord)
    self.c1.setLayout(qt.QHBoxLayout())
    self.coordLayout.addWidget(self.c1)
    self.c1Select = qt.QLabel("Coordinate 1: ", self.c1)
    self.c1.layout().addWidget(self.c1Select)

    self.c1Select = ctk.ctkCoordinatesWidget(self.c1)
    self.c1Select.connect('coordinatesChanged(double*)', self.changedCoordinates)    
    
    self.c1.layout().addWidget(self.c1Select)

#   Coordinate 2 Label and widget
    self.c2 = qt.QFrame(self.coord)
    self.c2.setLayout(qt.QHBoxLayout())
    self.coordLayout.addWidget(self.c2)
    self.c2Select = qt.QLabel("Coordinate 2: ", self.c2)
    self.c2.layout().addWidget(self.c2Select)

    self.c2Select = ctk.ctkCoordinatesWidget(self.c2)
    self.c2Select.connect('coordinatesChanged(double*)', self.changedCoordinates)
    
    self.c2.layout().addWidget(self.c2Select)
    

#   Deploy caliper button
    runCaliperButton = qt.QPushButton("Deploy Caliper")
    runCaliperButton.toolTip = "Deploy the virtual caliper on the data set."
    self.coordLayout.addWidget(runCaliperButton)
    runCaliperButton.connect('clicked(bool)', self.runCaliper)

#   Label with updating distance value results
    self.distanceLabel = qt.QFrame(self.coord)
    self.distanceLabel.setLayout(qt.QHBoxLayout())
    self.coordLayout.addWidget(self.distanceLabel)
    self.distUpdate = qt.QLabel("Distance: ", self.distanceLabel)
    self.distanceLabel.layout().addWidget(self.distUpdate)

#   Interactive coordinates collapsible button set-up 
    self.interactiveCoord = ctk.ctkCollapsibleButton()
    self.interactiveCoord.text = "Interactive coordinates"
    self.layout.addWidget(self.interactiveCoord)

    self.interactiveCoordLayout = qt.QFormLayout(self.interactiveCoord)

#   Interactive caliper 1 button
    buttonIC1 = qt.QPushButton("Interactive Caliper - Point 1")
    buttonIC1.toolTip = "Run the interactive caliper for Point 1."
    self.interactiveCoordLayout.addWidget(buttonIC1)
    buttonIC1.connect('clicked(bool)', logic.saveInteractivePoint1)

#   Interactive caliper 2 button
    buttonIC2 = qt.QPushButton("Interactive Caliper - Point 2")
    buttonIC2.toolTip = "Run the interactive caliper for Point 2."
    self.interactiveCoordLayout.addWidget(buttonIC2)
    buttonIC2.connect('clicked(bool)', logic.saveInteractivePoint2)

#   Interactive caliper 1 label with axes
    self.labelIC1 = qt.QFrame(self.interactiveCoord)
    self.labelIC1.setLayout(qt.QHBoxLayout())
    self.interactiveCoordLayout.addWidget(self.labelIC1)
    self.labelIC1update = qt.QLabel("X: NaN  Y: NaN  Z: NaN  ", self.labelIC1)
    self.labelIC1.layout().addWidget(self.labelIC1update)

#   Label with updating distance value results
    self.intDistanceLabel = qt.QFrame(self.interactiveCoord)
    self.intDistanceLabel.setLayout(qt.QHBoxLayout())
    self.interactiveCoordLayout.addWidget(self.intDistanceLabel)
    self.intDistUpdate = qt.QLabel("Distance: ", self.intDistanceLabel)
    self.intDistanceLabel.layout().addWidget(self.intDistUpdate)

#   Blur gaussian collapsible button set-up 
    self.blurButton = ctk.ctkCollapsibleButton()
    self.blurButton.text = "Add gaussian blur"
    self.layout.addWidget(self.blurButton)

    self.blurButtonLayout = qt.QFormLayout(self.blurButton)

#   Blur checkmark
    self.blur = qt.QCheckBox("Blur image", self.blurButton)
    self.blur.toolTip = "When checked, blur image based on distance"
    self.blur.checked = False
    self.blurButtonLayout.addWidget(self.blur)
    self.blur.connect('stateChanged(int)', self.blurCheckBox)

#   Display original checkmark
    self.orig = qt.QCheckBox("Display original", self.blurButton)
    self.orig.toolTip = "When checked, blur image based on distance"
    self.orig.checked = True
    self.blurButtonLayout.addWidget(self.orig)
    self.orig.connect('stateChanged(int)', self.origCheckBox)
    
    # Add vertical spacer
    self.layout.addStretch(1)

    # Set local var as instance attribute
    self.runCaliperButton = runCaliperButton
示例#25
0
  def locateCochlea(self, inputVolumeNode,  inputPointEdt, volumeType):

        # Create Fiducial Node for the cochlea location  
        print(" ..... getting cochlea location in "+volumeType+ " image")

        #  Display Coronal during locating the cochlea
        green_logic = slicer.app.layoutManager().sliceWidget("Green").sliceLogic()
        green_cn = green_logic.GetSliceCompositeNode()
        green_cn.SetBackgroundVolumeID(inputVolumeNode.GetID())
        lm = slicer.app.layoutManager()
        lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutOneUpGreenSliceView)
        # Fit slice to window
        sliceNodes = slicer.util.getNodes('vtkMRMLSliceNode*')
        layoutManager = slicer.app.layoutManager()
        for sliceNode in sliceNodes.values():
            sliceWidget = layoutManager.sliceWidget(sliceNode.GetLayoutName())
            if sliceWidget:
                sliceWidget.sliceLogic().FitSliceToAll()
            #endif
        #endfor
               
        # Remove old Fiducial nodes
        nodes = slicer.util.getNodesByClass('vtkMRMLMarkupsFiducialNode')
        for f in nodes:
            if ((f.GetName() == volumeType+"Point") ):
                    slicer.mrmlScene.RemoveNode(f)
            #endif
        #endfor
  
        # Reset global point label
        inputPoint = [0,0,0]
        inputPointEdt.setText("[0, 0, 0]")
        # Check if a volume is selected
        #
        if not inputVolumeNode:
            print >> sys.stderr, "You need to select a "+ volumeType +" image first."
            return -1
        #endif
        #TODO: reduce this code
        if volumeType=="fixed":
             self.fixedVolumeNode = inputVolumeNode  
             self.fixedPointEdt = inputPointEdt
             self.fixedMarkupNode = slicer.vtkMRMLMarkupsFiducialNode()
             self.fixedMarkupNode.SetName(volumeType+"Point")
             slicer.mrmlScene.AddNode(self.fixedMarkupNode)
             # Start Fiducial Placement Mode in Slicer
             placeModePersistance = 0
             slicer.modules.markups.logic().StartPlaceMode(placeModePersistance)
             # Observe scene for updates
             self.fixedMarkupNode.AddObserver(self.fixedMarkupNode.MarkupAddedEvent,   self.convRAS2IJK)
             self.fixedMarkupNode.AddObserver(self.fixedMarkupNode.MarkupRemovedEvent, self.convRAS2IJK)
             self.fixedMarkupNode.AddObserver(self.fixedMarkupNode.PointModifiedEvent, self.convRAS2IJK)             
        elif volumeType=="moving":
             self.movingVolumeNode = inputVolumeNode  
             self.movingPointEdt = inputPointEdt
             self.movingMarkupNode = slicer.vtkMRMLMarkupsFiducialNode()
             self.movingMarkupNode.SetName(volumeType+"Point")
             slicer.mrmlScene.AddNode(self.movingMarkupNode)
             # Start Fiducial Placement Mode in Slicer
             placeModePersistance = 0
             slicer.modules.markups.logic().StartPlaceMode(placeModePersistance)

             # Observe scene for updates
             self.movingMarkupNode.AddObserver(self.movingMarkupNode.MarkupAddedEvent,   self.convRAS2IJK)
             self.movingMarkupNode.AddObserver(self.movingMarkupNode.MarkupRemovedEvent, self.convRAS2IJK)
             self.movingMarkupNode.AddObserver(self.movingMarkupNode.PointModifiedEvent, self.convRAS2IJK)
示例#26
0
    def setupScene(self):  # applet specific
        logging.debug("setupScene")
        Guidelet.setupScene(self)

        logging.debug("Create transforms")

        self.cauteryTipToCautery = slicer.util.getNode("CauteryTipToCautery")
        if not self.cauteryTipToCautery:
            self.cauteryTipToCautery = slicer.vtkMRMLLinearTransformNode()
            self.cauteryTipToCautery.SetName("CauteryTipToCautery")
            m = self.readTransformFromSettings("CauteryTipToCautery")
            if m:
                self.cauteryTipToCautery.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.cauteryTipToCautery)

        self.cauteryModelToCauteryTip = slicer.util.getNode("CauteryModelToCauteryTip")
        if not self.cauteryModelToCauteryTip:
            self.cauteryModelToCauteryTip = slicer.vtkMRMLLinearTransformNode()
            self.cauteryModelToCauteryTip.SetName("CauteryModelToCauteryTip")
            m = self.readTransformFromSettings("CauteryModelToCauteryTip")
            if m:
                self.cauteryModelToCauteryTip.SetMatrixTransformToParent(m)
            self.cauteryModelToCauteryTip.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.cauteryModelToCauteryTip)

        self.needleTipToNeedle = slicer.util.getNode("NeedleTipToNeedle")
        if not self.needleTipToNeedle:
            self.needleTipToNeedle = slicer.vtkMRMLLinearTransformNode()
            self.needleTipToNeedle.SetName("NeedleTipToNeedle")
            m = self.readTransformFromSettings("NeedleTipToNeedle")
            if m:
                self.needleTipToNeedle.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.needleTipToNeedle)

        self.needleModelToNeedleTip = slicer.util.getNode("NeedleModelToNeedleTip")
        if not self.needleModelToNeedleTip:
            self.needleModelToNeedleTip = slicer.vtkMRMLLinearTransformNode()
            self.needleModelToNeedleTip.SetName("NeedleModelToNeedleTip")
            m = self.readTransformFromSettings("NeedleModelToNeedleTip")
            if m:
                self.needleModelToNeedleTip.SetMatrixTransformToParent(m)
            self.needleModelToNeedleTip.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.needleModelToNeedleTip)

        self.cauteryCameraToCautery = slicer.util.getNode("CauteryCameraToCautery")
        if not self.cauteryCameraToCautery:
            self.cauteryCameraToCautery = slicer.vtkMRMLLinearTransformNode()
            self.cauteryCameraToCautery.SetName("CauteryCameraToCautery")
            m = vtk.vtkMatrix4x4()
            m.SetElement(0, 0, 0)
            m.SetElement(0, 2, -1)
            m.SetElement(1, 1, 0)
            m.SetElement(1, 0, 1)
            m.SetElement(2, 2, 0)
            m.SetElement(2, 1, -1)
            self.cauteryCameraToCautery.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.cauteryCameraToCautery)

        self.CauteryToNeedle = slicer.util.getNode("CauteryToNeedle")
        if not self.CauteryToNeedle:
            self.CauteryToNeedle = slicer.vtkMRMLLinearTransformNode()
            self.CauteryToNeedle.SetName("CauteryToNeedle")
            slicer.mrmlScene.AddNode(self.CauteryToNeedle)

        # Create transforms that will be updated through OpenIGTLink

        self.cauteryToReference = slicer.util.getNode("CauteryToReference")
        if not self.cauteryToReference:
            self.cauteryToReference = slicer.vtkMRMLLinearTransformNode()
            self.cauteryToReference.SetName("CauteryToReference")
            slicer.mrmlScene.AddNode(self.cauteryToReference)

        self.needleToReference = slicer.util.getNode("NeedleToReference")
        if not self.needleToReference:
            self.needleToReference = slicer.vtkMRMLLinearTransformNode()
            self.needleToReference.SetName("NeedleToReference")
            slicer.mrmlScene.AddNode(self.needleToReference)

        # Cameras
        logging.debug("Create cameras")

        self.LeftCamera = slicer.util.getNode("Left Camera")
        if not self.LeftCamera:
            self.LeftCamera = slicer.vtkMRMLCameraNode()
            self.LeftCamera.SetName("Left Camera")
            slicer.mrmlScene.AddNode(self.LeftCamera)

        self.RightCamera = slicer.util.getNode("Right Camera")
        if not self.RightCamera:
            self.RightCamera = slicer.vtkMRMLCameraNode()
            self.RightCamera.SetName("Right Camera")
            slicer.mrmlScene.AddNode(self.RightCamera)

        # Models
        logging.debug("Create models")

        self.cauteryModel_CauteryTip = slicer.util.getNode("CauteryModel")
        if not self.cauteryModel_CauteryTip:
            if self.parameterNode.GetParameter("TestMode") == "True":
                moduleDirectoryPath = slicer.modules.lumpnav.path.replace("LumpNav.py", "")
                slicer.util.loadModel(
                    qt.QDir.toNativeSeparators(moduleDirectoryPath + "../../../models/temporary/cautery.stl")
                )
                self.cauteryModel_CauteryTip = slicer.util.getNode(pattern="cautery")
            else:
                slicer.modules.createmodels.logic().CreateNeedle(100, 1.0, 2.5, 0)
                self.cauteryModel_CauteryTip = slicer.util.getNode(pattern="NeedleModel")
                self.cauteryModel_CauteryTip.GetDisplayNode().SetColor(1.0, 1.0, 0)
            self.cauteryModel_CauteryTip.SetName("CauteryModel")

        self.needleModel_NeedleTip = slicer.util.getNode("NeedleModel")
        if not self.needleModel_NeedleTip:
            slicer.modules.createmodels.logic().CreateNeedle(80, 1.0, 2.5, 0)
            self.needleModel_NeedleTip = slicer.util.getNode(pattern="NeedleModel")
            self.needleModel_NeedleTip.GetDisplayNode().SetColor(0.333333, 1.0, 1.0)
            self.needleModel_NeedleTip.SetName("NeedleModel")
            self.needleModel_NeedleTip.GetDisplayNode().SliceIntersectionVisibilityOn()

        # Create surface from point set

        logging.debug("Create surface from point set")

        self.tumorModel_Needle = slicer.util.getNode("TumorModel")
        if not self.tumorModel_Needle:
            self.tumorModel_Needle = slicer.vtkMRMLModelNode()
            self.tumorModel_Needle.SetName("TumorModel")
            sphereSource = vtk.vtkSphereSource()
            sphereSource.SetRadius(0.001)
            self.tumorModel_Needle.SetPolyDataConnection(sphereSource.GetOutputPort())
            slicer.mrmlScene.AddNode(self.tumorModel_Needle)
            # Add display node
            modelDisplayNode = slicer.vtkMRMLModelDisplayNode()
            modelDisplayNode.SetColor(0, 1, 0)  # Green
            modelDisplayNode.BackfaceCullingOff()
            modelDisplayNode.SliceIntersectionVisibilityOn()
            modelDisplayNode.SetSliceIntersectionThickness(4)
            modelDisplayNode.SetOpacity(0.3)  # Between 0-1, 1 being opaque
            slicer.mrmlScene.AddNode(modelDisplayNode)
            self.tumorModel_Needle.SetAndObserveDisplayNodeID(modelDisplayNode.GetID())

        tumorMarkups_Needle = slicer.util.getNode("T")
        if not tumorMarkups_Needle:
            tumorMarkups_Needle = slicer.vtkMRMLMarkupsFiducialNode()
            tumorMarkups_Needle.SetName("T")
            slicer.mrmlScene.AddNode(tumorMarkups_Needle)
            tumorMarkups_Needle.CreateDefaultDisplayNodes()
            tumorMarkups_Needle.GetDisplayNode().SetTextScale(0)
        self.setAndObserveTumorMarkupsNode(tumorMarkups_Needle)

        # Set up breach warning node
        logging.debug("Set up breach warning")
        self.breachWarningNode = slicer.util.getNode("LumpNavBreachWarning")

        if not self.breachWarningNode:
            self.breachWarningNode = slicer.mrmlScene.CreateNodeByClass("vtkMRMLBreachWarningNode")
            self.breachWarningNode.SetName("LumpNavBreachWarning")
            slicer.mrmlScene.AddNode(self.breachWarningNode)
            self.breachWarningNode.SetPlayWarningSound(True)
            self.breachWarningNode.SetWarningColor(1, 0, 0)
            self.breachWarningNode.SetOriginalColor(self.tumorModel_Needle.GetDisplayNode().GetColor())
            self.breachWarningNode.SetAndObserveToolTransformNodeId(self.cauteryTipToCautery.GetID())
            self.breachWarningNode.SetAndObserveWatchedModelNodeID(self.tumorModel_Needle.GetID())

        # Set up breach warning light
        import BreachWarningLight

        logging.debug("Set up breach warning light")
        self.breachWarningLightLogic = BreachWarningLight.BreachWarningLightLogic()
        self.breachWarningLightLogic.setMarginSizeMm(
            float(self.parameterNode.GetParameter("BreachWarningLightMarginSizeMm"))
        )
        if self.parameterNode.GetParameter("EnableBreachWarningLight") == "True":
            logging.debug("BreachWarningLight: active")
            self.breachWarningLightLogic.startLightFeedback(self.breachWarningNode, self.connectorNode)
        else:
            logging.debug("BreachWarningLight: shutdown")
            self.breachWarningLightLogic.shutdownLight(self.connectorNode)

        # Build transform tree
        logging.debug("Set up transform tree")
        self.cauteryToReference.SetAndObserveTransformNodeID(self.ReferenceToRas.GetID())
        self.cauteryCameraToCautery.SetAndObserveTransformNodeID(self.cauteryToReference.GetID())
        self.cauteryTipToCautery.SetAndObserveTransformNodeID(self.cauteryToReference.GetID())
        self.cauteryModelToCauteryTip.SetAndObserveTransformNodeID(self.cauteryTipToCautery.GetID())
        self.needleToReference.SetAndObserveTransformNodeID(self.ReferenceToRas.GetID())
        self.needleTipToNeedle.SetAndObserveTransformNodeID(self.needleToReference.GetID())
        self.needleModelToNeedleTip.SetAndObserveTransformNodeID(self.needleTipToNeedle.GetID())
        self.cauteryModel_CauteryTip.SetAndObserveTransformNodeID(self.cauteryModelToCauteryTip.GetID())
        self.needleModel_NeedleTip.SetAndObserveTransformNodeID(self.needleModelToNeedleTip.GetID())
        self.tumorModel_Needle.SetAndObserveTransformNodeID(self.needleToReference.GetID())
        self.tumorMarkups_Needle.SetAndObserveTransformNodeID(self.needleToReference.GetID())
        # self.liveUltrasoundNode_Reference.SetAndObserveTransformNodeID(self.ReferenceToRas.GetID())

        # Hide slice view annotations (patient name, scale, color bar, etc.) as they
        # decrease reslicing performance by 20%-100%
        logging.debug("Hide slice view annotations")
        import DataProbe

        dataProbeUtil = DataProbe.DataProbeLib.DataProbeUtil()
        dataProbeParameterNode = dataProbeUtil.getParameterNode()
        dataProbeParameterNode.SetParameter("showSliceViewAnnotations", "0")
    def setup(self):

        self.__clippingModelNode = None
        self.__clippingMarkupNode = None
        self.__clippingMarkupNodeObserver = None

        self.toFids = slicer.vtkMRMLMarkupsFiducialNode()
        self.fromFids = slicer.vtkMRMLMarkupsFiducialNode()
        self.toFids.SetName('toFids')
        self.fromFids.SetName('fromFids')
        slicer.mrmlScene.AddNode(self.toFids)
        slicer.mrmlScene.AddNode(self.fromFids)
        self.__markupList = []
        # create a callapsible button
        collapsibleButton = ctk.ctkCollapsibleButton()
        collapsibleButton.text = "Cubic Spline Image Segmentation Correction"

        # bind collapsibleButton to root Layout
        self.layout.addWidget(collapsibleButton)

        # new layout for collapsible button
        self.formLayout = qt.QFormLayout(collapsibleButton)

        # volume selector
        self.formFrame = qt.QFrame(collapsibleButton)
        self.formFrame1 = qt.QFrame(collapsibleButton)
        self.formFrame4 = qt.QFrame(collapsibleButton)
        self.formFrame2 = qt.QFrame(collapsibleButton)
        self.formFrame5 = qt.QFrame(collapsibleButton)
        self.formFrame3 = qt.QFrame(collapsibleButton)

        # set a layout to horizontal
        self.formFrame.setLayout(qt.QHBoxLayout())
        self.formFrame1.setLayout(qt.QHBoxLayout())
        self.formFrame4.setLayout(qt.QHBoxLayout())
        self.formFrame2.setLayout(qt.QHBoxLayout())
        self.formFrame5.setLayout(qt.QHBoxLayout())
        self.formFrame3.setLayout(qt.QHBoxLayout())

        # bind a new frame to existing layout in collapsible menu
        self.formLayout.addWidget(self.formFrame)
        self.formLayout.addWidget(self.formFrame1)
        self.formLayout.addWidget(self.formFrame4)
        self.formLayout.addWidget(self.formFrame2)
        self.formLayout.addWidget(self.formFrame5)
        self.formLayout.addWidget(self.formFrame3)

        # creating new volume selector
        self.inputSelector = qt.QLabel("Input Volume: ", self.formFrame)
        self.formFrame.layout().addWidget(self.inputSelector)
        self.inputSelector = slicer.qMRMLNodeComboBox(self.formFrame)
        self.inputSelector.nodeTypes = (("vtkMRMLScalarVolumeNode"), "")
        self.inputSelector.addEnabled = False
        self.inputSelector.removeEnabled = False

        self.inputSelector1 = qt.QLabel("Input segmentation: ",
                                        self.formFrame1)
        self.formFrame1.layout().addWidget(self.inputSelector1)
        self.inputSelector1 = slicer.qMRMLNodeComboBox(self.formFrame1)
        self.inputSelector1.nodeTypes = (("vtkMRMLSegmentationNode"), "")
        self.inputSelector1.addEnabled = False
        self.inputSelector1.removeEnabled = False

        self.inputSelector4 = qt.QLabel("Input transformation: ",
                                        self.formFrame4)
        self.formFrame4.layout().addWidget(self.inputSelector4)
        self.inputSelector4 = slicer.qMRMLNodeComboBox(self.formFrame4)
        self.inputSelector4.nodeTypes = (("vtkMRMLTransformNode"), "")
        self.inputSelector4.addEnabled = False
        self.inputSelector4.removeEnabled = False

        self.inputSelector2 = qt.QLabel("Set default Segmentation display : ",
                                        self.formFrame2)
        self.formFrame2.layout().addWidget(self.inputSelector2)

        self.inputSelector5 = qt.QLabel("Add markups : ", self.formFrame3)
        self.formFrame5.layout().addWidget(self.inputSelector5)

        self.inputSelector3 = qt.QLabel("Segmentation Correction: ",
                                        self.formFrame3)
        self.formFrame3.layout().addWidget(self.inputSelector3)

        # bind the current volume selector to the current scene of slicer
        self.inputSelector.setMRMLScene(slicer.mrmlScene)
        self.inputSelector1.setMRMLScene(slicer.mrmlScene)
        self.inputSelector4.setMRMLScene(slicer.mrmlScene)

        # bind the input selector to the frame
        self.formFrame.layout().addWidget(self.inputSelector)
        self.formFrame1.layout().addWidget(self.inputSelector1)
        self.formFrame4.layout().addWidget(self.inputSelector4)

        # testing
        button = qt.QPushButton("Load Volume")
        self.formFrame.layout().addWidget(button)
        button.connect("clicked()", slicer.util.openAddVolumeDialog)
        button.show()

        # button for importing mesh files
        button1 = qt.QPushButton("Load Segemntation")
        self.formFrame1.layout().addWidget(button1)
        button1.connect("clicked()", slicer.util.openAddSegmentationDialog)
        button1.show()

        # button for importing mesh files
        button4 = qt.QPushButton("Load Transform")
        self.formFrame4.layout().addWidget(button4)
        button4.connect("clicked()", slicer.util.openAddTransformDialog)
        button4.show()

        # button for setting default segmentation display
        button2 = qt.QPushButton("Set default")
        self.formFrame2.layout().addWidget(button2)
        button2.connect("clicked(bool)", self.SetDefaultValuesClicked)
        button2.show()

        # button for Final work
        self.button5 = qt.QToolButton()
        self.button5.icon = qt.QIcon(
            os.path.join(os.path.dirname(__file__),
                         'MarkupsMouseModePlace.png'))
        self.button5.setCheckable(1)
        self.formFrame5.layout().addWidget(self.button5)
        self.button5.connect("clicked(bool)", self.enableaddmarkuponclick)
        self.button5.show()

        # button for Final work
        button3 = qt.QPushButton("Do corrections")
        self.formFrame3.layout().addWidget(button3)
        button3.connect("clicked(bool)", self.do_correctionsClicked)
        button3.show()
  def __init__(self, modelNode):
    self.modelNode = modelNode
    self.toolTipToTool = None
    self.toolToReference = None
    self.modelTransform = None
  
    self.transformedModel = slicer.util.getNode('Transformed Model')
    if not self.transformedModel:
      self.transformedModel = slicer.vtkMRMLModelNode()
      self.transformedModel.SetName('Transformed Model')
      self.transformedModel.SetAndObservePolyData(self.modelNode.GetPolyData())     
      modelDisplay = slicer.vtkMRMLModelDisplayNode()
      modelDisplay.SetSliceIntersectionVisibility(True)
      modelDisplay.SetColor(0,1,0)
      slicer.mrmlScene.AddNode(modelDisplay)      
      self.transformedModel.SetAndObserveDisplayNodeID(modelDisplay.GetID())      
      slicer.mrmlScene.AddNode(self.transformedModel)
      self.transformedModel.SetDisplayVisibility(False)     

    self.closestFiducial = slicer.util.getNode('CP')
    if not self.closestFiducial:
      self.closestFiducial = slicer.vtkMRMLMarkupsFiducialNode()  
      self.closestFiducial.SetName('CP')
      self.closestFiducial.AddFiducial(0, 0, 0)
      self.closestFiducial.SetNthFiducialLabel(0, '')
      slicer.mrmlScene.AddNode(self.closestFiducial)
      self.closestFiducial.SetDisplayVisibility(False)
      self.closestFiducial.GetDisplayNode().SetGlyphScale(3.0)
      self.closestFiducial.GetDisplayNode().SetGlyphType(4) # ThickCross2D
      self.closestFiducial.GetDisplayNode().SetSelectedColor(0,0,1)

    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.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
示例#29
0
    def FiducialButtonClick(self, volumeType):

        # Remove old Fiducial nodes
        nodes = slicer.util.getNodesByClass('vtkMRMLMarkupsFiducialNode')
        for f in nodes:
            if ((f.GetName() == "FixedImageFiducial")
                    or (f.GetName() == "MovingImageFiducial")):
                slicer.mrmlScene.RemoveNode(f)

        # Create Fiducial Node for the cochlea location in both images
        if (volumeType == "fixed"):
            print(" ..... getting cochlea location in the fixed image")
            # Reset global point label
            self.fixedPoint = [0, 0, 0]
            self.fixedPointLbl.setText("[0, 0, 0]")
            # Check if a volume is selected
            if not self.fixedSelectorCoBx.currentNode():
                print >> sys.stderr, "ERROR: No fixed volume"
                return -1

            # TODO bug: if the fiducial placement mode is cancelled using the Slicer Fiducial button, the button remains colored
            self.fixedFiducialBtn.setStyleSheet(
                "QPushButton{ background-color: DarkSeaGreen  }")
            self.movingFiducialBtn.setStyleSheet(
                "QPushButton{ background-color: White  }")

            self.fixedFiducialNode = slicer.vtkMRMLMarkupsFiducialNode()
            self.fixedFiducialNode.SetName("FixedImageFiducial")
            slicer.mrmlScene.AddNode(self.fixedFiducialNode)

            self.displayCoronalView(self.fixedSelectorCoBx.currentNode())

            # Start Fiducial Placement Mode in Slicer
            placeModePersistance = 0
            slicer.modules.markups.logic().StartPlaceMode(placeModePersistance)

            # Observe scene for updates
            self.fixedFiducialNode.AddObserver(
                self.fixedFiducialNode.MarkupAddedEvent, self.convRAS2IJK)
            self.fixedFiducialNode.AddObserver(
                self.fixedFiducialNode.MarkupRemovedEvent, self.convRAS2IJK)
        elif (volumeType == "moving"):
            print(" ..... getting cochlea location in the moving image")
            # Reset global point label
            self.movingPoint = [0, 0, 0]
            self.movingPointLbl.setText("[0, 0, 0]")
            # Check if a volume is selected
            if not self.movingSelectorCoBx.currentNode():
                print >> sys.stderr, "ERROR: No moving volume, Bad Path or DICOM."
                return -1

            # TODO bug: if the fiducial placement mode is cancelled using the Slicer Fiducial button, the button remains colored
            self.movingFiducialBtn.setStyleSheet(
                "QPushButton{ background-color: DarkSeaGreen  }")
            self.fixedFiducialBtn.setStyleSheet(
                "QPushButton{ background-color: White  }")

            self.movingFiducialNode = slicer.vtkMRMLMarkupsFiducialNode()
            self.movingFiducialNode.SetName("MovingImageFiducial")
            slicer.mrmlScene.AddNode(self.movingFiducialNode)

            self.displayCoronalView(self.movingSelectorCoBx.currentNode())

            # Start Fiducial Placement Mode in Slicer
            placeModePersistance = 0
            slicer.modules.markups.logic().StartPlaceMode(placeModePersistance)

            # Observe scene for updates
            self.movingFiducialNode.AddObserver(
                self.movingFiducialNode.MarkupAddedEvent, self.convRAS2IJK)
            self.movingFiducialNode.AddObserver(
                self.movingFiducialNode.MarkupRemovedEvent, self.convRAS2IJK)
  def run(self,enableScreenshots=0,screenshotScaleFactor=1):
    """
    Run the actual algorithm
    """
    self.delayDisplay('Running test of the Neurosurgical Planning tutorial')

    moduleSelector = slicer.util.mainWindow().moduleSelector()
    #
    # first load the data
    #
    if enableScreenshots == 1:
      # for the tutorial, do it through the welcome module
      moduleSelector.selectModule('Welcome')
      self.delayDisplay("Screenshot")
      self.takeScreenshot('NeurosurgicalPlanning-Welcome','Welcome module',-1,screenshotScaleFactor)

    # but use the sample data module logic to load it for the self test
    import SampleData
    sampleDataLogic = SampleData.SampleDataLogic()
    self.delayDisplay("Getting Baseline volume")
    baselineVolume = sampleDataLogic.downloadWhiteMatterExplorationBaselineVolume()

    self.delayDisplay("Getting DTI volume")
    dtiVolume = sampleDataLogic.downloadWhiteMatterExplorationDTIVolume()

    if enableScreenshots == 1:
      self.delayDisplay("Screenshot")
      self.takeScreenshot('NeurosurgicalPlanning-Loaded','Data loaded',-1,screenshotScaleFactor)

    #
    # link the viewers
    #

    if enableScreenshots == 1:
      # for the tutorial, pop up the linking control
      # TODO: pipPopup is not exposed to python
      sliceController = slicer.app.layoutManager().sliceWidget("Red").sliceController()
      # sliceController.pinPopup(1)
      # self.delayDisplay("Screenshot")
      # self.takeScreenshot('NeurosurgicalPlanning-Link','Link slice viewers',-1,screenshotScaleFactor)
      # sliceController.pinPopup(0)

    sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
    compositeNode = sliceLogic.GetSliceCompositeNode()
    compositeNode.SetLinkedControl(1)

    #
    # baseline in the background
    #
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(baselineVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()

    if enableScreenshots == 1:
      self.delayDisplay("Screenshot")
      self.takeScreenshot('NeurosurgicalPlanning-Baseline','Baseline in background',-1,screenshotScaleFactor)

    #
    # adjust window level on baseline
    #
    moduleSelector.selectModule('Volumes')
    baselineVolume.GetDisplayNode().SetWindow(2600)
    baselineVolume.GetDisplayNode().SetLevel(1206)
    if enableScreenshots == 1:
      self.delayDisplay("Screenshot")
      self.takeScreenshot('NeurosurgicalPlanning-WindowLevel','Set W/L on baseline',-1,screenshotScaleFactor)

    #
    # switch to red slice only
    #
    lm = slicer.app.layoutManager()
    lm.setLayout(6)
    if enableScreenshots == 1:
      self.delayDisplay("Screenshot")
      self.takeScreenshot('NeurosurgicalPlanning-RedSliceOnly','Set layout to Red Slice only',-1,screenshotScaleFactor)

    #
    # skip segmentation of tumour
    #

    #
    # switch to conventional layout
    #
    lm.setLayout(2)

    #
    # skip tractography label map seeding
    #


    #
    # tractography fiducial seeding
    #
    moduleSelector.selectModule('TractographyInteractiveSeeding')
    if enableScreenshots == 1:
     self.delayDisplay("Screenshot")
     self.takeScreenshot('NeurosurgicalPlanning-TIS','Showing Tractography Interactive Seeding Module',-1,screenshotScaleFactor)

    # DTI in background
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(dtiVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()

    # DTI visible in 3D
    sliceNode = sliceLogic.GetSliceNode()
    sliceLogic.StartSliceNodeInteraction(128)
    sliceNode.SetSliceVisible(1)
    sliceLogic.EndSliceNodeInteraction()

    if enableScreenshots == 1:
     self.delayDisplay("Screenshot")
     self.takeScreenshot('NeurosurgicalPlanning-TIS-DTI','DTI volume with Tractography Interactive Seeding Module',-1,screenshotScaleFactor)

    # place a fiducial
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)
    fidNode = slicer.vtkMRMLMarkupsFiducialNode()
    fidNode.SetName('F')
    slicer.mrmlScene.AddNode(fidNode)
    fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
    r = 28.338526
    a = 34.064367
    s = 58.74121
    fidNode.AddFiducial(r,a,s)

    # make it active
    selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
    if (selectionNode != None):
      selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

    if enableScreenshots == 1:
     self.delayDisplay("Screenshot")
     self.takeScreenshot('NeurosurgicalPlanning-TIS-Fid1','Fiducial in Tractography Interactive Seeding Module',-1,screenshotScaleFactor)


    # set up the arguments
    wr = slicer.modules.tractographyinteractiveseeding.widgetRepresentation()
    wr.setDiffusionTensorVolumeNode(dtiVolume)
    # fiber bundle is created automatically
    wr.setSeedingNode(fidNode)
    wr.setMinimumPath(10)
    wr.setStoppingValue(0.15)

    if enableScreenshots == 1:
     self.delayDisplay("Screenshot")
     self.takeScreenshot('NeurosurgicalPlanning-TIS-Args','Tractography Interactive Seeding arguments',-1,screenshotScaleFactor)

    self.delayDisplay("Moving the fiducial")
    for y in range(-20, 100, 5):
      msg = "Moving the fiducial to y = " + str(y)
      self.delayDisplay(msg,250)
      fidNode.SetNthFiducialPosition(0, r, y, s)

    if enableScreenshots == 1:
     self.delayDisplay("Screenshot")
     self.takeScreenshot('NeurosurgicalPlanning-TIS-Moved','Moved fiducial and did Tractography Interactive Seeding',-1,screenshotScaleFactor)

    return True
示例#31
0
    def run(self):
        """
    Run the actual algorithm
    """
        print('Running test of the Neurosurgical Planning tutorial')

        #
        # first load the data
        #
        import SampleData
        sampleDataLogic = SampleData.SampleDataLogic()
        print("Getting Baseline volume")
        baselineVolume = sampleDataLogic.downloadWhiteMatterExplorationBaselineVolume(
        )

        print("Getting DTI volume")
        dtiVolume = sampleDataLogic.downloadWhiteMatterExplorationDTIVolume()

        #
        # link the viewers
        #
        sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
        compositeNode = sliceLogic.GetSliceCompositeNode()
        compositeNode.SetLinkedControl(1)

        #
        # baseline in the background
        #
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetBackgroundVolumeID(baselineVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()

        #
        # adjust window level on baseline
        #
        mainWindow = slicer.util.mainWindow()
        mainWindow.moduleSelector().selectModule('Volumes')
        baselineVolume.GetDisplayNode().SetWindow(2600)
        baselineVolume.GetDisplayNode().SetLevel(1206)

        #
        # switch to red slice only
        #
        lm = slicer.app.layoutManager()
        lm.setLayout(6)

        #
        # skip segmentation of tumour
        #

        #
        # switch to conventional layout
        #
        lm.setLayout(2)

        #
        # skip tractography label map seeding
        #

        #
        # tractography fiducial seeding
        #
        mainWindow.moduleSelector().selectModule(
            'TractographyInteractiveSeeding')
        # DTI in background
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetBackgroundVolumeID(dtiVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()
        # place a fiducial
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
        r = 28.338526
        a = 34.064367
        s = 58.74121
        fidNode.AddFiducial(r, a, s)

        # make it active
        selectionNode = slicer.mrmlScene.GetNodeByID(
            "vtkMRMLSelectionNodeSingleton")
        if (selectionNode != None):
            selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

        # set up the arguments
        wr = slicer.modules.tractographyinteractiveseeding.widgetRepresentation(
        )
        wr.setDiffusionTensorVolumeNode(dtiVolume)
        # fiber bundle is created automatically
        wr.setSeedingNode(fidNode)
        wr.setMinimumPath(10)
        wr.setStoppingValue(0.15)

        print("Moving the fiducial")
        for y in range(-20, 100, 5):
            msg = "Moving the fiducial to y = " + str(y)
            print msg
            moveMsg = qt.QDialog()
            moveMsg.setLayout(qt.QVBoxLayout())
            moveMsg.layout().addWidget(qt.QLabel(msg))
            qt.QTimer.singleShot(250, moveMsg.close)
            moveMsg.exec_()
            fidNode.SetNthFiducialPosition(0, r, y, s)

        return True
示例#32
0
    def setupScene(self):  #applet specific
        logging.debug('setupScene')
        Guidelet.setupScene(self)

        logging.debug('Create transforms')

        self.cauteryTipToCautery = slicer.util.getNode('CauteryTipToCautery')
        if not self.cauteryTipToCautery:
            self.cauteryTipToCautery = slicer.vtkMRMLLinearTransformNode()
            self.cauteryTipToCautery.SetName("CauteryTipToCautery")
            m = self.readTransformFromSettings('CauteryTipToCautery')
            if m:
                self.cauteryTipToCautery.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.cauteryTipToCautery)

        self.cauteryModelToCauteryTip = slicer.util.getNode(
            'CauteryModelToCauteryTip')
        if not self.cauteryModelToCauteryTip:
            self.cauteryModelToCauteryTip = slicer.vtkMRMLLinearTransformNode()
            self.cauteryModelToCauteryTip.SetName("CauteryModelToCauteryTip")
            m = self.readTransformFromSettings('CauteryModelToCauteryTip')
            if m:
                self.cauteryModelToCauteryTip.SetMatrixTransformToParent(m)
            self.cauteryModelToCauteryTip.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.cauteryModelToCauteryTip)

        self.needleTipToNeedle = slicer.util.getNode('NeedleTipToNeedle')
        if not self.needleTipToNeedle:
            self.needleTipToNeedle = slicer.vtkMRMLLinearTransformNode()
            self.needleTipToNeedle.SetName("NeedleTipToNeedle")
            m = self.readTransformFromSettings('NeedleTipToNeedle')
            if m:
                self.needleTipToNeedle.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.needleTipToNeedle)

        self.needleModelToNeedleTip = slicer.util.getNode(
            'NeedleModelToNeedleTip')
        if not self.needleModelToNeedleTip:
            self.needleModelToNeedleTip = slicer.vtkMRMLLinearTransformNode()
            self.needleModelToNeedleTip.SetName("NeedleModelToNeedleTip")
            m = self.readTransformFromSettings('NeedleModelToNeedleTip')
            if m:
                self.needleModelToNeedleTip.SetMatrixTransformToParent(m)
            self.needleModelToNeedleTip.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.needleModelToNeedleTip)

        self.cauteryCameraToCautery = slicer.util.getNode(
            'CauteryCameraToCautery')
        if not self.cauteryCameraToCautery:
            self.cauteryCameraToCautery = slicer.vtkMRMLLinearTransformNode()
            self.cauteryCameraToCautery.SetName("CauteryCameraToCautery")
            m = vtk.vtkMatrix4x4()
            m.SetElement(0, 0, 0)
            m.SetElement(0, 2, -1)
            m.SetElement(1, 1, 0)
            m.SetElement(1, 0, 1)
            m.SetElement(2, 2, 0)
            m.SetElement(2, 1, -1)
            self.cauteryCameraToCautery.SetMatrixTransformToParent(m)
            slicer.mrmlScene.AddNode(self.cauteryCameraToCautery)

        self.CauteryToNeedle = slicer.util.getNode('CauteryToNeedle')
        if not self.CauteryToNeedle:
            self.CauteryToNeedle = slicer.vtkMRMLLinearTransformNode()
            self.CauteryToNeedle.SetName("CauteryToNeedle")
            slicer.mrmlScene.AddNode(self.CauteryToNeedle)

        # Create transforms that will be updated through OpenIGTLink

        self.cauteryToReference = slicer.util.getNode('CauteryToReference')
        if not self.cauteryToReference:
            self.cauteryToReference = slicer.vtkMRMLLinearTransformNode()
            self.cauteryToReference.SetName("CauteryToReference")
            slicer.mrmlScene.AddNode(self.cauteryToReference)

        self.needleToReference = slicer.util.getNode('NeedleToReference')
        if not self.needleToReference:
            self.needleToReference = slicer.vtkMRMLLinearTransformNode()
            self.needleToReference.SetName("NeedleToReference")
            slicer.mrmlScene.AddNode(self.needleToReference)

        # Cameras
        logging.debug('Create cameras')

        self.LeftCamera = slicer.util.getNode('Left Camera')
        if not self.LeftCamera:
            self.LeftCamera = slicer.vtkMRMLCameraNode()
            self.LeftCamera.SetName("Left Camera")
            slicer.mrmlScene.AddNode(self.LeftCamera)

        self.RightCamera = slicer.util.getNode('Right Camera')
        if not self.RightCamera:
            self.RightCamera = slicer.vtkMRMLCameraNode()
            self.RightCamera.SetName("Right Camera")
            slicer.mrmlScene.AddNode(self.RightCamera)

        # Models
        logging.debug('Create models')

        self.cauteryModel_CauteryTip = slicer.util.getNode('CauteryModel')
        if not self.cauteryModel_CauteryTip:
            if (self.parameterNode.GetParameter('TestMode') == 'True'):
                moduleDirectoryPath = slicer.modules.lumpnav.path.replace(
                    'LumpNav.py', '')
                slicer.util.loadModel(
                    qt.QDir.toNativeSeparators(
                        moduleDirectoryPath +
                        '../../../models/temporary/cautery.stl'))
                self.cauteryModel_CauteryTip = slicer.util.getNode(
                    pattern="cautery")
            else:
                slicer.modules.createmodels.logic().CreateNeedle(
                    100, 1.0, 2.5, 0)
                self.cauteryModel_CauteryTip = slicer.util.getNode(
                    pattern="NeedleModel")
                self.cauteryModel_CauteryTip.GetDisplayNode().SetColor(
                    1.0, 1.0, 0)
            self.cauteryModel_CauteryTip.SetName("CauteryModel")

        self.needleModel_NeedleTip = slicer.util.getNode('NeedleModel')
        if not self.needleModel_NeedleTip:
            slicer.modules.createmodels.logic().CreateNeedle(80, 1.0, 2.5, 0)
            self.needleModel_NeedleTip = slicer.util.getNode(
                pattern="NeedleModel")
            self.needleModel_NeedleTip.GetDisplayNode().SetColor(
                0.333333, 1.0, 1.0)
            self.needleModel_NeedleTip.SetName("NeedleModel")
            self.needleModel_NeedleTip.GetDisplayNode(
            ).SliceIntersectionVisibilityOn()

        # Create surface from point set

        logging.debug('Create surface from point set')

        self.tumorModel_Needle = slicer.util.getNode('TumorModel')
        if not self.tumorModel_Needle:
            self.tumorModel_Needle = slicer.vtkMRMLModelNode()
            self.tumorModel_Needle.SetName("TumorModel")
            sphereSource = vtk.vtkSphereSource()
            sphereSource.SetRadius(0.001)
            self.tumorModel_Needle.SetPolyDataConnection(
                sphereSource.GetOutputPort())
            slicer.mrmlScene.AddNode(self.tumorModel_Needle)
            # Add display node
            modelDisplayNode = slicer.vtkMRMLModelDisplayNode()
            modelDisplayNode.SetColor(0, 1, 0)  # Green
            modelDisplayNode.BackfaceCullingOff()
            modelDisplayNode.SliceIntersectionVisibilityOn()
            modelDisplayNode.SetSliceIntersectionThickness(4)
            modelDisplayNode.SetOpacity(0.3)  # Between 0-1, 1 being opaque
            slicer.mrmlScene.AddNode(modelDisplayNode)
            self.tumorModel_Needle.SetAndObserveDisplayNodeID(
                modelDisplayNode.GetID())

        tumorMarkups_Needle = slicer.util.getNode('T')
        if not tumorMarkups_Needle:
            tumorMarkups_Needle = slicer.vtkMRMLMarkupsFiducialNode()
            tumorMarkups_Needle.SetName("T")
            slicer.mrmlScene.AddNode(tumorMarkups_Needle)
            tumorMarkups_Needle.CreateDefaultDisplayNodes()
            tumorMarkups_Needle.GetDisplayNode().SetTextScale(0)
        self.setAndObserveTumorMarkupsNode(tumorMarkups_Needle)

        # Set up breach warning node
        logging.debug('Set up breach warning')
        self.breachWarningNode = slicer.util.getNode('LumpNavBreachWarning')

        if not self.breachWarningNode:
            self.breachWarningNode = slicer.mrmlScene.CreateNodeByClass(
                'vtkMRMLBreachWarningNode')
            self.breachWarningNode.SetName("LumpNavBreachWarning")
            slicer.mrmlScene.AddNode(self.breachWarningNode)
            self.breachWarningNode.SetPlayWarningSound(True)
            self.breachWarningNode.SetWarningColor(1, 0, 0)
            self.breachWarningNode.SetOriginalColor(
                self.tumorModel_Needle.GetDisplayNode().GetColor())
            self.breachWarningNode.SetAndObserveToolTransformNodeId(
                self.cauteryTipToCautery.GetID())
            self.breachWarningNode.SetAndObserveWatchedModelNodeID(
                self.tumorModel_Needle.GetID())

        # Set up breach warning light
        import BreachWarningLight
        logging.debug('Set up breach warning light')
        self.breachWarningLightLogic = BreachWarningLight.BreachWarningLightLogic(
        )
        self.breachWarningLightLogic.setMarginSizeMm(
            float(
                self.parameterNode.GetParameter(
                    'BreachWarningLightMarginSizeMm')))
        if (self.parameterNode.GetParameter('EnableBreachWarningLight') ==
                'True'):
            logging.debug("BreachWarningLight: active")
            self.breachWarningLightLogic.startLightFeedback(
                self.breachWarningNode, self.connectorNode)
        else:
            logging.debug("BreachWarningLight: shutdown")
            self.breachWarningLightLogic.shutdownLight(self.connectorNode)

        # Build transform tree
        logging.debug('Set up transform tree')
        self.cauteryToReference.SetAndObserveTransformNodeID(
            self.ReferenceToRas.GetID())
        self.cauteryCameraToCautery.SetAndObserveTransformNodeID(
            self.cauteryToReference.GetID())
        self.cauteryTipToCautery.SetAndObserveTransformNodeID(
            self.cauteryToReference.GetID())
        self.cauteryModelToCauteryTip.SetAndObserveTransformNodeID(
            self.cauteryTipToCautery.GetID())
        self.needleToReference.SetAndObserveTransformNodeID(
            self.ReferenceToRas.GetID())
        self.needleTipToNeedle.SetAndObserveTransformNodeID(
            self.needleToReference.GetID())
        self.needleModelToNeedleTip.SetAndObserveTransformNodeID(
            self.needleTipToNeedle.GetID())
        self.cauteryModel_CauteryTip.SetAndObserveTransformNodeID(
            self.cauteryModelToCauteryTip.GetID())
        self.needleModel_NeedleTip.SetAndObserveTransformNodeID(
            self.needleModelToNeedleTip.GetID())
        self.tumorModel_Needle.SetAndObserveTransformNodeID(
            self.needleToReference.GetID())
        self.tumorMarkups_Needle.SetAndObserveTransformNodeID(
            self.needleToReference.GetID())
        # self.liveUltrasoundNode_Reference.SetAndObserveTransformNodeID(self.ReferenceToRas.GetID())

        # Hide slice view annotations (patient name, scale, color bar, etc.) as they
        # decrease reslicing performance by 20%-100%
        logging.debug('Hide slice view annotations')
        import DataProbe
        dataProbeUtil = DataProbe.DataProbeLib.DataProbeUtil()
        dataProbeParameterNode = dataProbeUtil.getParameterNode()
        dataProbeParameterNode.SetParameter('showSliceViewAnnotations', '0')
  def run(self):
    """
    Run the actual algorithm
    """
    print('Running test of the Neurosurgical Planning tutorial')

    #
    # first load the data
    #
    import SampleData
    sampleDataLogic = SampleData.SampleDataLogic()
    print("Getting Baseline volume")
    baselineVolume = sampleDataLogic.downloadWhiteMatterExplorationBaselineVolume()

    print("Getting DTI volume")
    dtiVolume = sampleDataLogic.downloadWhiteMatterExplorationDTIVolume()

    #
    # link the viewers
    #
    sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
    compositeNode = sliceLogic.GetSliceCompositeNode()
    compositeNode.SetLinkedControl(1)

    #
    # baseline in the background
    #
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(baselineVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()

    #
    # adjust window level on baseline
    #
    mainWindow = slicer.util.mainWindow()
    mainWindow.moduleSelector().selectModule('Volumes')
    baselineVolume.GetDisplayNode().SetWindow(2600)
    baselineVolume.GetDisplayNode().SetLevel(1206)

    #
    # switch to red slice only
    #
    lm = slicer.app.layoutManager()
    lm.setLayout(6)

    #
    # skip segmentation of tumour
    #

    #
    # switch to conventional layout
    #
    lm.setLayout(2)

    #
    # skip tractography label map seeding
    #


    #
    # tractography fiducial seeding
    #
    mainWindow.moduleSelector().selectModule('TractographyInteractiveSeeding')
    # DTI in background
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(dtiVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()
    # place a fiducial
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)
    fidNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(fidNode)
    fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
    r = 28.338526
    a = 34.064367
    s = 58.74121
    fidNode.AddFiducial(r,a,s)

    # make it active
    selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
    if (selectionNode != None):
      selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

    # set up the arguments
    wr = slicer.modules.tractographyinteractiveseeding.widgetRepresentation()
    wr.setDiffusionTensorVolumeNode(dtiVolume)
    # fiber bundle is created automatically
    wr.setSeedingNode(fidNode)
    wr.setMinimumPath(10)
    wr.setStoppingValue(0.15)

    print("Moving the fiducial")
    for y in range(-20, 100, 5):
      msg = "Moving the fiducial to y = " + str(y)
      print msg
      moveMsg = qt.QDialog()
      moveMsg.setLayout(qt.QVBoxLayout())
      moveMsg.layout().addWidget(qt.QLabel(msg))
      qt.QTimer.singleShot(250, moveMsg.close)
      moveMsg.exec_()
      fidNode.SetNthFiducialPosition(0, r, y, s)

    return True
示例#34
0
 def __init__(self):  
   # Member variables
   self.outputLabels = None    
   self.recordedDataBuffer = []   
   self.record = False
   self.reset = False
   self.outputObserverTag = -1
   self.rigidBodyToTrackerTransformNode = None
   self.measurementToMeasurerTransformNode = None
   self.parametersToMeasurerTransformNode = None
   self.plus = None
   self.m = vtk.vtkMatrix4x4()
   self.direction = -1
   self.ras = [0, 0, 0, 1]
   self.d = 0.0
   self.snr = 0
   self.total = 0
   self.LABEL_UPDATE_RATE = 10  
   self.labelUpdateCount = 0
   self.snrThreshold = 40       
   self.distanceMaximumValue = 1000.0       
   self.distanceMinimumValue = 0.0 
   self.lensMaxDistance = 0.0
   self.lensMinDistance = 0.0
   self.normalizingConstant = 0.0
   self.min = -1000.0
   self.addColours = True
   import Viewpoint # Viewpoint
   self.viewpointLogic = Viewpoint.ViewpointLogic()
   self.stopWatch = None # StopWatch        
   # Create style sheets        
   self.errorStyleSheet = "QLabel { color : #FF0000; \
                               font: bold 14px}"
   self.defaultStyleSheet = "QLabel { color : #000000; \
                                 font: bold 14px}"        
   # Create rainbow colour table                                      
   self.colorTable=slicer.vtkMRMLColorTableNode()
   self.colorTable.SetTypeToRainbow ()                                    
   # Add MeasurementPoint
   self.measurementPointMarkupsFiducialNode = slicer.util.getNode('MeasurementPoint')
   if not self.measurementPointMarkupsFiducialNode:
     self.measurementPointMarkupsFiducialNode = slicer.vtkMRMLMarkupsFiducialNode()  
     self.measurementPointMarkupsFiducialNode.SetName('MeasurementPoint')
     self.measurementPointMarkupsFiducialNode.AddFiducial(0, 0, 0)
     self.measurementPointMarkupsFiducialNode.SetNthFiducialLabel(0, '')
     slicer.mrmlScene.AddNode(self.measurementPointMarkupsFiducialNode)
     self.measurementPointMarkupsFiducialNode.GetDisplayNode().SetGlyphScale(2.0)
     self.measurementPointMarkupsFiducialNode.GetDisplayNode().SetGlyphType(13) # Sphere3D
     self.measurementPointMarkupsFiducialNode.GetDisplayNode().SetSelectedColor(1, 0, 0)     
   # Add RecordedModel
   self.recordedModelNode = slicer.util.getNode('RecordedModel')
   if not self.recordedModelNode:
     recordedPoints = vtk.vtkPoints()
     recordedVertices = vtk.vtkCellArray()               
     recordedPolyData = vtk.vtkPolyData()
     recordedPolyData.SetPoints(recordedPoints)
     recordedPolyData.SetVerts(recordedVertices)
     self.recordedModelNode = self.addModelToScene(recordedPolyData, "RecordedModel")    
     self.recordedModelNode.GetModelDisplayNode().SetPointSize(3)
     # Set up coloured scalars  
     colorArray = vtk.vtkDoubleArray()
     colorArray.SetNumberOfComponents(4)
     colorArray.SetName('Colors')
     self.recordedModelNode.GetPolyData().GetPointData().SetScalars(colorArray)          
   # Create share directory
   self.pathToCreatedSaveDir = self.createShareDirectory()    
   # Post-Processing default (for undo)
   self.recordedDataBufferDefault = []
示例#35
0
    def testSegmentationWizard(self):
        """ Test the ChangeTracker module
    """
        self.delayDisplay("Starting the test")

        try:

            self.delayDisplay("Loading sample data")

            import SampleData
            sampleDataLogic = SampleData.SampleDataLogic()
            head = sampleDataLogic.downloadMRHead()
            braintumor1 = sampleDataLogic.downloadMRBrainTumor1()
            braintumor2 = sampleDataLogic.downloadMRBrainTumor2()

            self.delayDisplay("Getting scene variables")

            mainWindow = slicer.util.mainWindow()
            layoutManager = slicer.app.layoutManager()
            threeDView = layoutManager.threeDWidget(0).threeDView()
            redWidget = layoutManager.sliceWidget('Red')
            redController = redWidget.sliceController()
            viewNode = threeDView.mrmlViewNode()
            cameras = slicer.util.getNodes('vtkMRMLCameraNode*')

            mainWindow.moduleSelector().selectModule('SegmentationWizard')
            modelsegmentation_module = slicer.modules.modelsegmentation.widgetRepresentation(
            ).self()

            self.delayDisplay('Select Volumes')
            baselineNode = braintumor1
            followupNode = braintumor2
            modelsegmentation_module.Step1._VolumeSelectStep__enableSubtractionMapping.setChecked(
                True)
            modelsegmentation_module.Step1._VolumeSelectStep__baselineVolumeSelector.setCurrentNode(
                baselineNode)
            modelsegmentation_module.Step1._VolumeSelectStep__followupVolumeSelector.setCurrentNode(
                followupNode)

            self.delayDisplay('Go Forward')
            modelsegmentation_module.workflow.goForward()

            self.delayDisplay('Register Images')
            modelsegmentation_module.Step2.onRegistrationRequest(
                wait_for_completion=True)

            self.delayDisplay('Go Forward')
            modelsegmentation_module.workflow.goForward()

            self.delayDisplay('Normalize Images')
            modelsegmentation_module.Step3.onGaussianNormalizationRequest()

            self.delayDisplay('Subtract Images')
            modelsegmentation_module.Step3.onSubtractionRequest(
                wait_for_completion=True)

            self.delayDisplay('Go Forward')
            modelsegmentation_module.workflow.goForward()

            self.delayDisplay('Load model')

            displayNode = slicer.vtkMRMLMarkupsDisplayNode()
            slicer.mrmlScene.AddNode(displayNode)
            inputMarkup = slicer.vtkMRMLMarkupsFiducialNode()
            inputMarkup.SetName('Test')
            slicer.mrmlScene.AddNode(inputMarkup)
            inputMarkup.SetAndObserveDisplayNodeID(displayNode.GetID())

            modelsegmentation_module.Step4._ROIStep__clippingMarkupSelector.setCurrentNode(
                inputMarkup)

            inputMarkup.AddFiducial(35, -10, -10)
            inputMarkup.AddFiducial(-15, 20, -10)
            inputMarkup.AddFiducial(-25, -25, -10)
            inputMarkup.AddFiducial(-5, -60, -15)
            inputMarkup.AddFiducial(-5, 5, 60)
            inputMarkup.AddFiducial(-5, -35, -30)

            self.delayDisplay('Go Forward')
            modelsegmentation_module.workflow.goForward()

            self.delayDisplay('Set Thresholds')
            modelsegmentation_module.Step5._ThresholdStep__threshRange.minimumValue = 50
            modelsegmentation_module.Step5._ThresholdStep__threshRange.maximumValue = 150

            self.delayDisplay('Go Forward')
            modelsegmentation_module.workflow.goForward()

            self.delayDisplay('Restart Module')
            modelsegmentation_module.Step6.Restart()

            self.delayDisplay('Test passed!')

        except Exception, e:
            import traceback
            traceback.print_exc()
            self.delayDisplay('Test caused exception!\n' + str(e))
    def run(self):
        """
    Run the actual algorithm
    """
        print("Running test of the markups in compare viewers")

        #
        # first load the data
        #
        import SampleData

        sampleDataLogic = SampleData.SampleDataLogic()
        print("Getting MR Head Volume")
        mrHeadVolume = sampleDataLogic.downloadMRHead()

        #
        # link the viewers
        #
        sliceLogic = slicer.app.layoutManager().sliceWidget("Red").sliceLogic()
        compositeNode = sliceLogic.GetSliceCompositeNode()
        compositeNode.SetLinkedControl(1)

        #
        # MR Head in the background
        #
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetBackgroundVolumeID(mrHeadVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()

        #
        # switch to conventional layout
        #
        lm = slicer.app.layoutManager()
        lm.setLayout(2)

        # create a fiducial list
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

        # make it active
        selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
        if selectionNode != None:
            selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

        # add some known points to it
        eye1 = [33.4975, 79.4042, -10.2143]
        eye2 = [-31.283, 80.9652, -16.2143]
        nose = [4.61944, 114.526, -33.2143]
        index = fidNode.AddFiducialFromArray(eye1)
        fidNode.SetNthFiducialLabel(index, "eye-1")
        index = fidNode.AddFiducialFromArray(eye2)
        fidNode.SetNthFiducialLabel(index, "eye-2")
        index = fidNode.AddFiducialFromArray(nose)
        fidNode.SetNthFiducialLabel(index, "nose")

        self.logicDelayDisplay("Placed 3 fiducials")

        #
        # switch to 2 viewers compare layout
        #
        lm.setLayout(12)
        self.logicDelayDisplay("Switched to Compare 2 viewers")

        #
        # get compare slice composite node
        #
        compareLogic1 = slicer.app.layoutManager().sliceWidget("Compare1").sliceLogic()
        compareCompositeNode1 = compareLogic1.GetSliceCompositeNode()

        # set MRHead in the background
        compareLogic1.StartSliceCompositeNodeInteraction(1)
        compareCompositeNode1.SetBackgroundVolumeID(mrHeadVolume.GetID())
        compareLogic1.EndSliceCompositeNodeInteraction()
        compareLogic1.FitSliceToAll()
        # make it visible in 3D
        compareLogic1.GetSliceNode().SetSliceVisible(1)

        # scroll to a fiducial location
        compareLogic1.StartSliceOffsetInteraction()
        compareLogic1.SetSliceOffset(eye1[2])
        compareLogic1.EndSliceOffsetInteraction()
        self.logicDelayDisplay("MH Head in background, scrolled to a fiducial")

        # scroll around through the range of points
        offset = nose[2]
        while offset < eye1[2]:
            compareLogic1.StartSliceOffsetInteraction()
            compareLogic1.SetSliceOffset(offset)
            compareLogic1.EndSliceOffsetInteraction()
            msg = "Scrolled to " + str(offset)
            self.logicDelayDisplay(msg, 250)
            offset += 1.0

        # switch back to conventional
        lm.setLayout(2)
        self.logicDelayDisplay("Switched back to conventional layout")

        # switch to compare grid
        lm.setLayout(23)
        compareLogic1.FitSliceToAll()
        self.logicDelayDisplay("Switched to Compare grid")

        # switch back to conventional
        lm.setLayout(2)
        self.logicDelayDisplay("Switched back to conventional layout")

        return True
    def run(self):
        """
    Run the actual algorithm
    """
        print('Running test of the markups in compare viewers')

        #
        # first load the data
        #
        import SampleData
        sampleDataLogic = SampleData.SampleDataLogic()
        print("Getting MR Head Volume")
        mrHeadVolume = sampleDataLogic.downloadMRHead()

        #
        # link the viewers
        #
        sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
        compositeNode = sliceLogic.GetSliceCompositeNode()
        compositeNode.SetLinkedControl(1)

        #
        # MR Head in the background
        #
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetBackgroundVolumeID(mrHeadVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()

        #
        # switch to conventional layout
        #
        lm = slicer.app.layoutManager()
        lm.setLayout(2)

        # create a fiducial list
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

        # make it active
        selectionNode = slicer.mrmlScene.GetNodeByID(
            "vtkMRMLSelectionNodeSingleton")
        if (selectionNode != None):
            selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

        # add some known points to it
        eye1 = [33.4975, 79.4042, -10.2143]
        eye2 = [-31.283, 80.9652, -16.2143]
        nose = [4.61944, 114.526, -33.2143]
        index = fidNode.AddFiducialFromArray(eye1)
        fidNode.SetNthFiducialLabel(index, "eye-1")
        index = fidNode.AddFiducialFromArray(eye2)
        fidNode.SetNthFiducialLabel(index, "eye-2")
        index = fidNode.AddFiducialFromArray(nose)
        fidNode.SetNthFiducialLabel(index, "nose")

        self.logicDelayDisplay("Placed 3 fiducials")

        #
        # switch to 2 viewers compare layout
        #
        lm.setLayout(12)
        self.logicDelayDisplay("Switched to Compare 2 viewers")

        #
        # get compare slice composite node
        #
        compareLogic1 = slicer.app.layoutManager().sliceWidget(
            'Compare1').sliceLogic()
        compareCompositeNode1 = compareLogic1.GetSliceCompositeNode()

        # set MRHead in the background
        compareLogic1.StartSliceCompositeNodeInteraction(1)
        compareCompositeNode1.SetBackgroundVolumeID(mrHeadVolume.GetID())
        compareLogic1.EndSliceCompositeNodeInteraction()
        compareLogic1.FitSliceToAll()
        # make it visible in 3D
        compareLogic1.GetSliceNode().SetSliceVisible(1)

        # scroll to a fiducial location
        compareLogic1.StartSliceOffsetInteraction()
        compareLogic1.SetSliceOffset(eye1[2])
        compareLogic1.EndSliceOffsetInteraction()
        self.logicDelayDisplay("MH Head in background, scrolled to a fiducial")

        # scroll around through the range of points
        offset = nose[2]
        while offset < eye1[2]:
            compareLogic1.StartSliceOffsetInteraction()
            compareLogic1.SetSliceOffset(offset)
            compareLogic1.EndSliceOffsetInteraction()
            msg = "Scrolled to " + str(offset)
            self.logicDelayDisplay(msg, 250)
            offset += 1.0

        # switch back to conventional
        lm.setLayout(2)
        self.logicDelayDisplay("Switched back to conventional layout")

        # switch to compare grid
        lm.setLayout(23)
        compareLogic1.FitSliceToAll()
        self.logicDelayDisplay("Switched to Compare grid")

        # switch back to conventional
        lm.setLayout(2)
        self.logicDelayDisplay("Switched back to conventional layout")

        return True
 def createFiducialMap(self, name):
   if slicer.util.getNode(name) is None:
     fiducial = slicer.mrmlScene.AddNode(slicer.vtkMRMLMarkupsFiducialNode())
     fiducial.SetName(name)
示例#39
0
  def run(self):
    """
    Run the actual algorithm
    """
    print('Running test of the markups in different views')

    #
    # first load the data
    #
    import SampleData
    sampleDataLogic = SampleData.SampleDataLogic()
    print("Getting MR Head Volume")
    mrHeadVolume = sampleDataLogic.downloadMRHead()

    #
    # link the viewers
    #
    sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
    compositeNode = sliceLogic.GetSliceCompositeNode()
    compositeNode.SetLinkedControl(1)

    #
    # MR Head in the background
    #
    sliceLogic.StartSliceCompositeNodeInteraction(1)
    compositeNode.SetBackgroundVolumeID(mrHeadVolume.GetID())
    sliceLogic.EndSliceCompositeNodeInteraction()

    #
    # switch to conventional layout
    #
    lm = slicer.app.layoutManager()
    lm.setLayout(2)

    # create a fiducial list
    displayNode = slicer.vtkMRMLMarkupsDisplayNode()
    slicer.mrmlScene.AddNode(displayNode)
    fidNode = slicer.vtkMRMLMarkupsFiducialNode()
    slicer.mrmlScene.AddNode(fidNode)
    fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())

    # make it active
    selectionNode = slicer.mrmlScene.GetNodeByID("vtkMRMLSelectionNodeSingleton")
    if (selectionNode != None):
      selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

    # add some known points to it
    eye1 = [33.4975, 79.4042, -10.2143]
    eye2 = [-31.283, 80.9652, -16.2143]
    nose = [4.61944, 114.526, -33.2143]
    index = fidNode.AddFiducialFromArray(eye1)
    fidNode.SetNthFiducialLabel(index, "eye-1")
    index = fidNode.AddFiducialFromArray(eye2)
    fidNode.SetNthFiducialLabel(index, "eye-2")
    # hide the second eye as a test of visibility flags
    fidNode.SetNthFiducialVisibility(index, 0)
    index = fidNode.AddFiducialFromArray(nose)
    fidNode.SetNthFiducialLabel(index, "nose")

    self.logicDelayDisplay("Placed 3 fiducials")

    # self.printViewAndSliceNodes()

    if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 0:
      self.logicDelayDisplay("Test failed: widget is not visible in view 1")
      # self.printViewNodeIDs(displayNode)
      return False

    #
    # switch to 2 3D views layout
    #
    lm.setLayout(15)
    self.logicDelayDisplay("Switched to 2 3D views")
    # self.printViewAndSliceNodes()

    if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 0 or self.widgetVisible(fidNode, 'vtkMRMLViewNode2') == 0:
      self.logicDelayDisplay("Test failed: widget is not visible in view 1 and 2")
      # self.printViewNodeIDs(displayNode)
      return False

    #
    # show only in view 2
    #
    displayNode.AddViewNodeID("vtkMRMLViewNode2")
    self.logicDelayDisplay("Showing only in view 2")
    if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 1:
      self.logicDelayDisplay("Test failed: widget is not supposed to be visible in view 1")
      # self.printViewNodeIDs(displayNode)
      return False
    if self.widgetVisible(fidNode, 'vtkMRMLViewNode2') == 0:
      self.logicDelayDisplay("Test failed: widget is not visible in view 2")
      # self.printViewNodeIDs(displayNode)
      return False

    #
    # remove it so show in all
    #
    displayNode.RemoveAllViewNodeIDs()
    self.logicDelayDisplay("Showing in both views")
    if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 0 or self.widgetVisible(fidNode, 'vtkMRMLViewNode2') == 0:
      self.logicDelayDisplay("Test failed: widget is not visible in view 1 and 2")
      self.printViewNodeIDs(displayNode)
      return False

    #
    # show only in view 1
    #
    displayNode.AddViewNodeID("vtkMRMLViewNode1")
    self.logicDelayDisplay("Showing only in view 1")
    if self.widgetVisible(fidNode, 'vtkMRMLViewNode2') == 1:
      self.logicDelayDisplay("Test failed: widget is not supposed to be visible in view 2")
      # self.printViewNodeIDs(displayNode)
      return False
    if self.widgetVisible(fidNode, 'vtkMRMLViewNode1') == 0:
      self.logicDelayDisplay("Test failed: widget is not visible in view 1")
      # self.printViewNodeIDs(displayNode)
      return False

    # switch back to conventional
    lm.setLayout(2)
    self.logicDelayDisplay("Switched back to conventional layout")
    # self.printViewAndSliceNodes()

    # test of the visibility in slice views
    displayNode.RemoveAllViewNodeIDs()

    # jump to the last fiducial
    slicer.modules.markups.logic().JumpSlicesToNthPointInMarkup(fidNode.GetID(), index, 1)

    # show only in red
    displayNode.AddViewNodeID('vtkMRMLSliceNodeRed')
    self.logicDelayDisplay("Show only in red slice")
    if self.widgetVisibleOnSlice(fidNode,'vtkMRMLSliceNodeRed') != 1:
      self.logicDelayDisplay("Test failed: widget not displayed on red slice")
      # self.printViewNodeIDs(displayNode)
      return False

    # remove all, add green
    # print 'before remove all, after added red'
    # self.printViewNodeIDs(displayNode)
    displayNode.RemoveAllViewNodeIDs()
    # print 'after removed all'
    # self.printViewNodeIDs(displayNode)
    displayNode.AddViewNodeID('vtkMRMLSliceNodeGreen')
    self.logicDelayDisplay('Show only in green slice')
    if self.widgetVisibleOnSlice(fidNode,'vtkMRMLSliceNodeRed') != 0 or self.widgetVisibleOnSlice(fidNode,'vtkMRMLSliceNodeGreen') != 1:
      self.logicDelayDisplay("Test failed: widget not displayed only on green slice")
      print '\tred = ',self.widgetVisibleOnSlice(fidNode,'vtkMRMLSliceNodeRed')
      print '\tgreen =',self.widgetVisibleOnSlice(fidNode,'vtkMRMLSliceNodeGreen')
      self.printViewNodeIDs(displayNode)
      return False

    return True
 def readPlane(self):
     filename = qt.QFileDialog.getOpenFileName(parent=self,caption='Open file')
     print 'filename:', filename
     fichier2 = open(filename, 'r')
     fichier2.readline()
     NodeRed = slicer.mrmlScene.GetNodeByID('vtkMRMLSliceNodeRed')
     matRed = NodeRed.GetSliceToRAS()
     
     for i in range(0, 4):
         ligne = fichier2.readline()
         ligne = ligne.replace('[', '')
         ligne = ligne.replace('   ', ' ')
         ligne = ligne.replace(']', '')
         ligne = ligne.replace('\n', '')
         print ligne
         items = ligne.split()
         print items
         for j in range(0, 4):
             matRed.SetElement(i, j, float(items[j]))
     
     
     print matRed
     compare_red = 0
     for i in range(0,4):
         for j in range(0,4):
             if matRed.GetElement(i,j) == self.matRed_init[i,j]:
                 compare_red = compare_red + 1
     
     print compare_red
     
     if compare_red != 16:
         self.redslice = slicer.util.getNode('vtkMRMLSliceNodeRed')
         if self.red_plane_box.isChecked():
             self.red_plane_box.setChecked(False)
             self.redslice.SetWidgetVisible(False)
         self.red_plane_box.setChecked(True)
         self.redPlaneCheckBoxClicked()
     
     fichier2.readline()
     fichier2.readline()
     
     
     NodeGreen = slicer.mrmlScene.GetNodeByID('vtkMRMLSliceNodeGreen')
     matGreen = NodeGreen.GetSliceToRAS()
     for i in range (0,4):
         ligne = fichier2.readline()
         ligne = ligne.replace('[', '')
         ligne = ligne.replace('   ', ' ')
         ligne = ligne.replace(']', '')
         ligne = ligne.replace('\n', '')
         print ligne
         items = ligne.split()
         print items
         for j in range(0, 4):
             matGreen.SetElement(i, j, float(items[j]))
     
     
     print matGreen
     
     
     compare_green = 0
     for i in range(0,4):
         for j in range(0,4):
             if matGreen.GetElement(i,j) == self.matGreen_init[i,j]:
                 compare_green = compare_green + 1
     
     print compare_green
     
     if compare_green != 16:
         self.greenslice = slicer.util.getNode('vtkMRMLSliceNodeGreen')
         if self.green_plane_box.isChecked():
             self.green_plane_box.setChecked(False)
             self.greenslice.SetWidgetVisible(False)
         
         self.green_plane_box.setChecked(True)
         self.greenPlaneCheckBoxClicked()
     
     
     fichier2.readline()
     fichier2.readline()
     
     displayNode = slicer.vtkMRMLMarkupsDisplayNode()
     slicer.mrmlScene.AddNode(displayNode)
     fidNode = slicer.vtkMRMLMarkupsFiducialNode()
     slicer.mrmlScene.AddNode(fidNode)
     fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
     
     ligne = fichier2.readline()
     ligne = ligne.replace('[', '')
     ligne = ligne.replace('   ', ' ')
     ligne = ligne.replace(']', '')
     ligne = ligne.replace('\n', '')
     print ligne
     items = ligne.split()
     print items
     
     r = float(items[0])
     a = float(items[1])
     s = float(items[2])
     fidNode.AddFiducial(r,a,s)
     
     fichier2.readline()
     
     displayNode = slicer.vtkMRMLMarkupsDisplayNode()
     slicer.mrmlScene.AddNode(displayNode)
     fidNode = slicer.vtkMRMLMarkupsFiducialNode()
     slicer.mrmlScene.AddNode(fidNode)
     fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
     
     ligne = fichier2.readline()
     ligne = ligne.replace('[', '')
     ligne = ligne.replace('   ', ' ')
     ligne = ligne.replace(']', '')
     ligne = ligne.replace('\n', '')
     print ligne
     items = ligne.split()
     print items
     
     r = float(items[0])
     a = float(items[1])
     s = float(items[2])
     fidNode.AddFiducial(r,a,s)
     
     fichier2.readline()
     
     displayNode = slicer.vtkMRMLMarkupsDisplayNode()
     slicer.mrmlScene.AddNode(displayNode)
     fidNode = slicer.vtkMRMLMarkupsFiducialNode()
     slicer.mrmlScene.AddNode(fidNode)
     fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
     
     ligne = fichier2.readline()
     ligne = ligne.replace('[', '')
     ligne = ligne.replace('   ', ' ')
     ligne = ligne.replace(']', '')
     ligne = ligne.replace('\n', '')
     print ligne
     items = ligne.split()
     print items
     
     r = float(items[0])
     a = float(items[1])
     s = float(items[2])
     fidNode.AddFiducial(r,a,s)
     
     fichier2.close()
    def run(self, enableScreenshots=0, screenshotScaleFactor=1):
        """
    Run the actual algorithm
    """
        self.delayDisplay(
            'Running test of the Neurosurgical Planning tutorial')

        self.enableScreenshots = enableScreenshots
        self.screenshotScaleFactor = screenshotScaleFactor

        # conventional layout
        lm = slicer.app.layoutManager()
        lm.setLayout(2)

        moduleSelector = slicer.util.mainWindow().moduleSelector()
        #
        # first load the data
        #
        if self.enableScreenshots == 1:
            # for the tutorial, do it through the welcome module
            moduleSelector.selectModule('Welcome')
            self.delayDisplay("Screenshot")
            self.takeScreenshot('NeurosurgicalPlanning-Welcome',
                                'Welcome module', -1)
        else:
            # otherwise show the sample data module
            moduleSelector.selectModule('SampleData')

        # use the sample data module logic to load data for the self test
        import SampleData
        sampleDataLogic = SampleData.SampleDataLogic()

        self.delayDisplay("Getting Baseline volume")
        baselineVolume = sampleDataLogic.downloadWhiteMatterExplorationBaselineVolume(
        )

        self.delayDisplay("Getting DTI volume")
        dtiVolume = sampleDataLogic.downloadWhiteMatterExplorationDTIVolume()

        self.takeScreenshot('NeurosurgicalPlanning-Loaded', 'Data loaded', -1)

        #
        # link the viewers
        #

        if self.enableScreenshots == 1:
            # for the tutorial, pop up the linking control
            sliceController = slicer.app.layoutManager().sliceWidget(
                "Red").sliceController()
            popupWidget = sliceController.findChild("ctkPopupWidget")
            if popupWidget != None:
                popupWidget.pinPopup(1)
                self.takeScreenshot('NeurosurgicalPlanning-Link',
                                    'Link slice viewers', -1)
                popupWidget.pinPopup(0)

        sliceLogic = slicer.app.layoutManager().sliceWidget('Red').sliceLogic()
        compositeNode = sliceLogic.GetSliceCompositeNode()
        compositeNode.SetLinkedControl(1)

        #
        # baseline in the background
        #
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetBackgroundVolumeID(baselineVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()

        self.takeScreenshot('NeurosurgicalPlanning-Baseline',
                            'Baseline in background', -1)

        #
        # adjust window level on baseline
        #
        moduleSelector.selectModule('Volumes')
        baselineDisplay = baselineVolume.GetDisplayNode()
        baselineDisplay.SetAutoWindowLevel(0)
        baselineDisplay.SetWindow(2600)
        baselineDisplay.SetLevel(1206)
        self.takeScreenshot('NeurosurgicalPlanning-WindowLevel',
                            'Set W/L on baseline', -1)

        #
        # switch to red slice only
        #
        lm.setLayout(6)
        self.takeScreenshot('NeurosurgicalPlanning-RedSliceOnly',
                            'Set layout to Red Slice only', -1)

        #
        # segmentation of tumour
        #

        #
        # create a label map and set it for editing
        #
        volumesLogic = slicer.modules.volumes.logic()
        baselineVolumeLabel = volumesLogic.CreateAndAddLabelVolume(
            slicer.mrmlScene, baselineVolume,
            baselineVolume.GetName() + '-label')
        baselineDisplayNode = baselineVolumeLabel.GetDisplayNode()
        baselineDisplayNode.SetAndObserveColorNodeID(
            'vtkMRMLColorTableNodeFileGenericAnatomyColors.txt')
        selectionNode = slicer.app.applicationLogic().GetSelectionNode()
        selectionNode.SetReferenceActiveVolumeID(baselineVolume.GetID())
        selectionNode.SetReferenceActiveLabelVolumeID(
            baselineVolumeLabel.GetID())
        slicer.app.applicationLogic().PropagateVolumeSelection(0)

        #
        # editor module
        #
        moduleSelector.selectModule('Editor')
        self.takeScreenshot('NeurosurgicalPlanning-Editor',
                            'Showing Editor Module', -1)

        # set the slice offset so drawing is right
        sliceNode = sliceLogic.GetSliceNode()
        sliceOffset = 58.7
        sliceNode.SetSliceOffset(sliceOffset)

        #
        # paint
        #
        editUtil = EditorLib.EditUtil.EditUtil()
        parameterNode = editUtil.getParameterNode()
        paintEffect = EditorLib.PaintEffectOptions()
        paintEffect.setMRMLDefaults()
        paintEffect.__del__()
        sliceWidget = lm.sliceWidget('Red')
        paintTool = EditorLib.PaintEffectTool(sliceWidget)
        self.takeScreenshot('NeurosurgicalPlanning-Paint',
                            'Paint tool in Editor Module', -1)

        #
        # paint in cystic part of tumor, using converstion from RAS coords to
        # avoid slice widget size differences
        #
        editUtil.setLabel(293)
        displayCoords = self.rasToDisplay(-7.4, 71, sliceOffset)
        paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
        displayCoords = self.rasToDisplay(-11, 73, sliceOffset)
        paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
        displayCoords = self.rasToDisplay(-12, 85, sliceOffset)
        paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
        displayCoords = self.rasToDisplay(-13, 91, sliceOffset)
        paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
        displayCoords = self.rasToDisplay(-15, 78, sliceOffset)
        paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
        paintTool.paintApply()
        self.takeScreenshot('NeurosurgicalPlanning-PaintCystic',
                            'Paint cystic part of tumor', -1)

        #
        # paint in solid part of tumor
        #
        editUtil.setLabel(7)
        displayCoords = self.rasToDisplay(-0.5, 118.5, sliceOffset)
        paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
        displayCoords = self.rasToDisplay(-7.4, 116, sliceOffset)
        paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
        paintTool.paintApply()
        self.takeScreenshot('NeurosurgicalPlanning-PaintSolid',
                            'Paint solid part of tumor', -1)

        #
        # paint around the tumor
        #
        editUtil.setLabel(295)
        rMax = 25
        rMin = -50
        aMax = 145
        aMin = 50
        rasStep = 5

        # draw the top and bottom
        for r in range(rMin, rMax, rasStep):
            displayCoords = self.rasToDisplay(r, aMin, sliceOffset)
            paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
            displayCoords = self.rasToDisplay(r, aMax, sliceOffset)
            paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
        # draw the left and right
        for a in range(aMin, aMax, rasStep):
            displayCoords = self.rasToDisplay(rMin, a, sliceOffset)
            paintTool.paintAddPoint(displayCoords[0], displayCoords[1])
            displayCoords = self.rasToDisplay(rMax, a, sliceOffset)
            paintTool.paintAddPoint(displayCoords[0], displayCoords[1])

        paintTool.paintApply()

        self.takeScreenshot('NeurosurgicalPlanning-PaintAround',
                            'Paint around tumor', -1)
        #
        # clean up after painting
        #
        paintTool.cleanup()
        paintTool = None

        #
        # Grow cut
        #
        growCutLogic = EditorLib.GrowCutEffectLogic(sliceWidget.sliceLogic())
        growCutLogic.growCut()
        self.takeScreenshot('NeurosurgicalPlanning-Growcut', 'Growcut', -1)

        #
        # Merge split volume
        #
        slicer.util.selectModule('Editor')
        slicer.util.findChildren(text='Split Merge Volume')[0].clicked()
        self.takeScreenshot('NeurosurgicalPlanning-SplitMerge', 'SplitMerge',
                            -1)

        #
        # go to the data module
        #
        moduleSelector.selectModule('Data')
        self.takeScreenshot('NeurosurgicalPlanning-SplitMergeData',
                            'SplitMerge results in Data', -1)

        #
        # Ventricles Segmentation
        #

        moduleSelector.selectModule('Editor')
        #
        # select the label volume with the area around the tumor
        slicer.util.findChildren(
            name='PerStructureVolumesFrame')[0].collapsed = False
        treeView = slicer.util.findChildren(name='StructuresView')[0]
        selection = qt.QItemSelection()
        # selecting the last split volume in the third row
        row = 2
        rowStart = treeView.model().index(row, 0)
        rowEnd = treeView.model().index(row,
                                        treeView.model().columnCount() - 1)
        # rowSel = qt.QItemSelection(rowStart, rowEnd)
        selection.select(rowStart, rowEnd)
        # backup: select the label map in the slice logic too
        baselinelabel295 = slicer.mrmlScene.GetFirstNodeByName(
            "BaselineVolume-region 3-label")
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetLabelVolumeID(baselinelabel295.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()
        self.takeScreenshot('NeurosurgicalPlanning-SelOutside',
                            'Select outside region', -1)

        #
        # Threshold tool
        #
        slicer.modules.EditorWidget.toolsBox.selectEffect('ThresholdEffect')
        parameterNode = slicer.modules.EditorWidget.toolsBox.currentOption.editUtil.getParameterNode(
        )
        parameterNode.SetParameter('ThresholdEffect,min', str(1700))
        slicer.modules.EditorWidget.toolsBox.currentTools[0].apply()
        self.takeScreenshot('NeurosurgicalPlanning-Ventricles',
                            'Ventricles segmentation', -1)

        #
        # Save Islands
        #
        slicer.modules.EditorWidget.toolsBox.selectEffect('SaveIslandEffect')
        saveIslandLogic = EditorLib.SaveIslandEffectLogic(
            sliceWidget.sliceLogic())
        displayCoords = self.rasToDisplay(25.3, 5.8, sliceOffset)
        xy = (displayCoords[0], displayCoords[1])
        saveIslandLogic.saveIsland(xy)
        self.takeScreenshot('NeurosurgicalPlanning-SaveIsland',
                            'Ventricles save island', -1)

        #
        # Merge and build
        #
        slicer.util.findChildren(text='Merge And Build')[0].clicked()

        #
        # switch to conventional layout
        #
        lm.setLayout(2)
        self.takeScreenshot('NeurosurgicalPlanning-MergeAndBuild',
                            'Merged and built models', -1)

        #
        # Tractography label map seeding
        #

        #
        # select label volume with label 293, in the second row
        #
        row = 1
        rowStart = treeView.model().index(row, 0)
        rowEnd = treeView.model().index(row,
                                        treeView.model().columnCount() - 1)
        # rowSel = qt.QItemSelection(rowStart, rowEnd)
        selection.select(rowStart, rowEnd)
        # backup: select the label map in the slice logic too
        baselinelabel293 = slicer.mrmlScene.GetFirstNodeByName(
            "BaselineVolume-region 1-label")
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetLabelVolumeID(baselinelabel293.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()
        self.takeScreenshot('NeurosurgicalPlanning-SelCystic',
                            'Select cystic region', -1)

        #
        # Dilate
        #
        slicer.modules.EditorWidget.toolsBox.selectEffect('DilateEffect')
        editUtil.setLabel(293)
        self.takeScreenshot('NeurosurgicalPlanning-Dilate', 'Dilate tool', -1)
        # tutorial says to click apply three times
        for d in range(1, 3):
            print d
            # slicer.util.findChildren(name='DilateEffectOptionsApply')[0].clicked()
            # slicer.modules.EditorWidget.toolsBox.currentTools[0].apply()
            slicer.modules.EditorWidget.toolsBox.currentOption.onApply()
        self.takeScreenshot('NeurosurgicalPlanning-Dilated', 'Dilated tumor',
                            -1)

        #
        # Tractography Label Map Seeding module
        #
        moduleSelector.selectModule('TractographyLabelMapSeeding')
        self.takeScreenshot('NeurosurgicalPlanning-LabelMapSeedingModule',
                            'Showing Tractography Label Seeding Module', -1)
        tractographyLabelSeeding = slicer.modules.tractographylabelmapseeding
        parameters = {}
        parameters['InputVolume'] = dtiVolume.GetID()
        baselinelabel293 = slicer.mrmlScene.GetFirstNodeByName(
            "BaselineVolume-region 1-label")
        # VTK6 TODO - set 'InputROIPipelineInfo'
        parameters['InputROI'] = baselinelabel293.GetID()
        fibers = slicer.vtkMRMLFiberBundleNode()
        slicer.mrmlScene.AddNode(fibers)
        parameters['OutputFibers'] = fibers.GetID()
        parameters['UseIndexSpace'] = 1
        parameters['StoppingValue'] = 0.15
        parameters['ROIlabel'] = 293
        parameters['StoppingMode'] = 'FractionalAnisotropy'
        # defaults
        # parameters['ClTh'] = 0.3
        # parameters['MinimumLength'] = 20
        # parameters['MaximumLength'] = 800
        # parameters['StoppingCurvature'] = 0.7
        # parameters['IntegrationStepLength'] = 0.5
        # parameters['SeedSpacing'] = 2
        # and run it
        slicer.cli.run(tractographyLabelSeeding, None, parameters)
        self.takeScreenshot('NeurosurgicalPlanning-LabelMapSeeding',
                            'Showing Tractography Label Seeding Results', -1)

        #
        # tractography fiducial seeding
        #
        moduleSelector.selectModule('TractographyInteractiveSeeding')
        self.takeScreenshot('NeurosurgicalPlanning-TIS',
                            'Showing Tractography Interactive Seeding Module',
                            -1)

        # DTI in background
        sliceLogic.StartSliceCompositeNodeInteraction(1)
        compositeNode.SetBackgroundVolumeID(dtiVolume.GetID())
        sliceLogic.EndSliceCompositeNodeInteraction()

        # DTI visible in 3D
        sliceNode = sliceLogic.GetSliceNode()
        sliceLogic.StartSliceNodeInteraction(128)
        sliceNode.SetSliceVisible(1)
        sliceLogic.EndSliceNodeInteraction()

        self.takeScreenshot(
            'NeurosurgicalPlanning-TIS-DTI',
            'DTI volume with Tractography Interactive Seeding Module', -1)

        # place a fiducial
        displayNode = slicer.vtkMRMLMarkupsDisplayNode()
        slicer.mrmlScene.AddNode(displayNode)
        fidNode = slicer.vtkMRMLMarkupsFiducialNode()
        fidNode.SetName('F')
        slicer.mrmlScene.AddNode(fidNode)
        fidNode.SetAndObserveDisplayNodeID(displayNode.GetID())
        r = 28.338526
        a = 34.064367
        s = sliceOffset
        fidNode.AddFiducial(r, a, s)

        # make it active
        selectionNode = slicer.mrmlScene.GetNodeByID(
            "vtkMRMLSelectionNodeSingleton")
        if (selectionNode != None):
            selectionNode.SetReferenceActivePlaceNodeID(fidNode.GetID())

        self.takeScreenshot(
            'NeurosurgicalPlanning-TIS-Fid1',
            'Fiducial in Tractography Interactive Seeding Module', -1)

        # set up the arguments
        wr = slicer.modules.tractographyinteractiveseeding.widgetRepresentation(
        )
        wr.setDiffusionTensorVolumeNode(dtiVolume)
        # create a fiber bundle
        fiducialFibers = slicer.vtkMRMLFiberBundleNode()
        slicer.mrmlScene.AddNode(fiducialFibers)
        wr.setFiberBundleNode(fiducialFibers)
        wr.setSeedingNode(fidNode)
        wr.setMinimumPath(10)
        wr.setStoppingValue(0.15)

        self.takeScreenshot('NeurosurgicalPlanning-TIS-Args',
                            'Tractography Interactive Seeding arguments', -1)

        self.delayDisplay("Moving the fiducial")
        for y in range(-20, 100, 5):
            msg = "Moving the fiducial to y = " + str(y)
            self.delayDisplay(msg, 250)
            fidNode.SetNthFiducialPosition(0, r, y, s)

        self.takeScreenshot(
            'NeurosurgicalPlanning-TIS-Moved',
            'Moved fiducial and did Tractography Interactive Seeding', -1)

        return True
示例#42
0
 def createFiducialMap(self, name):
     if slicer.util.getNode(name) is None:
         fiducial = slicer.mrmlScene.AddNode(
             slicer.vtkMRMLMarkupsFiducialNode())
         fiducial.SetName(name)