Exemplo n.º 1
0
  def run(self, segmentationVolume, falseNegativeLine, truePositiveRegion, dilationFactor):
    """
    Run the actual algorithm
    """
    logging.info('Processing started')

    if (not self.isValidDilateValue(dilationFactor)):
      slicer.util.errorDisplay("The dilation value must be an integer.")
      return False

    if (not self.hasImageData(segmentationVolume)):
      slicer.util.errorDisplay("The segmentation is not valid.")
      return False

    # Iteratively compute the false negative true positive metrics
    falseNegativeResults = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    truePositiveResults = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    falseNegativeArray = falseNegativeResults.GetArray()
    truePositiveArray = truePositiveResults.GetArray()
    falseNegativeArray.SetNumberOfTuples(int(dilationFactor))
    truePositiveArray.SetNumberOfTuples(int(dilationFactor))
    for dilateValue in range(int(dilationFactor)):
      cliParams = {'truePositiveGroundTruthVolume': truePositiveRegion.GetID(),
                   'falseNegativeGroundTruthVolume': falseNegativeLine.GetID(),
                   'dilateValue' : dilateValue,
                   'segmentedVolume': segmentationVolume.GetID()}
      cliNode = slicer.cli.run(slicer.modules.usbonesegmentationevaluator, None, cliParams, wait_for_completion=True)
      falseNegativeResult = cliNode.GetParameterAsString("falseNegativePercentage")
      falseNegativeArray.SetComponent(dilateValue, 0, dilateValue)
      falseNegativeArray.SetComponent(dilateValue, 1, float(falseNegativeResult))
      falseNegativeArray.SetComponent(dilateValue, 2, 0)
      truePositiveResult = cliNode.GetParameterAsString("truePositivePercentage")
      truePositiveArray.SetComponent(dilateValue, 0, dilateValue)
      truePositiveArray.SetComponent(dilateValue, 1, float(truePositiveResult))
      truePositiveArray.SetComponent(dilateValue, 2, 0)


    # Change to layout which has a chart view
    layoutNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
    layoutNodes.InitTraversal()
    layoutNode = layoutNodes.GetNextItemAsObject()
    layoutNode.SetViewArrangement(24)

    # Create chart node and chart view node
    chartViewNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartViewNode())
    chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
    chartNode.AddArray('False Negative Percentage', falseNegativeResults.GetID())
    chartNode.AddArray('True Positive Percentage', truePositiveResults.GetID())
    chartNode.SetProperty('default', 'xAxisLabel', 'Dilation Value')
    chartNode.SetProperty('default', 'yAxisLabel', 'Percentage')
    chartNode.SetProperty('default', 'type', 'Scatter')
    chartViewNode.SetChartNodeID(chartNode.GetID())
    chartNode.Modified()
    chartViewNode.Modified()
    slicer.mrmlScene.Modified()
    layoutNode.Modified()

    logging.info('Processing completed')

    return True
  def __init__(self, ar1, ar2):
    array1=numpy.asarray(ar1.GetArray())[:,1]
    array2=numpy.asarray(ar2.GetArray())[:,1]
    x1=numpy.asarray(ar1.GetArray())[:,0]
    x2=numpy.asarray(ar2.GetArray())[:,0]

    Xnt=numpy.concatenate((x1,x2))
    Xnt.sort()
    Xn=numpy.unique(Xnt)
    self.array1=numpy.interp(Xn,x1,array1,left=0,right=0)
    self.array2=numpy.interp(Xn,x2,array2,left=0,right=0)
    
    #test da cancellare
    lnmx=Xn.size
    arrayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    arrayNode.SetName(ar1.GetName() + "-nr")
    arrayD = arrayNode.GetArray()
    arrayD.SetNumberOfComponents(2)
    arrayD.SetNumberOfTuples(lnmx)
    for n in range(lnmx):
      arrayD.SetComponent(n, 0, Xn[0]+n)
      arrayD.SetComponent(n, 1, self.array1[n])

    arrayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    arrayNode.SetName(ar2.GetName() + "-nr")
    arrayD = arrayNode.GetArray()
    arrayD.SetNumberOfComponents(2)
    arrayD.SetNumberOfTuples(lnmx)
    for n in range(lnmx):
      arrayD.SetComponent(n, 0, Xn[0]+n)
      arrayD.SetComponent(n, 1, self.array2[n])
Exemplo n.º 3
0
  def ChartRepresentationRotation(self, rotationX,rotationY,rotationZ, timeStamp):
    # Switch to a layout (24) that contains a Chart View to initiate the construction of the widget and Chart View Node
    lns = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
    lns.InitTraversal()
    ln = lns.GetNextItemAsObject()
    ln.SetViewArrangement(506)

    # Get the Chart View Node
    cvns = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
    cvns.InitTraversal()
    cvn = cvns.GetNextItemAsObject()

    # Create an Array Node and add some data
    dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn.GetArray()
    a.SetNumberOfTuples(len(rotationX))
    t=range(0,len(rotationX))
    for i in t:
        a.SetComponent(i, 0, i)
        a.SetComponent(i, 1, rotationX[i])
        a.SetComponent(i, 2, 0)

    # Create a second Array node
    dn2 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    b = dn2.GetArray()
    b.SetNumberOfTuples(len(rotationY))
    for i in t:
        b.SetComponent(i, 0, i)
        b.SetComponent(i, 1, rotationY[i])
        b.SetComponent(i, 2, 0)

    # Create a second Array node
    dn3 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    c = dn3.GetArray()
    c.SetNumberOfTuples(len(rotationZ))
    for i in t:
        c.SetComponent(i, 0, i)
        c.SetComponent(i, 1, rotationZ[i])
        c.SetComponent(i, 2, 0)

    # Create a Chart Node.
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add the Array Nodes to the Chart. The first argument is a string used for the legend and to refer to the Array when setting properties.
    cn.AddArray('Rotation in X', dn.GetID())
    cn.AddArray('Rotation in Y', dn2.GetID())
    cn.AddArray('Rotation in Z', dn3.GetID())

    # Set a few properties on the Chart. The first argument is a string identifying which Array to assign the property. 
    # 'default' is used to assign a property to the Chart itself (as opposed to an Array Node).
    cn.SetProperty('default', 'title', 'ROTATION PLOT')
    cn.SetProperty('default', 'xAxisLabel', 'Time')
    cn.SetProperty('default', 'yAxisLabel', 'Angle (degrees)')

    # Tell the Chart View which Chart to display
    cvn.SetChartNodeID(cn.GetID())
Exemplo n.º 4
0
  def showChart(self):

    #switch to layout containing a chart viewer

    #lm = slicer.app.layoutManager()
    #lm.setLayout(slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpQuantitativeView)

    # Switch to a layout (24) that contains a Chart View to initiate the construction of the widget and Chart View Node
    lns = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
    lns.InitTraversal()
    ln = lns.GetNextItemAsObject()
    ln.SetViewArrangement(506)

    # Get the Chart View Node
    cvns = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
    cvns.InitTraversal()
    cvn = cvns.GetNextItemAsObject()
  
    # Create an Array Node and add some data
    dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn.GetArray()
    a.SetNumberOfTuples(600)
    x = range(0, 600)
    for i in range(len(x)):
        a.SetComponent(i, 0, x[i]/50.0)
        a.SetComponent(i, 1, math.sin(x[i]/50.0))
        a.SetComponent(i, 2, 0)

    # Create a second Array node
    dn2 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn2.GetArray()
    a.SetNumberOfTuples(600)
    x = range(0, 600)
    for i in range(len(x)):
        a.SetComponent(i, 0, x[i]/50.0)
        a.SetComponent(i, 1, math.cos(x[i]/50.0))
        a.SetComponent(i, 2, 0)

    # Create a Chart Node.
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    #   Add the Array Nodes to the Chart. The first argument is a string used for the legend and to refer to the Array when setting properties.
    cn.AddArray('A double array', dn.GetID())
    cn.AddArray('Another double array', dn2.GetID())

    # Set a few properties on the Chart. The first argument is a string identifying which Array to assign the property. 
    # 'default' is used to assign a property to the Chart itself (as opposed to an Array Node).
    cn.SetProperty('default', 'title', 'A simple chart with 2 curves')
    cn.SetProperty('default', 'xAxisLabel', 'Something in x')
    cn.SetProperty('default', 'yAxisLabel', 'Something in y')

    # Tell the Chart View which Chart to display
    cvn.SetChartNodeID(cn.GetID())
    def showChart(self, samples, names):
        print("Logic showing chart")

        lm = slicer.app.layoutManager()
        lm.setLayout(
            slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpQuantitativeView)

        doubleArrays = []
        for sample in samples:
            arrayNode = slicer.mrmlScene.AddNode(
                slicer.vtkMRMLDoubleArrayNode())
            array = arrayNode.GetArray()
            nDataPoints = sample.GetNumberOfTuples()
            array.SetNumberOfTuples(nDataPoints)
            array.SetNumberOfComponents(3)
            for i in range(nDataPoints):
                array.SetComponent(i, 0, i)
                array.SetComponent(i, 1, sample.GetTuple1(i))
                array.SetComponent(i, 2, 0)
            doubleArrays.append(arrayNode)

        cvNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
        cvNodes.SetReferenceCount(cvNodes.GetReferenceCount() - 1)
        cvNodes.InitTraversal()
        cvNode = cvNodes.GetNextItemAsObject()

        chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
        for pairs in zip(names, doubleArrays):
            chartNode.AddArray(pairs[0], pairs[1].GetID())
        cvNode.SetChartNodeID(chartNode.GetID())
        return
  def onApplyButton(self):
    ar1=self.ArraySelector1.currentNode()
    ar2=self.ArraySelector2.currentNode()
    logic = CrossCorrCalculatorLogic(ar1,ar2)
    cc=logic.run()

    name="cc-"+ar1.GetName()+"-"+ar2.GetName()
    ntuple=len(cc)
    arrayNode = slicer.mrmlScene.GetNodesByClassByName("vtkMRMLDoubleArrayNode",name).GetItemAsObject(0)

    if not arrayNode:
      arrayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
      arrayNode.SetName(name)

    arrayD = arrayNode.GetArray()

    arrayD.SetNumberOfComponents(2)
    arrayD.SetNumberOfTuples(ntuple)
    
    for n in range(ntuple):
      #arrayD.SetComponent(n, 0, n+1-ar2.GetSize())
      arrayD.SetComponent(n, 0, n+int((1-ntuple)/2))
      arrayD.SetComponent(n, 1, cc[n])


    self.delaySW.enabled = True
    self.delaySW.minimum = -ntuple+1
    self.delaySW.maximum = ntuple-1
    self.delaySW.value=0

    self.getCC(self.delaySW.value)
