def splitModels(self, Surface):
        dataArray = Surface.GetPointData().GetScalars("GroupIds")
        scalarRange = dataArray.GetRange()

        newPdList = []
        newCaList = []
        self._parentClass._helper.debug("started splitter")
        # generate containers CellArray & PolyData + copy points
        for i in range(1, int(scalarRange[1]) + 2):
            newCellArray = slicer.vtkCellArray()
            newPolyData = slicer.vtkPolyData()

            points = slicer.vtkPoints()
            points.DeepCopy(Surface.GetPoints())
            newPolyData.SetPoints(points)
            newPolyData.SetPolys(newCellArray)
            newPolyData.Update()

            newPdList.append(newPolyData)
            newCaList.append(newCellArray)

        #Fill containers with Polys
        for i in range(0, Surface.GetPolys().GetNumberOfCells()):
            poi = Surface.GetCell(i).GetPointIds()

            if (poi.GetNumberOfIds() == 0):
                continue

            scalarsOfPoints = []

            for pid in range(0, poi.GetNumberOfIds()):
                p = poi.GetId(pid)
                scalarsOfPoints.append(dataArray.GetValue(p))

            max = 0
            largestIndex = 0
            for j in range(1, int(scalarRange[1]) + 2):
                c = scalarsOfPoints.count(j)
                if c >= max:
                    max = c
                    largestIndex = j
            newCaList[largestIndex].InsertNextCell(Surface.GetCell(i))

        # clean PolyData
        for pd in newPdList:
            cleanPolyData = slicer.vtkCleanPolyData()
            cleanPolyData.SetInput(pd)
            cleanPolyData.Update()
            pd.DeepCopy(cleanPolyData.GetOutput())

        self._parentClass._helper.debug("finished splitter")

        return newPdList
  def splitModels(self,Surface):
    dataArray=Surface.GetPointData().GetScalars("GroupIds")
    scalarRange=dataArray.GetRange()
    
    newPdList=[]
    newCaList=[]
    self._parentClass._helper.debug("started splitter")
    # generate containers CellArray & PolyData + copy points
    for i in range(1,int(scalarRange[1])+2):
      newCellArray=slicer.vtkCellArray()
      newPolyData=slicer.vtkPolyData()

      points=slicer.vtkPoints()
      points.DeepCopy(Surface.GetPoints())		
      newPolyData.SetPoints(points)
      newPolyData.SetPolys(newCellArray)
      newPolyData.Update()

      newPdList.append(newPolyData)
      newCaList.append(newCellArray)

    #Fill containers with Polys
    for i in range (0,Surface.GetPolys().GetNumberOfCells()):
      poi=Surface.GetCell(i).GetPointIds()

      if(poi.GetNumberOfIds()==0):
        continue

      scalarsOfPoints =[]
  
      for pid in range(0,poi.GetNumberOfIds()): 
        p=poi.GetId(pid)
        scalarsOfPoints.append(dataArray.GetValue(p))

      max=0
      largestIndex=0
      for j in range(1,int(scalarRange[1])+2):
        c=scalarsOfPoints.count(j)
        if c >= max:
          max=c
          largestIndex=j
      newCaList[largestIndex].InsertNextCell(Surface.GetCell(i))

    # clean PolyData
    for pd in newPdList:
      cleanPolyData = slicer.vtkCleanPolyData();
      cleanPolyData.SetInput(pd);
      cleanPolyData.Update();
      pd.DeepCopy(cleanPolyData.GetOutput())
      
    self._parentClass._helper.debug("finished splitter")

    return newPdList
def Execute(dwi_node, seeds_node, mask_node, ff_node, \
            record_fa = False, record_state = False, record_cov = False, \
            model="two-tensor", FA_min=.15, GA_min=.10,
            seeds=1, labels=[1],
            Qm=.0030, Ql=100, Rs=.015, theta_max=45):
    for i in xrange(10):
        print ''

    is_2t = (model == "two-tensor")

    print 'HACK hardcode 2T'
    is_2t = True
    follow = iff(is_2t, follow2t, follow1t)

    state_dim = iff(is_2t, 10, 5)  # dimension of state space

    theta_min = 5  # angle which triggers branch
    param = dict({
        'FA_min': FA_min,  # fractional anisotropy stopping threshold
        'GA_min': GA_min,  # generalized anisotropy stopping threshold
        'dt': .2,  # forward Euler step size (path integration)
        'max_len': 250,  # stop if fiber gets this long
        'min_radius': .87,  # stop if fiber curves this much
        'seeds': seeds,  # number of seeds in each voxel
        'theta_min':
        np.cos(theta_min * np.pi / 180),  # angle which triggers branch
        'theta_max':
        np.cos(theta_max * np.pi / 180),  # angle which triggers branch
        'min_radius': .87,  # stop if fiber curves this much
        'record_fa': record_fa,
        'record_st': record_state,
        'record_co': record_cov,
        # Kalman filter parameters
        'Qm': Qm,  # injected angular noise
        'Ql': Ql,  # injected eigenvalue noise
        'Rs': Rs,  # dependent on latent noise in your data
        'P0': 0.01 * np.eye(state_dim)
    })  # initial covariance

    from Slicer import slicer

    #     foo = slicer.vtkFloatArray()
    #     foo.SetNumberOfComponents(1)
    #     foo.SetName('foo')

    #     foo.InsertNextValue(234)          # Success
    #     foo.InsertNextValue(23.4)         # Success
    #     foo.InsertNextValue(255 * np.random.rand())       # Success
    #     foo.InsertNextValue(np.empty(1,dtype='float32'))  # FAIL
    #     foo.InsertNextValue(np.empty(1,dtype='float64'))  # FAIL
    #     asdf

    scene = slicer.MRMLScene
    dwi_node = scene.GetNodeByID(dwi_node)
    seeds_node = scene.GetNodeByID(seeds_node)
    mask_node = scene.GetNodeByID(mask_node)
    ff_node = scene.GetNodeByID(ff_node)

    # ensure normalized signal
    bb = dwi_node.GetBValues().ToArray()
    if np.any(bb.sum(1) == 0):
        import Slicer
        Slicer.tk.eval(
            'tk_messageBox -message "Use the \'Normalize Signal\' module to prepare the DWI data"'
        )
        return
    b = bb.mean()
    S = dwi_node.GetImageData().ToArray()
    u = dwi_node.GetDiffusionGradients().ToArray()
    i2r = vtk2mat(dwi_node.GetIJKToRASMatrix, slicer)
    r2i = vtk2mat(dwi_node.GetRASToIJKMatrix, slicer)
    mf = vtk2mat(dwi_node.GetMeasurementFrameMatrix, slicer)
    voxel = np.mat(dwi_node.GetSpacing()).reshape(3, 1)
    voxel = voxel[::-1]  # HACK Numpy has [z y x]

    # generalized loading...
    R = r2i[0:3, 0:3] / voxel.T  # normalize each column
    M = mf[0:3, 0:3]

    # transform gradients
    u = dwi_node.GetDiffusionGradients().ToArray()
    u = u * (np.linalg.inv(R) * M).T
    u = u / np.sqrt(np.power(u, 2).sum(1))
    u = np.vstack((u, -u))  # duplicate signal

    param['voxel'] = voxel
    mask = mask_node.GetImageData().ToArray().astype('uint16')

    # pull all seeds
    seeds_ = seeds_node.GetImageData().ToArray()
    seeds = np.zeros(seeds_.shape, dtype='bool')
    for lbl in labels:
        seeds |= (seeds_ == lbl)
    seeds = zip(*seeds.nonzero())

    # ensure seeds
    if len(seeds) == 0:
        import Slicer
        Slicer.tk.eval(
            'tk_messageBox -message "No seeds found for this label"')
        return

    # double check branching
    if 0 < theta_max and theta_max < 5:
        import Slicer
        Slicer.tk.eval(
            'tk_messageBox -message "Nonzero branching angle must be greater than 5 degrees"'
        )
        return
    is_branching = is_2t and param['theta_max'] < 1

    # tractography...
    ff1 = init(S, seeds, u, b, param, is_2t)
    ff2, ff_fa, ff_st, ff_co = [], [], [], []
    t1 = time.time()
    for i in xrange(0, len(ff1)):
        print '[%3.0f%%] (%7d - %7d)' % (100.0 * i / len(ff1), i, len(ff1))
        ff1[i], next, extra = follow(S, u, b, mask, ff1[i], param,
                                     is_branching)
        ff2.extend(next)
        # store extras
        if record_fa: ff_fa.append(extra[0])
        if record_state: ff_st.append(extra[1])
        if record_cov: ff_co.append(extra[2])

    t2 = time.time()
    print 'Time: ', t2 - t1, 'sec'

    if is_branching:
        for i in xrange(0, len(ff2)):
            print '[%3.0f%%] (%7d - %7d)' % (100.0 * i / len(ff2), i, len(ff2))
            f, _ = follow(S, u, b, mask, ff2[i], param, False)
            ff1.append(f)
        print 'Time: ', time.time() - t2, 'sec'

    # build polydata
    ss_x = slicer.vtkPoints()
    lines = slicer.vtkCellArray()
    if record_fa:
        ss_fa = slicer.vtkFloatArray()
        ss_fa.SetNumberOfComponents(1)
        ss_fa.SetName('FA')
    if record_state:
        ss_st = slicer.vtkFloatArray()
        ss_st.SetNumberOfComponents(state_dim)
        ss_st.SetName('state')
    if record_cov:
        ss_co = slicer.vtkFloatArray()
        ss_co.SetNumberOfComponents(state_dim**2)
        ss_co.SetName('covariance')
    cell_id = 0

    for i in xrange(0, len(ff1)):
        f = ff1[i]
        lines.InsertNextCell(len(f))
        if record_fa: f_fa = ff_fa[i]
        if record_state: f_st = ff_st[i]
        if record_cov: f_co = ff_co[i]
        for j in xrange(0, len(f)):
            lines.InsertCellPoint(cell_id)
            cell_id += 1
            x = f[j]
            x = x[::-1]  # HACK
            x_ = np.array(transform(i2r, x)).ravel()  # HACK
            ss_x.InsertNextPoint(x_[0], x_[1], x_[2])
            if record_fa:
                ss_fa.InsertNextValue(255 * f_fa[j])  # FIXME numpy type
            if record_state: ss_st.InsertNextValue(f_fa[j])  # FIXME tuples?
            if record_cov: ss_co.InsertNextValue(f_fa[j])  # FIXME tuples?

    # setup output fibers
    dnode = ff_node.GetDisplayNode()
    if not dnode:
        dnode = slicer.vtkMRMLModelDisplayNode()
        ff_node.GetScene().AddNodeNoNotify(dnode)
        ff_node.SetAndObserveDisplayNodeID(dnode.GetID())
    pd = ff_node.GetPolyData()
    if not pd:
        pd = slicer.vtkPolyData()  # create if necessary
        ff_node.SetAndObservePolyData(pd)
    pd.SetPoints(ss_x)
    if record_fa: pd.GetPointData().SetScalars(ss_fa)
    pd.SetLines(lines)
    pd.Update()
    ff_node.Modified()

    asdf  # HACK flush stdio
    def Import(self):
        outModel = self._importModelSelector.GetSelected()
        outputFileName = self._loadButton.GetFileName()

        if outModel and outputFileName:

            self._helper.debug("Start import..")

            points = slicer.vtkPoints()
            conn = slicer.vtkCellArray()
            polyData = slicer.vtkPolyData()

            f=open(outputFileName)
            lines = f.readlines()
            i = 0
            lastId = None
            for line in lines:

                if self._importHeaders.GetSelectedState()==1 and i==0:
                    self._helper.debug("Ignore first line..")
                else:
                    # now parse the rest
                    splitted = line.split()

                    x = float(splitted[0])
                    y = float(splitted[1])
                    z = float(splitted[2])

                    if self._importNifti.GetSelectedState()==1:
                        x = x*(-1)
                        y = y*(-1)

                    #self._helper.debug("Found point: "+str(x)+","+str(y)+","+str(z))

                    id = points.InsertNextPoint(x,y,z)
                    #self._helper.debug(id)

                    if lastId:
                        curLine = slicer.vtkLine()
                        curLine.GetPointIds().SetId(0,lastId)
                        curLine.GetPointIds().SetId(1,id)

                        conn.InsertNextCell(curLine)
                        #conn.InsertCellPoint(id)

                    lastId = id

                i = i+1

            f.close()

            result = slicer.vtkPolyData()
            result.SetPoints(points)
            result.SetLines(conn)
            result.Update()

            self._helper.debug(result)
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(0.8, 0, 0)
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(1.0)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())
Exemple #5
0
    def Import(self):
        outModel = self._importModelSelector.GetSelected()
        outputFileName = self._loadButton.GetFileName()

        if outModel and outputFileName:

            self._helper.debug("Start import..")

            points = slicer.vtkPoints()
            conn = slicer.vtkCellArray()
            polyData = slicer.vtkPolyData()

            f = open(outputFileName)
            lines = f.readlines()
            i = 0
            lastId = None
            for line in lines:

                if self._importHeaders.GetSelectedState() == 1 and i == 0:
                    self._helper.debug("Ignore first line..")
                else:
                    # now parse the rest
                    splitted = line.split()

                    x = float(splitted[0])
                    y = float(splitted[1])
                    z = float(splitted[2])

                    if self._importNifti.GetSelectedState() == 1:
                        x = x * (-1)
                        y = y * (-1)

                    #self._helper.debug("Found point: "+str(x)+","+str(y)+","+str(z))

                    id = points.InsertNextPoint(x, y, z)
                    #self._helper.debug(id)

                    if lastId:
                        curLine = slicer.vtkLine()
                        curLine.GetPointIds().SetId(0, lastId)
                        curLine.GetPointIds().SetId(1, id)

                        conn.InsertNextCell(curLine)
                        #conn.InsertCellPoint(id)

                    lastId = id

                i = i + 1

            f.close()

            result = slicer.vtkPolyData()
            result.SetPoints(points)
            result.SetLines(conn)
            result.Update()

            self._helper.debug(result)
            outModel.SetAndObservePolyData(result)
            outModel.SetModifiedSinceRead(1)
            displayNode = outModel.GetModelDisplayNode()
            if not displayNode:
                displayNode = slicer.vtkMRMLModelDisplayNode()
            displayNode.SetPolyData(outModel.GetPolyData())
            displayNode.SetColor(0.8, 0, 0)
            displayNode.SetVisibility(1)
            displayNode.SetOpacity(1.0)
            self.GetLogic().GetMRMLScene().AddNode(displayNode)

            outModel.SetAndObserveDisplayNodeID(displayNode.GetID())