Exemplo n.º 7
0
  def PlotMembershipFunctions( membershipFunctions, min, max, steps ):

    step = float( max - min ) / steps
    # Setting up the array of values
    chartNode = slicer.vtkMRMLChartNode()
    chartNode.SetScene( slicer.mrmlScene )
    slicer.mrmlScene.AddNode( chartNode )

    for i in range( len( membershipFunctions ) ):
      arrayNode = slicer.vtkMRMLDoubleArrayNode()
      arrayNode.SetScene( slicer.mrmlScene )
      slicer.mrmlScene.AddNode( arrayNode )
      array = arrayNode.GetArray()
      array.SetNumberOfTuples( int( ( max - min ) / step ) )

      for j in range( array.GetNumberOfTuples() ):
        array.SetComponent( j, 0, min + j * step )
        array.SetComponent( j, 1, membershipFunctions[ i ].Evaluate( min + j * step ) )
        array.SetComponent( j, 2, 0 )

      # Add array into a chart node
      chartNode.AddArray( "Membership Function " + str( i ), arrayNode.GetID() )

    chartNode.SetProperty( 'default', 'title', 'Membership Functions' )
    chartNode.SetProperty( 'default', 'xAxisLabel', 'Membership Value' )
    chartNode.SetProperty( 'default', 'yAxisLabel', 'Element' )

    # Set the chart in the chart view node
    chartViewNode = slicer.mrmlScene.GetNthNodeByClass( 0, "vtkMRMLChartViewNode" )
    if ( chartViewNode is None ):
      chartViewNode = slicer.vtkMRMLChartViewNode()
      chartViewNode.SetScene( slicer.mrmlScene )
      slicer.mrmlScene.AddNode( chartViewNode )
    chartViewNode.SetChartNodeID( chartNode.GetID() )
Exemplo n.º 8
0
 def compareTRE_FRE():
   averages = []
   TREs = []
   numPoints = range(10, 45, 5)
   for i in range(10, 45, 5):
     # This is 7 iterations
     print "Number of points used: " + str(i)
     [alphaPoints, betaPoints, referenceToRas] = createTransformPoints(2.0, i)
     alphaToBetaMatrix = computeRegistration(referenceToRas, alphaPoints, betaPoints)
     average = avgDistAfterReg(i, alphaPoints, betaPoints, alphaToBetaMatrix)
     averages.append(average)
     TRE = computeTRE(alphaToBetaMatrix)
     TREs.append(TRE)
   lns = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
   lns.InitTraversal()
   ln = lns.GetNextItemAsObject()
   ln.SetViewArrangement(24)
   # Get the Chart View Node
   cvns = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
   cvns.InitTraversal()
   cvn = cvns.GetNextItemAsObject()
   # Create an Array Node and add some data
   TRE_dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
   arrayNode = TRE_dn.GetArray()
   arrayNode.SetNumberOfTuples(7)
   FRE_dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
   arrayNode2 = FRE_dn.GetArray()
   arrayNode2.SetNumberOfTuples(7)
   for i in range(len(numPoints)):
     arrayNode.SetComponent(i, 0, numPoints[i])
     arrayNode.SetComponent(i, 1, TREs[i])
     arrayNode.SetComponent(i, 2, 0)
     arrayNode2.SetComponent(i, 0, numPoints[i])
     arrayNode2.SetComponent(i, 1, averages[i])
     arrayNode2.SetComponent(i, 2, 0)
   # Create a Chart Node.
   cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
   # Add the Array Nodes to the Chart. The first argument is a string used for the legend and to refer to the Array when setting properties.
   cn.AddArray('TRE', TRE_dn.GetID())
   cn.AddArray('FRE', FRE_dn.GetID())
   # Set a few properties on the Chart. The first argument is a string identifying which Array to assign the property.
   # 'default' is used to assign a property to the Chart itself (as opposed to an Array Node).
   cn.SetProperty('default', 'title', 'TRE and FRE as a function of the number of points')
   cn.SetProperty('default', 'xAxisLabel', 'Number of points')
   cn.SetProperty('default', 'yAxisLabel', 'Unit Value')
   # Tell the Chart View which Chart to display
   cvn.SetChartNodeID(cn.GetID())
Exemplo n.º 9
0
    def createStatsChart(self, labelNode, valueToPlot):
        """Make a MRML chart of the current stats
        """
        self.setChartLayout()
        chartViewNode = slicer.util.getNode('ChartView')

        arrayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        array = arrayNode.GetArray()
        samples = len(self.regionTags)
        tuples = samples
        array.SetNumberOfTuples(tuples)
        tuple = 0

        for i in xrange(samples):
            index = self.regionTags[i]
            array.SetComponent(tuple, 0, i)
            array.SetComponent(tuple, 1, self.labelStats[valueToPlot, index])
            array.SetComponent(tuple, 2, 0)
            tuple += 1

        chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
        chartNode.AddArray(valueToPlot, arrayNode.GetID())

        chartViewNode.SetChartNodeID(chartNode.GetID())

        chartNode.SetProperty('default', 'title', 'Parenchyma Statistics')
        chartNode.SetProperty('default', 'xAxisLabel', 'Label')
        chartNode.SetProperty('default', 'yAxisLabel', valueToPlot)
        chartNode.SetProperty('default', 'type', 'Bar')
        chartNode.SetProperty('default', 'xAxisType', 'categorical')
        chartNode.SetProperty('default', 'showLegend', 'off')

        # series level properties
        if labelNode.GetDisplayNode() != None and labelNode.GetDisplayNode(
        ).GetColorNode() != None:
            colorNode = labelNode.GetDisplayNode().GetColorNode()

            newDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
            newDisplayNode.SetAndObserveColorNodeID(
                'vtkMRMLColorTableNodeFileGenericAnatomyColors.txt')
            slicer.mrmlScene.AddNode(newDisplayNode)
            newColorNode = newDisplayNode.GetColorNode()

            colorNumber = 0
            for tag in self.regionTags:
                c = [0, 0, 0, 0]
                value = self.valuesDictionary[tag]
                if value[0] == value[1]:
                    colorNode.SetColorName(value[0], tag)
                    colorNode.GetColor(value[0], c)
                    newColorNode.SetColor(colorNumber, c[0], c[1], c[2])

                newColorNode.SetColorName(colorNumber, tag)
                colorNumber += 1

            #      chartNode.SetProperty(valueToPlot, 'lookupTable', labelNode.GetDisplayNode().GetColorNodeID())
            chartNode.SetProperty(valueToPlot, 'lookupTable',
                                  newColorNode.GetID())
Exemplo n.º 10
0
    def createStatsChart(self, labelNode, valueToPlot, ignoreZero=False):
        """Make a MRML chart of the current stats
    """
        layoutNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
        layoutNodes.SetReferenceCount(layoutNodes.GetReferenceCount() - 1)
        layoutNodes.InitTraversal()
        layoutNode = layoutNodes.GetNextItemAsObject()
        layoutNode.SetViewArrangement(
            slicer.vtkMRMLLayoutNode.SlicerLayoutConventionalQuantitativeView)

        chartViewNodes = slicer.mrmlScene.GetNodesByClass(
            'vtkMRMLChartViewNode')
        chartViewNodes.SetReferenceCount(chartViewNodes.GetReferenceCount() -
                                         1)
        chartViewNodes.InitTraversal()
        chartViewNode = chartViewNodes.GetNextItemAsObject()

        arrayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        array = arrayNode.GetArray()
        samples = len(self.labelStats["Labels"])
        tuples = samples
        if ignoreZero and self.labelStats["Labels"].__contains__(0):
            tuples -= 1
        array.SetNumberOfTuples(tuples)
        tuple = 0
        for i in xrange(samples):
            index = self.labelStats["Labels"][i]
            if not (ignoreZero and index == 0):
                array.SetComponent(tuple, 0, index)
                array.SetComponent(tuple, 1, self.labelStats[index,
                                                             valueToPlot])
                array.SetComponent(tuple, 2, 0)
                tuple += 1

        chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        state = chartNode.StartModify()

        chartNode.AddArray(valueToPlot, arrayNode.GetID())

        chartViewNode.SetChartNodeID(chartNode.GetID())

        chartNode.SetProperty('default', 'title', 'Label Statistics')
        chartNode.SetProperty('default', 'xAxisLabel', 'Label')
        chartNode.SetProperty('default', 'yAxisLabel', valueToPlot)
        chartNode.SetProperty('default', 'type', 'Bar')
        chartNode.SetProperty('default', 'xAxisType', 'categorical')
        chartNode.SetProperty('default', 'showLegend', 'off')

        # series level properties
        if labelNode.GetDisplayNode() != None and labelNode.GetDisplayNode(
        ).GetColorNode() != None:
            chartNode.SetProperty(valueToPlot, 'lookupTable',
                                  labelNode.GetDisplayNode().GetColorNodeID())

        chartNode.EndModify(state)
Exemplo n.º 11
0
  def createStatsChart(self, labelNode, valueToPlot, ignoreZero=False):
    """Make a MRML chart of the current stats
    """
    layoutNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
    layoutNodes.SetReferenceCount(layoutNodes.GetReferenceCount()-1)
    layoutNodes.InitTraversal()
    layoutNode = layoutNodes.GetNextItemAsObject()
    layoutNode.SetViewArrangement(slicer.vtkMRMLLayoutNode.SlicerLayoutConventionalQuantitativeView)

    chartViewNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
    chartViewNodes.SetReferenceCount(chartViewNodes.GetReferenceCount()-1)
    chartViewNodes.InitTraversal()
    chartViewNode = chartViewNodes.GetNextItemAsObject()

    arrayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    array = arrayNode.GetArray()
    samples = len(self.labelStats["Labels"])
    tuples = samples
    if ignoreZero and self.labelStats["Labels"].__contains__(0):
      tuples -= 1
    array.SetNumberOfTuples(tuples)
    tuple = 0
    for i in xrange(samples):
        index = self.labelStats["Labels"][i]
        if not (ignoreZero and index == 0):
          array.SetComponent(tuple, 0, index)
          array.SetComponent(tuple, 1, self.labelStats[index,valueToPlot])
          array.SetComponent(tuple, 2, 0)
          tuple += 1

    chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    state = chartNode.StartModify()

    chartNode.AddArray(valueToPlot, arrayNode.GetID())

    chartViewNode.SetChartNodeID(chartNode.GetID())

    chartNode.SetProperty('default', 'title', 'Label Statistics')
    chartNode.SetProperty('default', 'xAxisLabel', 'Label')
    chartNode.SetProperty('default', 'yAxisLabel', valueToPlot)
    chartNode.SetProperty('default', 'type', 'Bar');
    chartNode.SetProperty('default', 'xAxisType', 'categorical')
    chartNode.SetProperty('default', 'showLegend', 'off')

    # series level properties
    if labelNode.GetDisplayNode() != None and labelNode.GetDisplayNode().GetColorNode() != None:
      chartNode.SetProperty(valueToPlot, 'lookupTable', labelNode.GetDisplayNode().GetColorNodeID());

    chartNode.EndModify(state)