def Execute(dwi_node, seeds_node, mask_node, ff_node, \
            record_fa = False, record_state = False, record_cov = False, \
            model="two-tensor", FA_min=.15, GA_min=.10,
            seeds=1, labels=[1],
            Qm=.0030, Ql=100, Rs=.015, theta_max=45):
    for i in xrange(10) : print ''

    is_2t = (model == "two-tensor")

    print 'HACK hardcode 2T'; is_2t = True
    follow = iff(is_2t, follow2t, follow1t)

    state_dim = iff(is_2t, 10, 5)  # dimension of state space

    theta_min = 5  # angle which triggers branch
    param = dict({'FA_min': FA_min, # fractional anisotropy stopping threshold
                  'GA_min': GA_min, # generalized anisotropy stopping threshold
                  'dt': .2,     # forward Euler step size (path integration)
                  'max_len': 250, # stop if fiber gets this long
                  'min_radius': .87,  # stop if fiber curves this much
                  'seeds' : seeds,  # number of seeds in each voxel
                  'theta_min': np.cos(theta_min * np.pi/180),  # angle which triggers branch
                  'theta_max': np.cos(theta_max * np.pi/180),  # angle which triggers branch
                  'min_radius': .87,  # stop if fiber curves this much
                  'record_fa' : record_fa,
                  'record_st' : record_state,
                  'record_co' : record_cov,
                  # Kalman filter parameters
                  'Qm': Qm, # injected angular noise
                  'Ql': Ql, # injected eigenvalue noise
                  'Rs': Rs, # dependent on latent noise in your data
                  'P0': 0.01 * np.eye(state_dim)}) # initial covariance

    from Slicer import slicer