Exemplo n.º 12
0
  def plotMotion(self, relOrigins, contourName):
    ln = slicer.util.getNode(pattern='vtkMRMLLayoutNode*')
    ln.SetViewArrangement(ln.SlicerLayoutOneUpQuantitativeView )

    # Get the first ChartView node
    cvn = slicer.util.getNode(pattern='vtkMRMLChartViewNode*')

    # Create arrays of data
    dn = {}
    dim = relOrigins.shape
    for i in range(0, 4):
      dn[i] = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
      a = dn[i].GetArray()
      a.SetNumberOfTuples(dim[1])
      for j in range(0,dim[1]):
        a.SetComponent(j, 0, j)
        a.SetComponent(j, 1, relOrigins[i, j])
        a.SetComponent(j, 2, 0)

    # Create the ChartNode,
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the Chart
    cn.AddArray('L-R', dn[0].GetID())
    cn.AddArray('A-P', dn[1].GetID())
    cn.AddArray('I-S', dn[2].GetID())
    cn.AddArray('abs', dn[3].GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title','Relative ' + contourName + ' motion')
    cn.SetProperty('default', 'xAxisLabel', 'phase')
    cn.SetProperty('default', 'yAxisLabel', 'position [mm]')
    cn.SetProperty('default', 'showGrid', 'on')
    cn.SetProperty('default', 'xAxisPad', '1')
    cn.SetProperty('default', 'showMarkers', 'on')

    cn.SetProperty('L-R', 'color', '#0000ff')
    cn.SetProperty('A-P', 'color', '#00ff00')
    cn.SetProperty('I-S', 'color', '#ff0000')
    cn.SetProperty('abs', 'color', '#000000')

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
Exemplo n.º 13
0
    def createHistogram(self):
        self.setHistogramLayout()

        histogramViewNode = slicer.util.getNode('HistogramView')

        # Show histogram
        self.histogramArrays = {}

        HistNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        for tag in self.regionTags:
            arrayDataNode = slicer.mrmlScene.AddNode(
                slicer.vtkMRMLDoubleArrayNode())
            arrayData = arrayDataNode.GetArray()

            histogram = self.regionHists[tag]
            bins = self.regionBins[tag]

            dataSamples = histogram.size
            dataTuples = dataSamples
            arrayData.SetNumberOfTuples(dataTuples)
            tuple = 0

            for i in xrange(dataSamples):
                arrayData.SetComponent(tuple, 0, bins[i])
                arrayData.SetComponent(tuple, 1, histogram[i])
                arrayData.SetComponent(tuple, 2, 0)
                tuple += 1

            self.histogramArrays[tag] = arrayDataNode
            HistNode.AddArray(tag, arrayDataNode.GetID())

        histogramViewNode.SetChartNodeID(HistNode.GetID())

        HistNode.SetProperty('default', 'title', 'Lung Density Histogram')
        HistNode.SetProperty('default', 'xAxisLabel', 'Density (HU)')
        HistNode.SetProperty('default', 'yAxisLabel', 'Frequency')
        HistNode.SetProperty('default', 'type', 'Line')
        HistNode.SetProperty('default', 'xAxisType', 'quantitative')
        HistNode.SetProperty('default', 'showLegend', 'on')
Exemplo n.º 14
0
  def ChartRepresentationRotation(self, rotationData, timeStamp):
    """
    Summary: This functions represents graphically the array rotationData versus time.
    """
    # Switch to a layout (24) that contains a Chart View to initiate the construction of the widget and Chart View Node
    lns = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
    lns.InitTraversal()
    ln = lns.GetNextItemAsObject()
    ln.SetViewArrangement(506)

    # Get the Chart View Node
    cvns = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
    cvns.InitTraversal()
    cvn = cvns.GetNextItemAsObject()

    # Create an Array Node and add some data
    dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn.GetArray()
    a.SetNumberOfTuples(len(rotationData))
    t=range(0,len(rotationData))
    for i in t:
        a.SetComponent(i, 0, i) # Intentar plotear con respecto al TimeStamp
        a.SetComponent(i, 1, rotationData[i])
        a.SetComponent(i, 2, 0)
    
    # Create a Chart Node.
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
    print('Chart Node created')
    # Add the Array Nodes to the Chart. The first argument is a string used for the legend and to refer to the Array when setting properties.
    cn.AddArray('Rotation', dn.GetID())
    
    # Set a few properties on the Chart. The first argument is a string identifying which Array to assign the property. 
    # 'default' is used to assign a property to the Chart itself (as opposed to an Array Node).
    cn.SetProperty('default', 'title', self.prename + ' Rotation Plot')
    cn.SetProperty('default', 'xAxisLabel', 'Sample Number')
    cn.SetProperty('default', 'yAxisLabel', 'Angle (degrees)')

    # Tell the Chart View which Chart to display
    cvn.SetChartNodeID(cn.GetID())
Exemplo n.º 15
0
    def showChart(self, samples, names):
        print('Logic showing chart\n')

        # S2. Switch to a layout containing a chart viewer
        lm = slicer.app.layoutManager()
        lm.setLayout(
            slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpQuantitativeView)

        # Initialise double array MRML node for each sample list
        # since this is what chart view MRML node needs
        doubleArrays = []
        for sample in samples:
            arrayNode = slicer.mrmlScene.AddNode(
                slicer.vtkMRMLDoubleArrayNode())
            array = arrayNode.GetArray()
            nDataPoints = sample.GetNumberOfTuples()
            array.SetNumberOfTuples(nDataPoints)
            array.SetNumberOfComponents(3)
            for i in range(nDataPoints):
                array.SetComponent(i, 0, i)
                array.SetComponent(i, 1, sample.GetTuple1(i))
                array.SetComponent(i, 2, 0)

            doubleArrays.append(arrayNode)

        # S3. Get the chart view MRML node
        cvNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
        cvNodes.SetReferenceCount(cvNodes.GetReferenceCount()-1)
        cvNodes.InitTraversal()
        cvNode = cvNodes.GetNextItemAsObject()

        # Create a new chart node
        chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
        for pairs in zip(names, doubleArrays):
            chartNode.AddArray(pairs[0], pairs[1].GetID())
        cvNode.SetChartNodeID(chartNode.GetID())

        return
Exemplo n.º 16
0
    def PlotMembershipFunctions(membershipFunctions, min, max, steps):

        step = float(max - min) / steps
        # Setting up the array of values
        chartNode = slicer.vtkMRMLChartNode()
        chartNode.SetScene(slicer.mrmlScene)
        slicer.mrmlScene.AddNode(chartNode)

        for i in range(len(membershipFunctions)):
            arrayNode = slicer.vtkMRMLDoubleArrayNode()
            arrayNode.SetScene(slicer.mrmlScene)
            slicer.mrmlScene.AddNode(arrayNode)
            array = arrayNode.GetArray()
            array.SetNumberOfTuples(int((max - min) / step))

            for j in range(array.GetNumberOfTuples()):
                array.SetComponent(j, 0, min + j * step)
                array.SetComponent(
                    j, 1, membershipFunctions[i].Evaluate(min + j * step))
                array.SetComponent(j, 2, 0)

            # Add array into a chart node
            chartNode.AddArray("Membership Function " + str(i),
                               arrayNode.GetID())

        chartNode.SetProperty('default', 'title', 'Membership Functions')
        chartNode.SetProperty('default', 'xAxisLabel', 'Membership Value')
        chartNode.SetProperty('default', 'yAxisLabel', 'Element')

        # Set the chart in the chart view node
        chartViewNode = slicer.mrmlScene.GetNthNodeByClass(
            0, "vtkMRMLChartViewNode")
        if (chartViewNode is None):
            chartViewNode = slicer.vtkMRMLChartViewNode()
            chartViewNode.SetScene(slicer.mrmlScene)
            slicer.mrmlScene.AddNode(chartViewNode)
        chartViewNode.SetChartNodeID(chartNode.GetID())
Exemplo n.º 17
0
    def showChart(self, samples, names):
        print("Logic showing chart")

        #Switch to a layout containing a chart viewer
        lm = slicer.app.layoutManager()
        lm.setLayout(
            slicer.vtkMRMLLayoutNode.SlicerLayoutFourUpQuantitativeView)

        #initialize double array MRML node for each sample list, since this is what chart view MRML node needs
        doubleArrays = []
        for sample in samples:
            arrayNode = slicer.mrmlScene.AddNode(
                slicer.vtkMRMLDoubleArrayNode())
            array = arrayNode.GetArray()
            nDataPoints = sample.GetNumberOfTuples()
            array.SetNumberOfTuples(nDataPoints)
            array.SetNumberOfComponents(3)
            for i in range(nDataPoints):
                array.SetComponent(i, 0, i)
                array.SetComponent(i, 1, sample.GetTuple1(i))
                array.SetComponent(i, 2, 0)

            doubleArrays.append(arrayNode)

        #Get the chart view mrml node
        cvNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
        cvNodes.SetReferenceCount(cvNodes.GetReferenceCount() - 1)
        cvNodes.InitTraversal()
        cvNode = cvNodes.GetNextItemAsObject()

        #Create a new chart node
        chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
        for pairs in zip(names, doubleArrays):
            chartNode.AddArray(pairs[0], pairs[1].GetID())
        cvNode.SetChartNodeID(chartNode.GetID())

        return
Exemplo n.º 18
0
    def grafTiempo(self):
        ## Se recupera la escena para recuperar el numero de imagenes el el volumen 4D
        escena = slicer.mrmlScene
        VectorInt = []
        volumen4D = self.inputSelector.currentNode()
        #Se carga el volumen seleccionado por el usuario
        numero_imagenes = volumen4D.GetNumberOfFrames(
        )  #Numero de volumenes en el volumen 4D cargado

        # Switch to a layout (24) that contains a Chart View to initiate the construction of the widget and Chart View Node
        lns = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
        lns.InitTraversal()
        ln = lns.GetNextItemAsObject()
        ln.SetViewArrangement(24)

        # Get the Chart View Node
        cvns = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
        cvns.InitTraversal()
        cvn = cvns.GetNextItemAsObject()

        # Create an Array Node and add some data
        dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn.GetArray()
        a.SetNumberOfTuples(numero_imagenes - 2)
        x = range(3, numero_imagenes)
        # se crea el nodo de salida para la multiplicacion de volumenes entre la roi y los volumenes funcionales
        #vol = slicer.vtkMRMLScalarVolumeNode();
        #vol.SetName('salida')
        #escena.AddNode(vol)
        ## se realiza la multiplicacion con cada volumen del volumen 4D
        for i in range(3, numero_imagenes):  #numero_imagenes
            vol = slicer.vtkMRMLScalarVolumeNode()
            vol.SetName('salida' + str(i))
            escena.AddNode(vol)
            parameters = {}  # parametros para la multiplicacion
            parameters['inputVolume1'] = self.inputSelectorRoi.currentNode()
            #dos volumenes de la escena, uno de ellos debe ser la mascara creada en el EDITOR
            parameters['inputVolume2'] = slicer.util.getNode('volumenmovil' +
                                                             str(i))
            parameters['outputVolume'] = vol.GetID()
            # se corre el modulo de multiplicacion
            cliNode = slicer.cli.run(slicer.modules.multiplyscalarvolumes,
                                     None,
                                     parameters,
                                     wait_for_completion=True)
            VolNP = slicer.util.array(
                'salida' + str(i)
            )  # se recupera el volumen resultante de la multiplicacion como un arreglo
            a.SetComponent(i - 2, 0,
                           i * 0.19)  # se agrega el tiempo para graficar
            a.SetComponent(i - 2, 1, np.mean(
                VolNP))  # se arregla el valor medio de intensidad de la roi
            a.SetComponent(i - 2, 2, 0)


# Create a Chart Node.
        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        # Add the Array Nodes to the Chart. The first argument is a string used for the legend and to refer to the Array when setting properties.
        cn.AddArray('Intensidad', dn.GetID())

        # Set a few properties on the Chart. The first argument is a string identifying which Array to assign the property.
        # 'default' is used to assign a property to the Chart itself (as opposed to an Array Node).
        cn.SetProperty('default', 'title', 'Intensidad vs Tiempo')
        cn.SetProperty('default', 'xAxisLabel', 'Time[min]')
        cn.SetProperty('default', 'yAxisLabel', 'Intensity ROI mean')

        # Tell the Chart View which Chart to display
        cvn.SetChartNodeID(cn.GetID())
Exemplo n.º 19
0
  def test_MichaelReid1(self):
    import numpy
    import slicer
    import math

    # Switch to a layout (24) that contains a Chart View to initiate the construction of the widget and Chart View Node
    lns = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
    lns.InitTraversal()
    ln = lns.GetNextItemAsObject()
    ln.SetViewArrangement(24)

    # Get the Chart View Node
    cvns = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
    cvns.InitTraversal()
    cvn = cvns.GetNextItemAsObject()

    referenceToRas = slicer.vtkMRMLLinearTransformNode()
    referenceToRas.SetName('referenceToRas')
    slicer.mrmlScene.AddNode(referenceToRas)

    TREdata = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    TREarray = TREdata.GetArray()
    TREarray.SetNumberOfTuples(9)
    for i in range(1,10):
      TREarray.SetComponent(i, 0, i*10)


    # Experiment parameters (start from here if you have alphaToBeta already)
    for N in range(1,10):  # Number of fiducials
      average,referenceToRasMatrix=self.distance(N,referenceToRas)

      createModelsLogic = slicer.modules.createmodels.logic()
      referenceModelNode = createModelsLogic.CreateCoordinate(20, 2)
      referenceModelNode.SetName('referenceCoordinateModel')
      postModelNode = createModelsLogic.CreateCoordinate(20, 2)
      postModelNode.SetName('RasCoordinateModel')

      referenceModelNode.GetDisplayNode().SetColor(1, 0, 0)
      postModelNode.GetDisplayNode().SetColor(0, 1, 0)

      postModelNode.SetAndObserveTransformNodeID(referenceToRas.GetID())

      targetPoint_Reference = numpy.array([0, 0, 0, 1])
      targetPoint_Ras = referenceToRasMatrix.MultiplyFloatPoint(targetPoint_Reference)
      distance = numpy.linalg.norm(targetPoint_Reference - targetPoint_Ras)
      print "Average distance after registration: " + str(average)
      print 'Target Registration Error: ' + str(distance)
      TREarray.SetComponent(N, 1, distance)

    #plotting TRE as function of num points
    # Create a Chart Node.
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
    # Add the Array Nodes to the Chart. The first argument is a string used for the legend and to refer to the Array when setting properties.
    cn.AddArray('A double array', TREdata.GetID())
    # Set a few properties on the Chart. The first argument is a string identifying which Array to assign the property.
    # 'default' is used to assign a property to the Chart itself (as opposed to an Array Node).
    cn.SetProperty('default', 'title', 'TRE as a function of number of points')
    cn.SetProperty('default', 'xAxisLabel', 'Number of points')
    cn.SetProperty('default', 'yAxisLabel', 'TRE')

    # Tell the Chart View which Chart to display
    cvn.SetChartNodeID(cn.GetID())
Exemplo n.º 20
0
    def test_Charting1(self):
        """ Testing charting
    """

        self.delayDisplay("Starting the test")

        # Change the layout to one that has a chart.  This created the ChartView
        ln = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLLayoutNode')
        ln.SetViewArrangement(24)

        # Get the first ChartView node
        cvn = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLChartViewNode')

        # Create arrays of data
        dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn.GetArray()
        a.SetNumberOfTuples(600)
        x = range(0, 600)
        for i in range(len(x)):
            a.SetComponent(i, 0, x[i] / 50.0)
            a.SetComponent(i, 1, math.sin(x[i] / 50.0))
            a.SetComponent(i, 2, 0)

        dn2 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn2.GetArray()
        a.SetNumberOfTuples(600)
        x = range(0, 600)
        for i in range(len(x)):
            a.SetComponent(i, 0, x[i] / 50.0)
            a.SetComponent(i, 1, math.cos(x[i] / 50.0))
            a.SetComponent(i, 2, 0)

        # Create the ChartNode,
        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        # Add data to the Chart
        cn.AddArray('A double array', dn.GetID())
        cn.AddArray('Another double array', dn2.GetID())

        # Configure properties of the Chart
        cn.SetProperty('default', 'title', 'A simple chart with 2 curves')
        cn.SetProperty('default', 'xAxisLabel', 'Something in x')
        cn.SetProperty('default', 'yAxisLabel', 'Something in y')

        # Set the chart to display
        cvn.SetChartNodeID(cn.GetID())
        self.delayDisplay('A simple chart with 2 curves')

        # Create another ChartNode
        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        # Add data to the Chart
        cn.AddArray('Just one array', dn.GetID())

        # Configure properties of the chart
        cn.SetProperty('default', 'title', 'A simple chart with 1 curve')
        cn.SetProperty('default', 'xAxisLabel', 'Just x')
        cn.SetProperty('default', 'yAxisLabel', 'Just y')

        # Set the chart to display
        cvn.SetChartNodeID(cn.GetID())
        self.delayDisplay('A simple chart with 1 curve')

        # Create another ChartNode
        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        # Add data to the Chart
        cn.AddArray('The other array', dn2.GetID())

        # Set properties on the chart
        cn.SetProperty('default', 'title', 'A simple chart with another curve')
        cn.SetProperty('default', 'xAxisLabel', 'time')
        cn.SetProperty('default', 'yAxisLabel', 'velocity')
        cn.SetProperty('The other array', 'showLines', 'on')
        cn.SetProperty('The other array', 'showMarkers', 'off')
        cn.SetProperty('The other array', 'color', '#fe7d20')

        # Set the chart to display
        cvn.SetChartNodeID(cn.GetID())
        self.delayDisplay('A simple chart with another curve')

        # Create another data array
        dn3 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn3.GetArray()
        a.SetNumberOfTuples(12)
        x = range(0, 12)
        for i in range(len(x)):
            a.SetComponent(i, 0, x[i] / 4.0)
            a.SetComponent(i, 1, math.sin(x[i] / 4.0))
            a.SetComponent(i, 2, 0)

        # Create another ChartNode
        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        # Add data to the chart
        cn.AddArray('Periodic', dn3.GetID())

        # Configure properties of the Chart
        cn.SetProperty('default', 'title', 'A bar chart')
        cn.SetProperty('default', 'xAxisLabel', 'time')
        cn.SetProperty('default', 'yAxisLabel', 'velocity')
        cn.SetProperty('default', 'type', 'Bar')

        # Set the chart to display
        cvn.SetChartNodeID(cn.GetID())
        self.delayDisplay('A bar chart')

        # Test using a date axis
        #

        # Create another data array
        dn4 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn4.GetArray()

        # ugh, python uses localtime
        dates = [
            "3/27/2010", "6/15/2010", "12/14/2010", "3/8/2011", "9/5/2011",
            "12/20/2011", "3/17/2012", "6/12/2012", "9/22/2012", "12/14/2012",
            "3/23/2012"
        ]
        #dates = ["3/27/2010","6/15/2010","9/21/2010","12/14/2010","3/8/2011","5/31/2011","9/5/2011","12/20/2011","3/17/2012","6/12/2012","9/22/2012","12/14/2012","3/23/2012"]
        times = []
        for i in range(len(dates)):
            times.append(
                time.mktime(
                    datetime.datetime.strptime(dates[i],
                                               "%m/%d/%Y").timetuple()))

        a.SetNumberOfTuples(len(times))

        for i in range(len(times)):
            a.SetComponent(i, 0, times[i])
            a.SetComponent(i, 1, math.sin(x[i] / 4.0) + 4)
            a.SetComponent(i, 2, 0)

        # Create another ChartNode
        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        # Add data to the chart
        cn.AddArray('Lesion #1', dn4.GetID())

        # Configure properties of the Chart
        cn.SetProperty('default', 'title', 'A chart with dates')
        cn.SetProperty('default', 'xAxisLabel', 'date')
        cn.SetProperty('default', 'xAxisType', 'date')
        cn.SetProperty('default', 'yAxisLabel', 'size (cm)')
        cn.SetProperty('default', 'type', 'Bar')

        # Set the chart to display
        cvn.SetChartNodeID(cn.GetID())
        self.delayDisplay('A chart with dates')

        # Test using a color table to look up label names
        #
        #

        # Create another data array
        dn5 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn5.GetArray()

        a.SetNumberOfTuples(4)
        a.SetComponent(0, 0, 6)
        a.SetComponent(0, 1, 32)
        a.SetComponent(1, 0, 3)
        a.SetComponent(1, 1, 12)
        a.SetComponent(2, 0, 4)
        a.SetComponent(2, 1, 20)
        a.SetComponent(3, 0, 5)
        a.SetComponent(3, 1, 6)

        # Create another ChartNode
        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        # Add data to the chart
        cn.AddArray('Volumes', dn5.GetID())

        # Configure properties of the Chart
        cn.SetProperty('default', 'title', 'A chart with labels')
        cn.SetProperty('default', 'xAxisLabel', 'structure')
        cn.SetProperty('default', 'xAxisType', 'categorical')
        cn.SetProperty('default', 'yAxisLabel', 'size (cm)')
        cn.SetProperty('default', 'type', 'Bar')
        cn.SetProperty('Volumes', 'lookupTable',
                       slicer.util.getNode('GenericAnatomyColors').GetID())

        # Set the chart to display
        cvn.SetChartNodeID(cn.GetID())
        self.delayDisplay('A chart with labels')

        # Test box plots
        #
        #

        # Create another data array
        dn6 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn6.GetArray()

        a.SetNumberOfTuples(40)
        for i in range(a.GetNumberOfTuples()):
            a.SetComponent(i, 0, 1)
            a.SetComponent(i, 1, (2.0 * random.random() - 0.5) + 20.0)

        # Create another data array
        dn7 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn7.GetArray()

        a.SetNumberOfTuples(25)
        for i in range(20):
            a.SetComponent(i, 0, 2)
            a.SetComponent(i, 1, 2.0 * (2.0 * random.random() - 1.0) + 27.0)
        for i in range(5):
            a.SetComponent(20 + i, 0, 2)
            a.SetComponent(20 + i, 1,
                           10.0 * (2.0 * random.random() - 1.0) + 27.0)

        # Create another data array
        dn8 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn8.GetArray()

        a.SetNumberOfTuples(25)
        for i in range(20):
            a.SetComponent(i, 0, 3)
            a.SetComponent(i, 1, 3.0 * (2.0 * random.random() - 1.0) + 24.0)
        for i in range(5):
            a.SetComponent(20 + i, 0, 2)
            a.SetComponent(20 + i, 1,
                           10.0 * (2.0 * random.random() - 1.0) + 24.0)

        # Create another ChartNode
        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        # Add data to the chart
        cn.AddArray('Controls', dn6.GetID())
        cn.AddArray('Group A', dn7.GetID())
        cn.AddArray('Group B', dn8.GetID())

        # Configure properties of the Chart
        cn.SetProperty('default', 'title', 'A box chart')
        cn.SetProperty('default', 'xAxisLabel', 'population')
        cn.SetProperty('default', 'xAxisType', 'categorical')
        cn.SetProperty('default', 'yAxisLabel', 'size (ml)')
        cn.SetProperty('default', 'type', 'Box')

        # Set the chart to display
        cvn.SetChartNodeID(cn.GetID())
        self.delayDisplay('A box chart')

        #
        self.delayDisplay('Test passed!')
    def chartTest(self):
        import math, random
        lns = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
        lns.InitTraversal()
        ln = lns.GetNextItemAsObject()
        ln.SetViewArrangement(24)

        chartView = findChildren(className='qMRMLChartView')[0]
        print(
            chartView.connect("dataMouseOver(const char *,int,double,double)",
                              self.chartMouseOverCallback))
        print(
            chartView.connect(
                "dataPointClicked(const char *,int,double,double)",
                self.chartCallback))

        cvns = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
        cvns.InitTraversal()
        cvn = cvns.GetNextItemAsObject()

        dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn.GetArray()
        a.SetNumberOfTuples(600)
        x = range(0, 600)
        phase = random.random()
        for i in range(len(x)):
            a.SetComponent(i, 0, x[i] / 50.0)
            a.SetComponent(i, 1, math.sin(phase + x[i] / 50.0))
            a.SetComponent(i, 2, 0)

        dn2 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        a = dn2.GetArray()
        a.SetNumberOfTuples(600)
        x = range(0, 600)
        for i in range(len(x)):
            a.SetComponent(i, 0, x[i] / 50.0)
            a.SetComponent(i, 1, math.cos(phase + x[i] / 50.0))
            a.SetComponent(i, 2, 0)

        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
        cn.AddArray('A double array', dn.GetID())
        cn.AddArray('Another double array', dn2.GetID())

        cvn.SetChartNodeID(cn.GetID())

        cn.SetProperty('default', 'title', 'A simple chart with 2 curves')
        cn.SetProperty('default', 'xAxisLabel', 'Something in x')
        cn.SetProperty('default', 'yAxisLabel', 'Something in y')

        cvn.SetChartNodeID(cn.GetID())

        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
        print cn.GetID()
        cn.AddArray('Just one array', dn.GetID())
        cn.SetProperty('default', 'title', 'A simple chart with 1 curve')
        cn.SetProperty('default', 'xAxisLabel', 'Just x')
        cn.SetProperty('default', 'yAxisLabel', 'Just y')

        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
        print cn.GetID()
        cn.AddArray('The other array', dn2.GetID())
        cn.SetProperty('default', 'title', 'A simple chart with another curve')
        cn.SetProperty('default', 'xAxisLabel', 'time')
        cn.SetProperty('default', 'yAxisLabel', 'velocity')
        cn.SetProperty('The other array', 'showLines', 'on')
        cn.SetProperty('The other array', 'showMarkers', 'off')
        cn.SetProperty('The other array', 'color', '#fe7d20')

        dn3 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
        print dn3.GetID()
        a = dn3.GetArray()
        a.SetNumberOfTuples(12)
        x = range(0, 12)
        for i in range(len(x)):
            a.SetComponent(i, 0, x[i] / 4.0)
            a.SetComponent(i, 1, math.sin(x[i] / 4.0))
            a.SetComponent(i, 2, 0)

        cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
        print cn.GetID()
        cn.AddArray('Periodic', dn3.GetID())
        cn.SetProperty('default', 'title', 'A bar chart')
        cn.SetProperty('default', 'xAxisLabel', 'time')
        cn.SetProperty('default', 'yAxisLabel', 'velocity')
        cn.SetProperty('default', 'type', 'Bar')
Exemplo n.º 22
0
  def test_Charting1(self):
    """ Testing charting
    """

    self.delayDisplay("Starting the test")

    # Change the layout to one that has a chart.  This created the ChartView
    ln = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLLayoutNode')
    ln.SetViewArrangement(24)

    # Get the first ChartView node
    cvn = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLChartViewNode')

    # Create arrays of data
    dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn.GetArray()
    a.SetNumberOfTuples(600)
    x = range(0, 600)
    for i in range(len(x)):
      a.SetComponent(i, 0, x[i]/50.0)
      a.SetComponent(i, 1, math.sin(x[i]/50.0))
      a.SetComponent(i, 2, 0)

    dn2 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn2.GetArray()
    a.SetNumberOfTuples(600)
    x = range(0, 600)
    for i in range(len(x)):
      a.SetComponent(i, 0, x[i]/50.0)
      a.SetComponent(i, 1, math.cos(x[i]/50.0))
      a.SetComponent(i, 2, 0)

    # Create the ChartNode,
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the Chart
    cn.AddArray('A double array', dn.GetID())
    cn.AddArray('Another double array', dn2.GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title', 'A simple chart with 2 curves')
    cn.SetProperty('default', 'xAxisLabel', 'Something in x')
    cn.SetProperty('default', 'yAxisLabel', 'Something in y')

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A simple chart with 2 curves')

    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the Chart
    cn.AddArray('Just one array', dn.GetID())

    # Configure properties of the chart
    cn.SetProperty('default', 'title', 'A simple chart with 1 curve')
    cn.SetProperty('default', 'xAxisLabel', 'Just x')
    cn.SetProperty('default', 'yAxisLabel', 'Just y')

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A simple chart with 1 curve')

    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the Chart
    cn.AddArray('The other array', dn2.GetID())

    # Set properties on the chart
    cn.SetProperty('default', 'title', 'A simple chart with another curve')
    cn.SetProperty('default', 'xAxisLabel', 'time')
    cn.SetProperty('default', 'yAxisLabel', 'velocity')
    cn.SetProperty('The other array', 'showLines', 'on')
    cn.SetProperty('The other array', 'showMarkers', 'off')
    cn.SetProperty('The other array', 'color', '#fe7d20')

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A simple chart with another curve')

    # Create another data array
    dn3 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn3.GetArray()
    a.SetNumberOfTuples(12)
    x = range(0, 12)
    for i in range(len(x)):
      a.SetComponent(i, 0, x[i]/4.0)
      a.SetComponent(i, 1, math.sin(x[i]/4.0))
      a.SetComponent(i, 2, 0)

    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the chart
    cn.AddArray('Periodic', dn3.GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title', 'A bar chart')
    cn.SetProperty('default', 'xAxisLabel', 'time')
    cn.SetProperty('default', 'yAxisLabel', 'velocity')
    cn.SetProperty('default', 'type', 'Bar');

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A bar chart')

    # Test using a date axis
    #

    # Create another data array
    dn4 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn4.GetArray()

    # ugh, python uses localtime
    dates = ["3/27/2010","6/15/2010","12/14/2010","3/8/2011","9/5/2011","12/20/2011","3/17/2012","6/12/2012","9/22/2012","12/14/2012","3/23/2012"]
    #dates = ["3/27/2010","6/15/2010","9/21/2010","12/14/2010","3/8/2011","5/31/2011","9/5/2011","12/20/2011","3/17/2012","6/12/2012","9/22/2012","12/14/2012","3/23/2012"]
    times = []
    for i in range(len(dates)):
      times.append(time.mktime(datetime.datetime.strptime(dates[i], "%m/%d/%Y").timetuple()))

    a.SetNumberOfTuples(len(times))

    for i in range(len(times)):
      a.SetComponent(i, 0, times[i])
      a.SetComponent(i, 1, math.sin(x[i]/4.0) + 4)
      a.SetComponent(i, 2, 0)

    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the chart
    cn.AddArray('Lesion #1', dn4.GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title', 'A chart with dates')
    cn.SetProperty('default', 'xAxisLabel', 'date')
    cn.SetProperty('default', 'xAxisType', 'date')
    cn.SetProperty('default', 'yAxisLabel', 'size (cm)')
    cn.SetProperty('default', 'type', 'Bar');

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A chart with dates')


    # Test using a color table to look up label names
    #
    #

    # Create another data array
    dn5 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn5.GetArray()

    a.SetNumberOfTuples(4)
    a.SetComponent(0, 0, 6)
    a.SetComponent(0, 1, 32)
    a.SetComponent(1, 0, 3)
    a.SetComponent(1, 1, 12)
    a.SetComponent(2, 0, 4)
    a.SetComponent(2, 1, 20)
    a.SetComponent(3, 0, 5)
    a.SetComponent(3, 1, 6)


    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the chart
    cn.AddArray('Volumes', dn5.GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title', 'A chart with labels')
    cn.SetProperty('default', 'xAxisLabel', 'structure')
    cn.SetProperty('default', 'xAxisType', 'categorical')
    cn.SetProperty('default', 'yAxisLabel', 'size (cm)')
    cn.SetProperty('default', 'type', 'Bar');
    cn.SetProperty('Volumes', 'lookupTable', slicer.util.getNode('GenericAnatomyColors').GetID() )

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A chart with labels')

    # Test box plots
    #
    #

    # Create another data array
    dn6 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn6.GetArray()

    a.SetNumberOfTuples(40)
    for i in range(a.GetNumberOfTuples()):
      a.SetComponent(i, 0, 1)
      a.SetComponent(i, 1, (2.0*random.random() - 0.5) + 20.0)

    # Create another data array
    dn7 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn7.GetArray()

    a.SetNumberOfTuples(25)
    for i in range(20):
      a.SetComponent(i, 0, 2)
      a.SetComponent(i, 1, 2.0*(2.0*random.random()-1.0) + 27.0)
    for i in range(5):
      a.SetComponent(20+i, 0, 2)
      a.SetComponent(20+i, 1, 10.0*(2.0*random.random()-1.0) + 27.0)

    # Create another data array
    dn8 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn8.GetArray()

    a.SetNumberOfTuples(25)
    for i in range(20):
      a.SetComponent(i, 0, 3)
      a.SetComponent(i, 1, 3.0*(2.0*random.random()-1.0) + 24.0)
    for i in range(5):
      a.SetComponent(20+i, 0, 2)
      a.SetComponent(20+i, 1, 10.0*(2.0*random.random()-1.0) + 24.0)

    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the chart
    cn.AddArray('Controls', dn6.GetID())
    cn.AddArray('Group A', dn7.GetID())
    cn.AddArray('Group B', dn8.GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title', 'A box chart')
    cn.SetProperty('default', 'xAxisLabel', 'population')
    cn.SetProperty('default', 'xAxisType', 'categorical')
    cn.SetProperty('default', 'yAxisLabel', 'size (ml)')
    cn.SetProperty('default', 'type', 'Box');

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A box chart')

    #
    self.delayDisplay('Test passed!')
Exemplo n.º 23
0
from __future__ import print_function
import slicer
import math

ln = slicer.mrmlScene.GetFirstNodesByClass('vtkMRMLLayoutNode')
print(ln.GetID())
ln.SetViewArrangement(24)

cvn = slicer.mrmlScene.GetFirstNodesByClass('vtkMRMLChartViewNode')
print(cvn.GetID())

dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
print(dn.GetID())
a = dn.GetArray()
a.SetNumberOfTuples(600)
x = range(0, 600)
for i in range(len(x)):
    a.SetComponent(i, 0, x[i]/50.0)
    a.SetComponent(i, 1, math.sin(x[i]/50.0))
    a.SetComponent(i, 2, 0)

dn2 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
print(dn2.GetID())
a = dn2.GetArray()
a.SetNumberOfTuples(600)
x = range(0, 600)
for i in range(len(x)):
    a.SetComponent(i, 0, x[i]/50.0)
    a.SetComponent(i, 1, math.cos(x[i]/50.0))
    a.SetComponent(i, 2, 0)
Exemplo n.º 24
0
  def test_Charting1(self):
    """ Testing charting
    """

    self.delayDisplay("Starting the test")
    #
    # first, get some data
    #
    #import urllib
    #downloads = (
    #    ('http://slicer.kitware.com/midas3/download?items=5767', 'FA.nrrd', slicer.util.loadVolume),
    #    )
    #
    #for url,name,loader in downloads:
    #  filePath = slicer.app.temporaryPath + '/' + name
    #  if not os.path.exists(filePath) or os.stat(filePath).st_size == 0:
    #    print('Requesting download %s from %s...\n' % (name, url))
    #    urllib.urlretrieve(url, filePath)
    #  if loader:
    #    print('Loading %s...\n' % (name,))
    #    loader(filePath)
    #self.delayDisplay('Finished with download and loading\n')

    #volumeNode = slicer.util.getNode(pattern="FA")
    #logic = ChartingLogic()
    #self.assertIsNotNone( logic.hasImageData(volumeNode) )

    # Change the layout to one that has a chart.  This created the ChartView
    ln = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLLayoutNode')
    ln.SetViewArrangement(24)

    # Get the first ChartView node
    cvn = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLChartViewNode')

    # Create arrays of data
    dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn.GetArray()
    a.SetNumberOfTuples(600)
    x = range(0, 600)
    for i in range(len(x)):
      a.SetComponent(i, 0, x[i]/50.0)
      a.SetComponent(i, 1, math.sin(x[i]/50.0))
      a.SetComponent(i, 2, 0)

    dn2 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn2.GetArray()
    a.SetNumberOfTuples(600)
    x = range(0, 600)
    for i in range(len(x)):
      a.SetComponent(i, 0, x[i]/50.0)
      a.SetComponent(i, 1, math.cos(x[i]/50.0))
      a.SetComponent(i, 2, 0)

    # Create the ChartNode,
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the Chart
    cn.AddArray('A double array', dn.GetID())
    cn.AddArray('Another double array', dn2.GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title', 'A simple chart with 2 curves')
    cn.SetProperty('default', 'xAxisLabel', 'Something in x')
    cn.SetProperty('default', 'yAxisLabel', 'Something in y')

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A simple chart with 2 curves')

    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the Chart
    cn.AddArray('Just one array', dn.GetID())

    # Configure properties of the chart
    cn.SetProperty('default', 'title', 'A simple chart with 1 curve')
    cn.SetProperty('default', 'xAxisLabel', 'Just x')
    cn.SetProperty('default', 'yAxisLabel', 'Just y')

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A simple chart with 1 curve')

    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the Chart
    cn.AddArray('The other array', dn2.GetID())

    # Set properties on the chart
    cn.SetProperty('default', 'title', 'A simple chart with another curve')
    cn.SetProperty('default', 'xAxisLabel', 'time')
    cn.SetProperty('default', 'yAxisLabel', 'velocity')
    cn.SetProperty('The other array', 'showLines', 'on')
    cn.SetProperty('The other array', 'showMarkers', 'off')
    cn.SetProperty('The other array', 'color', '#fe7d20')

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A simple chart with another curve')

    # Create another data array
    dn3 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn3.GetArray()
    a.SetNumberOfTuples(12)
    x = range(0, 12)
    for i in range(len(x)):
      a.SetComponent(i, 0, x[i]/4.0)
      a.SetComponent(i, 1, math.sin(x[i]/4.0))
      a.SetComponent(i, 2, 0)

    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the chart
    cn.AddArray('Periodic', dn3.GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title', 'A bar chart')
    cn.SetProperty('default', 'xAxisLabel', 'time')
    cn.SetProperty('default', 'yAxisLabel', 'velocity')
    cn.SetProperty('default', 'type', 'Bar');

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A bar chart')

    # Test using a date axis
    #

    # Create another data array
    dn4 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn4.GetArray()

    # ugh, python uses localtime
    dates = ["3/27/2010","6/15/2010","12/14/2010","3/8/2011","9/5/2011","12/20/2011","3/17/2012","6/12/2012","9/22/2012","12/14/2012","3/23/2012"]
    #dates = ["3/27/2010","6/15/2010","9/21/2010","12/14/2010","3/8/2011","5/31/2011","9/5/2011","12/20/2011","3/17/2012","6/12/2012","9/22/2012","12/14/2012","3/23/2012"]
    times = []
    for i in range(len(dates)):
      times.append(time.mktime(datetime.datetime.strptime(dates[i], "%m/%d/%Y").timetuple()))

    a.SetNumberOfTuples(len(times))

    for i in range(len(times)):
      a.SetComponent(i, 0, times[i])
      a.SetComponent(i, 1, math.sin(x[i]/4.0) + 4)
      a.SetComponent(i, 2, 0)

    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the chart
    cn.AddArray('Lesion #1', dn4.GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title', 'A chart with dates')
    cn.SetProperty('default', 'xAxisLabel', 'date')
    cn.SetProperty('default', 'xAxisType', 'date')
    cn.SetProperty('default', 'yAxisLabel', 'size (cm)')
    cn.SetProperty('default', 'type', 'Bar');

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A chart with dates')


    # Test using a color table to look up label names
    #
    #

    # Create another data array
    dn5 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn5.GetArray()

    a.SetNumberOfTuples(4)
    a.SetComponent(0, 0, 6)
    a.SetComponent(0, 1, 32)
    a.SetComponent(1, 0, 3)
    a.SetComponent(1, 1, 12)
    a.SetComponent(2, 0, 4)
    a.SetComponent(2, 1, 20)
    a.SetComponent(3, 0, 5)
    a.SetComponent(3, 1, 6)


    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the chart
    cn.AddArray('Volumes', dn5.GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title', 'A chart with labels')
    cn.SetProperty('default', 'xAxisLabel', 'structure')
    cn.SetProperty('default', 'xAxisType', 'categorical')
    cn.SetProperty('default', 'yAxisLabel', 'size (cm)')
    cn.SetProperty('default', 'type', 'Bar');
    cn.SetProperty('Volumes', 'lookupTable', slicer.util.getNode('GenericAnatomyColors').GetID() )

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A chart with labels')

    # Test box plots
    #
    #

    # Create another data array
    dn6 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn6.GetArray()

    a.SetNumberOfTuples(40)
    for i in range(a.GetNumberOfTuples()):
      a.SetComponent(i, 0, 1)
      a.SetComponent(i, 1, (2.0*random.random() - 0.5) + 20.0)

    # Create another data array
    dn7 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn7.GetArray()

    a.SetNumberOfTuples(25)
    for i in range(20):
      a.SetComponent(i, 0, 2)
      a.SetComponent(i, 1, 2.0*(2.0*random.random()-1.0) + 27.0)
    for i in range(5):
      a.SetComponent(20+i, 0, 2)
      a.SetComponent(20+i, 1, 10.0*(2.0*random.random()-1.0) + 27.0)

    # Create another data array
    dn8 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn8.GetArray()

    a.SetNumberOfTuples(25)
    for i in range(20):
      a.SetComponent(i, 0, 3)
      a.SetComponent(i, 1, 3.0*(2.0*random.random()-1.0) + 24.0)
    for i in range(5):
      a.SetComponent(20+i, 0, 2)
      a.SetComponent(20+i, 1, 10.0*(2.0*random.random()-1.0) + 24.0)

    # Create another ChartNode
    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

    # Add data to the chart
    cn.AddArray('Controls', dn6.GetID())
    cn.AddArray('Group A', dn7.GetID())
    cn.AddArray('Group B', dn8.GetID())

    # Configure properties of the Chart
    cn.SetProperty('default', 'title', 'A box chart')
    cn.SetProperty('default', 'xAxisLabel', 'population')
    cn.SetProperty('default', 'xAxisType', 'categorical')
    cn.SetProperty('default', 'yAxisLabel', 'size (ml)')
    cn.SetProperty('default', 'type', 'Box');

    # Set the chart to display
    cvn.SetChartNodeID(cn.GetID())
    self.delayDisplay('A box chart')

    #
    self.delayDisplay('Test passed!')
Exemplo n.º 25
0
    def plot(self, args):

        if "Title" in args:
            self.Title = args["Title"]
        if "XLabel" in args:
            self.XLabel = args["XLabel"]
        if "YLabel" in args:
            self.YLabel = args["YLabel"]
        if "Data" in args:
            self.Data = args["Data"]
        if "xAxis" in args:
            self.xAxis = args["xAxis"]
        if "Name" in args:
            self.chartName = args["Name"]

        # Get the Chart View Node
        chartViewNodes = slicer.mrmlScene.GetNodesByClass(
            'vtkMRMLChartViewNode')
        chartViewNodes.InitTraversal()
        chartViewNode = chartViewNodes.GetNextItemAsObject()

        # Create an Array Node and add some data
        serieArrayNode = slicer.mrmlScene.AddNode(
            slicer.vtkMRMLDoubleArrayNode())
        serieArrayNode.SetName(self.doubleArrayNodeFMRSIName)
        serieArray = serieArrayNode.GetArray()

        lenXAxis = len(self.xAxis)
        lenData = len(self.Data)

        if lenXAxis == 0:
            self.xAxis = range(0, lenData)

        if lenData > 0:
            serieArray.SetNumberOfTuples(lenData)
            for i in range(lenData):
                serieArray.SetComponent(i, 0, self.xAxis[i])
                serieArray.SetComponent(i, 1, self.Data[i])
                serieArray.SetComponent(i, 2, 0)

        # Create a Chart Node.
        # Delete previous existing node
        try:
            chartNode = slicer.util.getNode(self.chartName)
        except:
            chartNode = None

        if chartNode is not None:
            nod = chartNode.GetArray('Data')
            if nod is not None:
                slicer.mrmlScene.RemoveNode(slicer.util.getNode(nod))

            slicer.mrmlScene.RemoveNode(chartNode)

        chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

        # Set a few properties on the Chart. The first argument is a string identifying which Array to assign the property.
        # 'default' is used to assign a property to the Chart itself (as opposed to an Array Node).
        chartNode.SetProperty('default', 'title', self.Title)
        chartNode.SetProperty('default', 'xAxisLabel', self.XLabel)
        chartNode.SetProperty('default', 'yAxisLabel', self.YLabel)
        chartNode.SetProperty('default', 'color', self.Color)
        chartNode.SetName(self.chartName)

        # Add the Array Nodes to the Chart. The first argument is a string used for the legend and to refer to the Array when setting properties.
        chartNode.AddArray('Data', serieArrayNode.GetID())
        # chartNode.AddArray('Another double array', serieArrayNode2.GetID())

        # Tell the Chart View which Chart to display
        chartViewNode.SetChartNodeID(chartNode.GetID())
Exemplo n.º 26
0
  def chartTest(self):
    import math,random
    ln = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLLayoutNode')
    ln.SetViewArrangement(24)

    chartView = findChildren(className='qMRMLChartView')[0]
    print(chartView.connect("dataMouseOver(const char *,int,double,double)", self.chartMouseOverCallback))
    print(chartView.connect("dataPointClicked(const char *,int,double,double)", self.chartCallback))

    cvn = slicer.mrmlScene.GetFirstNodeByClass('vtkMRMLChartViewNode')

    dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn.GetArray()
    a.SetNumberOfTuples(600)
    x = range(0, 600)
    phase = random.random()
    for i in range(len(x)):
        a.SetComponent(i, 0, x[i]/50.0)
        a.SetComponent(i, 1, math.sin(phase+x[i]/50.0))
        a.SetComponent(i, 2, 0)

    dn2 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    a = dn2.GetArray()
    a.SetNumberOfTuples(600)
    x = range(0, 600)
    for i in range(len(x)):
        a.SetComponent(i, 0, x[i]/50.0)
        a.SetComponent(i, 1, math.cos(phase+x[i]/50.0))
        a.SetComponent(i, 2, 0)

    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
    cn.AddArray('A double array', dn.GetID())
    cn.AddArray('Another double array', dn2.GetID())

    cvn.SetChartNodeID(cn.GetID())

    cn.SetProperty('default', 'title', 'A simple chart with 2 curves')
    cn.SetProperty('default', 'xAxisLabel', 'Something in x')
    cn.SetProperty('default', 'yAxisLabel', 'Something in y')

    cvn.SetChartNodeID(cn.GetID())

    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
    print(cn.GetID())
    cn.AddArray('Just one array', dn.GetID())
    cn.SetProperty('default', 'title', 'A simple chart with 1 curve')
    cn.SetProperty('default', 'xAxisLabel', 'Just x')
    cn.SetProperty('default', 'yAxisLabel', 'Just y')

    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
    print(cn.GetID())
    cn.AddArray('The other array', dn2.GetID())
    cn.SetProperty('default', 'title', 'A simple chart with another curve')
    cn.SetProperty('default', 'xAxisLabel', 'time')
    cn.SetProperty('default', 'yAxisLabel', 'velocity')
    cn.SetProperty('The other array', 'showLines', 'on')
    cn.SetProperty('The other array', 'showMarkers', 'off')
    cn.SetProperty('The other array', 'color', '#fe7d20')

    dn3 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
    print(dn3.GetID())
    a = dn3.GetArray()
    a.SetNumberOfTuples(12)
    x = range(0, 12)
    for i in range(len(x)):
        a.SetComponent(i, 0, x[i]/4.0)
        a.SetComponent(i, 1, math.sin(x[i]/4.0))
        a.SetComponent(i, 2, 0)

    cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
    print(cn.GetID())
    cn.AddArray('Periodic', dn3.GetID())
    cn.SetProperty('default', 'title', 'A bar chart')
    cn.SetProperty('default', 'xAxisLabel', 'time')
    cn.SetProperty('default', 'yAxisLabel', 'velocity')
    cn.SetProperty('default', 'type', 'Bar');
from __future__ import print_function
import slicer
import math

ln = slicer.mrmlScene.GetFirstNodesByClass('vtkMRMLLayoutNode')
print(ln.GetID())
ln.SetViewArrangement(24)

cvn = slicer.mrmlScene.GetFirstNodesByClass('vtkMRMLChartViewNode')
print(cvn.GetID())

dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
print(dn.GetID())
a = dn.GetArray()
a.SetNumberOfTuples(600)
x = range(0, 600)
for i in range(len(x)):
    a.SetComponent(i, 0, x[i] / 50.0)
    a.SetComponent(i, 1, math.sin(x[i] / 50.0))
    a.SetComponent(i, 2, 0)

dn2 = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
print(dn2.GetID())
a = dn2.GetArray()
a.SetNumberOfTuples(600)
x = range(0, 600)
for i in range(len(x)):
    a.SetComponent(i, 0, x[i] / 50.0)
    a.SetComponent(i, 1, math.cos(x[i] / 50.0))
    a.SetComponent(i, 2, 0)
  def createStatsChart(self, labelNode, valueToPlot, ignoreZero=False, normalize=False,nbins=-1):
    if valueToPlot != "Distribution":
      LabelStatisticsLogic.createStatsChart(self, labelNode, valueToPlot, ignoreZero)
    else:
      layoutNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
      layoutNodes.SetReferenceCount(layoutNodes.GetReferenceCount()-1)
      layoutNodes.InitTraversal()
      layoutNode = layoutNodes.GetNextItemAsObject()
      layoutNode.SetViewArrangement(slicer.vtkMRMLLayoutNode.SlicerLayoutConventionalQuantitativeView)

      chartViewNodes = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
      chartViewNodes.SetReferenceCount(chartViewNodes.GetReferenceCount()-1)
      chartViewNodes.InitTraversal()
      chartViewNode = chartViewNodes.GetNextItemAsObject()

      chartNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

      displayNode = self.labelNode.GetDisplayNode()
      colorNode = displayNode.GetColorNode()
      color=numpy.full(4,0)

      #arrayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
      #array = arrayNode.GetArray()
      samples = len(self.labelStats["Labels"])
      qu=QCLib.QCUtil()

      rect=qu.minRectangle(labelNode)
      ROI=labelNode.GetImageData()
      nslices=ROI.GetDimensions()[2] #3D Volumes only
      im=self.grayscaleNode.GetImageData()

      s=[numpy.Inf,-numpy.Inf]
      start=0
      if ignoreZero and samples>1:
        start=1

      for ln in range(start,samples):
        l=self.labelStats["Labels"][ln]
        min=self.labelStats[l,"Min"]
        max=self.labelStats[l,"Max"]
        if min<s[0]:
          s[0]=min
        if max>s[1]:
          s[1]=max

      sr=range(int(s[0]),int(s[1])+1)

      distr={}
      cont={}
      for sl in range(nslices):
        if ignoreZero:
            xmin=rect['xmin'][sl]
            xmax=rect['xmax'][sl]
            ymin=rect['ymin'][sl]
            ymax=rect['ymax'][sl]
        else:
          xmin=0
          xmax=ROI.GetDimensions()[0]
          ymin=0
          ymax=ROI.GetDimensions()[1]

        for x in range(xmin,xmax+1):
          for y in range(ymin,ymax+1):
            label=ROI.GetScalarComponentAsDouble(x,y,sl,0)

            if not (ignoreZero and label == 0): #TODO : use numpy.histogram
              val=im.GetScalarComponentAsDouble(x,y,sl,0)
              try:
                dslab=distr[label]
              except: #TODO: errorcode
                distr[label]=numpy.full(self.labelStats[label,"Count"],0)
                dslab=distr[label]
                cont[label]=-1

              cont[label]=cont[label]+1
              dslab[cont[label]]=val

      #dx=numpy.diff(sr[0:2])[0]
      for n in range(samples):
        label=self.labelStats["Labels"][n]
        if not (ignoreZero and label == 0):
          if nbins=="FB":
            #Freedman Diaconis Estimator
            IQR=numpy.percentile(distr[label],75)-numpy.percentile(distr[label],25)
            bnw=2*IQR/numpy.power(distr[label].size,1.0/3.0)
            nb=int((s[1]-s[0])/bnw)
          elif nbins=="Rice":
            #Rice
            nb=int(2*numpy.power(distr[label].size,1.0/3.0))
          elif nbins=="Doane":
            #Doane
            mu=numpy.mean(distr[label])
            std=numpy.std(distr[label])
            g1=numpy.mean(numpy.power((distr[label]-mu)/float(std),3))
            n=distr[label].size
            sg1=numpy.sqrt(float(6*(n-2))/float(((n+1)*(n+3))))
            nb=int(1+numpy.log2(n)+numpy.log2(1+numpy.abs(g1)/sg1))
          elif nbins<=0:
            #nb=int(s[1]-s[0]+1) #TODO: if is not integer?
            nb=len(numpy.unique(distr[label]))
          else:
            #Manual
            nb=nbins
            
          if nbins>0:
            nm="-hist-"+str(nb)
          else:
            nm=""
          name=colorNode.GetColorName(label) + "-" + self.grayscaleNode.GetName() + nm

          ntuple=nb
          hst,bins=numpy.histogram(distr[label],bins=nb,range=[s[0],s[1]],density=normalize)

          arrayNode = slicer.mrmlScene.GetNodesByClassByName("vtkMRMLDoubleArrayNode",name).GetItemAsObject(0)

          if not arrayNode:
            arrayNode = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
            arrayNode.SetName(name)

          arrayD = arrayNode.GetArray()

          arrayD.SetNumberOfComponents(2)
          arrayD.SetNumberOfTuples(ntuple)

          for n in range(ntuple):
            arrayD.SetComponent(n, 0, bins[n]) #TODO
            arrayD.SetComponent(n, 1, hst[n])
            
          state = chartNode.StartModify()
          chartNode.AddArray(name, arrayNode.GetID())
          chartViewNode.SetChartNodeID(chartNode.GetID())
          chartNode.SetProperty('default', 'title', 'Histogram')
          chartNode.SetProperty('default', 'xAxisLabel', 'Grey Values')
          chartNode.SetProperty('default', 'yAxisLabel', valueToPlot)
          chartNode.SetProperty('default', 'type', 'Line');
          chartNode.SetProperty('default', 'xAxisType', 'quantitative')
          chartNode.SetProperty('default', 'yAxisType', 'quantitative')
          chartNode.SetProperty('default', 'showLegend', 'on')
          colorNode.GetColor(label,color)
          col='#'+str(hex(color[0]*255)[2:4])+str(hex(color[1]*255)[2:4])+str(hex(color[2]*255)[2:4])
          chartNode.SetProperty(name,'color',col)
          chartNode.EndModify(state)
Exemplo n.º 29
0
    def OnCurveButton(self):
        if (str(self.inputSmoothSelector.currentNode())
                or str(self.imagenMultuply.currentNode())) == "None":
            print('ERROR: Select Input Volume Node and Label Mask')
            qt.QMessageBox.information(
                slicer.util.mainWindow(), 'Slicer Python',
                'ERROR: Select Input Volume Node and Label Mask')

            return True
        else:

            mvNode = slicer.vtkMRMLMultiVolumeNode(
            )  #creación nodo multivolumen
            slicer.mrmlScene.AddNode(mvNode)  #añadir a la escena el nodo
            escena = slicer.mrmlScene
            volumen4D = self.inputSmoothSelector.currentNode()
            imagenvtk4D = volumen4D.GetImageData()
            numero_imagenes = volumen4D.GetNumberOfFrames(
            )  #numero de frames del MV
            #print('imagenes: ' + str(numero_imagenes))
            #filtro vtk para descomponer un volumen 4D
            extract1 = vtk.vtkImageExtractComponents()
            extract1.SetInputData(imagenvtk4D)
            #matriz de transformacion
            ras2ijk = vtk.vtkMatrix4x4()
            ijk2ras = vtk.vtkMatrix4x4()
            #le solicitamos al volumen original que nos devuelva sus matrices
            volumen4D.GetRASToIJKMatrix(ras2ijk)
            volumen4D.GetIJKToRASMatrix(ijk2ras)
            #creo un volumen nuevo
            #volumenFijo = self.inputVolumeSelector.currentNode();
            #le asigno las transformaciones

            #le asigno el volumen 3D fijo
            extract1.SetComponents(0)
            extract1.Update()
            volumenFiltro = slicer.vtkMRMLScalarVolumeNode()
            volumenFiltro.SetName('Filtro')
            volumenFiltro.SetAndObserveImageData(extract1.GetOutput())
            volumenFiltro.SetRASToIJKMatrix(ras2ijk)
            volumenFiltro.SetIJKToRASMatrix(ijk2ras)
            #anado el nuevo volumen a la escena
            escena.AddNode(volumenFiltro)

            volumenSalida = slicer.vtkMRMLScalarVolumeNode()
            #creacion de volumen de salida
            slicer.mrmlScene.AddNode(volumenSalida)
            j = 1
            bandera = 0

            frameLabelsAttr = ''
            volumeLabels = vtk.vtkDoubleArray()
            volumeLabels.SetNumberOfTuples(numero_imagenes)
            volumeLabels.SetNumberOfComponents(1)
            volumeLabels.Allocate(numero_imagenes)

            mvImage = vtk.vtkImageData()
            mvImage.SetExtent(volumenFiltro.GetImageData().GetExtent()
                              )  ##Se le asigna la dimension del miltuvolumen
            mvImage.AllocateScalars(
                volumenFiltro.GetImageData().GetScalarType(), numero_imagenes
            )  ##Se le asigna el tipo y numero de cortes al multivolumen
            mvImageArray = vtk.util.numpy_support.vtk_to_numpy(
                mvImage.GetPointData().GetScalars()
            )  ## Se crea la matriz de datos donde va a ir la imagen

            mat = vtk.vtkMatrix4x4()

            ##Se hace la conversion y se obtiene la matriz de transformacion del nodo
            volumenFiltro.GetRASToIJKMatrix(mat)
            mvNode.SetRASToIJKMatrix(mat)
            volumenFiltro.GetIJKToRASMatrix(mat)
            mvNode.SetIJKToRASMatrix(mat)
            ##
            vector_int = []
            for i in range(numero_imagenes):
                # extraigo la imagen movil
                extract1.SetComponents(i)  #Seleccionar un volumen lejano
                extract1.Update()
                #Creo un volumen movil, y realizamos el mismo procedimiento que con el fijo

                volumenFiltro.SetAndObserveImageData(extract1.GetOutput())
                volumenFiltro.SetName('Filtrado')
                escena.AddNode(volumenFiltro)

                #parametros para la operacion de registro que seran entregados al modulo cli "brainsfit" segun tipo de registro
                parameters = {}
                parameters['Conductance'] = 1
                parameters['numberOfIterations'] = 5
                parameters['timeStep'] = 0.0625
                parameters['inputVolume'] = volumenFiltro.GetID()
                parameters['outputVolume'] = volumenFiltro.GetID()
                cliNode = slicer.cli.run(
                    slicer.modules.gradientanisotropicdiffusion,
                    None,
                    parameters,
                    wait_for_completion=True)

                slicer.util.saveNode(volumenFiltro,
                                     'volumenFilter' + str(i) + '.nrrd')

                vol = slicer.vtkMRMLScalarVolumeNode()
                escena = slicer.mrmlScene
                vol.SetName('salida')
                escena.AddNode(vol)
                Label = self.imagenMultuply.currentNode()
                Label = slicer.util.getNode('vtkMRMLLabelMapVolumeNode1')

                #parametros para la operacion de registro
                parameters = {}
                parameters['inputVolume1'] = escena.GetNodeByID(
                    'vtkMRMLLabelMapVolumeNode1'
                )  #dos volumenes de la escena, uno de ellos debe ser la mascara creada en el EDITOR
                parameters['inputVolume2'] = volumenFiltro
                parameters['outputVolume'] = vol
                cliNode = slicer.cli.run(slicer.modules.multiplyscalarvolumes,
                                         None,
                                         parameters,
                                         wait_for_completion=True)
                slicer.util.saveNode(vol, 'volumenMulty' + str(i) + '.nrrd')
                print(vol)
                a = slicer.util.arrayFromVolume(vol)
                intensidad = np.mean(a[:])
                vector_int.append(intensidad)

        # Switch to a layout (24) that contains a Chart View to initiate the construction of the widget and Chart View Node
            lns = slicer.mrmlScene.GetNodesByClass('vtkMRMLLayoutNode')
            lns.InitTraversal()
            ln = lns.GetNextItemAsObject()
            ln.SetViewArrangement(24)

            # Get the Chart View Node
            cvns = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
            cvns.InitTraversal()
            cvn = cvns.GetNextItemAsObject()

            # Create an Array Node and add some data
            dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
            a = dn.GetArray()
            a.SetNumberOfTuples(numero_imagenes)
            x = range(0, 600)
            i = 0
            for i in range(numero_imagenes):
                a.SetComponent(i, 0, i)
                a.SetComponent(i, 1, vector_int[i])
                a.SetComponent(i, 2, 0)

            # Create a Chart Node.
            cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())

            # Add the Array Nodes to the Chart. The first argument is a string used for the legend and to refer to the Array when setting properties.
            cn.AddArray('Prostate perfusion', dn.GetID())

            # Set a few properties on the Chart. The first argument is a string identifying which Array to assign the property.
            # 'default' is used to assign a property to the Chart itself (as opposed to an Array Node).
            cn.SetProperty('default', 'title', 'Perfusion curves')
            cn.SetProperty('default', 'xAxisLabel', 'Time (s)')
            cn.SetProperty('default', 'yAxisLabel', 'Intensity')

            # Tell the Chart View which Chart to display
            cvn.SetChartNodeID(cn.GetID())