#     foo = slicer.vtkFloatArray()
#     foo.SetNumberOfComponents(1)
#     foo.SetName('foo')

#     foo.InsertNextValue(234)          # Success
#     foo.InsertNextValue(23.4)         # Success
#     foo.InsertNextValue(255 * np.random.rand())       # Success
#     foo.InsertNextValue(np.empty(1,dtype='float32'))  # FAIL
#     foo.InsertNextValue(np.empty(1,dtype='float64'))  # FAIL
#     asdf

    scene = slicer.MRMLScene
    dwi_node = scene.GetNodeByID(dwi_node)
    seeds_node = scene.GetNodeByID(seeds_node)
    mask_node = scene.GetNodeByID(mask_node)
    ff_node = scene.GetNodeByID(ff_node)

    # ensure normalized signal
    bb = dwi_node.GetBValues().ToArray()
    if np.any(bb.sum(1) == 0):
        import Slicer
        Slicer.tk.eval('tk_messageBox -message "Use the \'Normalize Signal\' module to prepare the DWI data"')
        return
    b = bb.mean()
    S = dwi_node.GetImageData().ToArray()
    u = dwi_node.GetDiffusionGradients().ToArray()
    i2r = vtk2mat(dwi_node.GetIJKToRASMatrix,         slicer)
    r2i = vtk2mat(dwi_node.GetRASToIJKMatrix,         slicer)
    mf  = vtk2mat(dwi_node.GetMeasurementFrameMatrix, slicer)
    voxel = np.mat(dwi_node.GetSpacing()).reshape(3,1)
    voxel = voxel[::-1]  # HACK Numpy has [z y x]

    # generalized loading...
    R = r2i[0:3,0:3] / voxel.T  # normalize each column
    M = mf[0:3,0:3]

    # transform gradients
    u = dwi_node.GetDiffusionGradients().ToArray()
    u = u * (np.linalg.inv(R) * M).T
    u = u / np.sqrt(np.power(u,2).sum(1))
    u = np.vstack((u,-u)) # duplicate signal

    param['voxel'] = voxel
    mask  = mask_node.GetImageData().ToArray().astype('uint16')

    # pull all seeds
    seeds_ = seeds_node.GetImageData().ToArray()
    seeds = np.zeros(seeds_.shape, dtype='bool')
    for lbl in labels:
        seeds |= (seeds_ == lbl)
    seeds = zip(*seeds.nonzero())

    # ensure seeds
    if len(seeds) == 0:
        import Slicer
        Slicer.tk.eval('tk_messageBox -message "No seeds found for this label"')
        return

    # double check branching
    if 0 < theta_max and theta_max < 5:
        import Slicer
        Slicer.tk.eval('tk_messageBox -message "Nonzero branching angle must be greater than 5 degrees"')
        return
    is_branching = is_2t and param['theta_max'] < 1

    # tractography...
    ff1 = init(S, seeds, u, b, param, is_2t)
    ff2,ff_fa,ff_st,ff_co = [],[],[],[]
    t1 = time.time()
    for i in xrange(0,len(ff1)):
        print '[%3.0f%%] (%7d - %7d)' % (100.0*i/len(ff1), i, len(ff1))
        ff1[i],next,extra = follow(S,u,b,mask,ff1[i],param,is_branching)
        ff2.extend(next)
        # store extras
        if record_fa:    ff_fa.append(extra[0])
        if record_state: ff_st.append(extra[1])
        if record_cov:   ff_co.append(extra[2])

    t2 = time.time()
    print 'Time: ', t2 - t1, 'sec'

    if is_branching:
        for i in xrange(0,len(ff2)):
            print '[%3.0f%%] (%7d - %7d)' % (100.0*i/len(ff2), i, len(ff2))
            f,_ = follow(S,u,b,mask,ff2[i],param,False)
            ff1.append(f)
        print 'Time: ', time.time() - t2, 'sec'

    # build polydata
    ss_x = slicer.vtkPoints()
    lines = slicer.vtkCellArray()
    if record_fa:    ss_fa = slicer.vtkFloatArray(); ss_fa.SetNumberOfComponents(1);            ss_fa.SetName('FA');
    if record_state: ss_st = slicer.vtkFloatArray(); ss_st.SetNumberOfComponents(state_dim);    ss_st.SetName('state');
    if record_cov:   ss_co = slicer.vtkFloatArray(); ss_co.SetNumberOfComponents(state_dim**2); ss_co.SetName('covariance');
    cell_id = 0

    for i in xrange(0,len(ff1)):
        f = ff1[i]
        lines.InsertNextCell(len(f))
        if record_fa:    f_fa = ff_fa[i]
        if record_state: f_st = ff_st[i]
        if record_cov:   f_co = ff_co[i]
        for j in xrange(0,len(f)):
            lines.InsertCellPoint(cell_id)
            cell_id += 1
            x = f[j]
            x = x[::-1] # HACK
            x_ = np.array(transform(i2r, x)).ravel() # HACK
            ss_x.InsertNextPoint(x_[0],x_[1],x_[2])
            if record_fa    : ss_fa.InsertNextValue(255 * f_fa[j]) # FIXME numpy type
            if record_state : ss_st.InsertNextValue(f_fa[j])  # FIXME tuples?
            if record_cov   : ss_co.InsertNextValue(f_fa[j])  # FIXME tuples?
 

    # setup output fibers
    dnode = ff_node.GetDisplayNode()
    if not dnode:
        dnode = slicer.vtkMRMLModelDisplayNode()
        ff_node.GetScene().AddNodeNoNotify(dnode)
        ff_node.SetAndObserveDisplayNodeID(dnode.GetID())
    pd = ff_node.GetPolyData()
    if not pd:
        pd = slicer.vtkPolyData() # create if necessary
        ff_node.SetAndObservePolyData(pd)
    pd.SetPoints(ss_x)
    if record_fa : pd.GetPointData().SetScalars(ss_fa)
    pd.SetLines(lines)
    pd.Update()
    ff_node.Modified()

    asdf # HACK flush stdio