Example #1
0
   def __init__(self, conn_sock, client_address, server):
        self.server             = server
        self.client_address     = client_address
        self.buffer             = ""

        self.is_writable        = False
        
        self.init               = False

        self.data               = ""            # data deals with string based data (non numpy data)
        self.ntype              = ""            # ntype deals with numpy stringified arrays sent remotely - store type (not data)
        self.nflag              = False         # nflag related to numpy data recv (buffer not enough large to get it in one turn) - set a reset point for data

        self.isPartial          = False
        self.nVols              = 0
        self.ldata              = ""
        self.pvol               = []

        self.isarray            = False
        self.result             = False

        self.issent             = False
        
        self.params             = nrrd.nrrd()
        self.nimage             = nrrd.nrrd()
        self.roiA               = nrrd.nrrd()
        self.roiB               = nrrd.nrrd()
        self.wm                 = nrrd.nrrd()
        self.ten                = nrrd.nrrd()

        self.res                = numpy.empty(0)

        asyncore.dispatcher.__init__(self, conn_sock)
        logger.debug("created handler; waiting for loop")
Example #2
0
    def __init__(self, conn_sock, client_address, server):
        self.server = server
        self.client_address = client_address
        self.buffer = ""

        self.is_writable = False

        self.init = False

        self.data = ""  # data deals with string based data (non numpy data)
        self.ntype = ""  # ntype deals with numpy stringified arrays sent remotely - store type (not data)
        self.nflag = False  # nflag related to numpy data recv (buffer not enough large to get it in one turn) - set a reset point for data

        self.isPartial = False
        self.nVols = 0
        self.ldata = ""
        self.pvol = []

        self.isarray = False
        self.result = False

        self.issent = False

        self.params = nrrd.nrrd()
        self.nimage = nrrd.nrrd()
        self.roiA = nrrd.nrrd()
        self.roiB = nrrd.nrrd()
        self.wm = nrrd.nrrd()
        self.ten = nrrd.nrrd()

        self.res = numpy.empty(0)

        asyncore.dispatcher.__init__(self, conn_sock)
        logger.debug("created handler; waiting for loop")
Example #3
0
    def get(self, id):
        """get and return the image from slicer with the given id
        """
        # create a socket
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((self.host, self.port))
        s.send('get ' + str(id) + ' \n')  # send

        nimage = nrrd.nrrd()

        fp = s.makefile()
        line = string.strip(fp.readline())

        name = string.strip(fp.readline())
        nimage.set('name', name)
        name = string.split(name)

        scalar_type = string.strip(fp.readline())
        nimage.set('scalar_type', scalar_type)
        scalar_type = string.split(scalar_type)

        dimensions = string.strip(fp.readline())
        nimage.set('dimensions', dimensions)
        dimensions = string.split(dimensions)

        space_origin = string.strip(fp.readline())
        nimage.set('space_origin', space_origin)
        space_origin = string.split(space_origin)

        space_directions = string.strip(fp.readline())
        nimage.set('space_directions', space_directions)
        space_directions = string.split(space_directions)

        dtype = vtk_types[int(scalar_type[1])]
        size = numpy_sizes[dtype]
        size = size * int(dimensions[3]) * int(dimensions[2]) * int(
            dimensions[1])

        data = s.recv(size)
        while len(data) != size:
            data += s.recv(size)

        im = numpy.fromstring(data, dtype)
        im = im.reshape(int(dimensions[3]), int(dimensions[2]),
                        int(dimensions[1]))

        s.close()

        nimage.setImage(im)
        return nimage
Example #4
0
    def get(self, id):
        """get and return the image from slicer with the given id
        """
        # create a socket
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect( (self.host, self.port) )
        s.send('get ' + str(id) + ' \n') # send 

        nimage = nrrd.nrrd()

        fp = s.makefile();
        line = string.strip(fp.readline())

        name = string.strip(fp.readline())
        nimage.set('name', name)
        name = string.split(name)

        scalar_type = string.strip(fp.readline())
        nimage.set('scalar_type', scalar_type)
        scalar_type = string.split(scalar_type)

        dimensions = string.strip(fp.readline())
        nimage.set('dimensions', dimensions)
        dimensions = string.split(dimensions)

        space_origin = string.strip(fp.readline())
        nimage.set('space_origin', space_origin)
        space_origin = string.split(space_origin)

        space_directions = string.strip(fp.readline())
        nimage.set('space_directions', space_directions)
        space_directions = string.split(space_directions)

        dtype = vtk_types [ int(scalar_type[1]) ]
        size = numpy_sizes [ dtype ]
        size = size * int(dimensions[3]) * int(dimensions[2]) * int(dimensions[1])

        data = s.recv(size)
        while len(data) != size:
          data += s.recv(size)

        im = numpy.fromstring (data, dtype)
        im = im.reshape( int(dimensions[3]), int(dimensions[2]), int(dimensions[1]) )

        s.close()

        nimage.setImage(im)
        return nimage
Example #5
0
    def handle_read(self):
        # handle incomings
        if self.nimage.hasKey('size') and not self.result:
            self.isarray = True
            size = self.nimage.get('size')
            dims = self.nimage.get('dimensions')
            nvols = int(dims[3])

            sizePerVol = size / nvols

            if not self.nflag:
                self.data = ""
                self.nflag = True

            self.ldata += self.recv(sizePerVol)

            if len(self.ldata) == sizePerVol:
                self.isPartial = True
                self.data += self.ldata
                self.pvol.append(self.ldata)
                self.nVols += 1
                self.ldata = ""

            # get DWI and run pipeline
            if self.nVols == nvols:
                logger.debug("volume acquired!")

                self.set_data(self.data)

                self.pvol = []
                self.isPartial = False
                self.nVols = 0

                self.data = ""
                logger.info("pipeline launchned")
                self.res = self.pipeline(self.nimage.getImage())
                logger.debug(
                    "result shape : %s:%s:%s" %
                    (self.res.shape[0], self.res.shape[1], self.res.shape[2]))
                logger.debug("result type : %s" % self.res.dtype)
                logger.info("pipeline completed")
                self.data = 'FACK'
                self.result = True
                logger.debug("ready for sending!")
        else:
            if not self.result:
                self.isarray = False
                self.data = self.recv(SIZE)

                if not self.init:  # first get parameters of the pipeline
                    self.set_params(self.data)
                elif self.data:  # second get data associated to the vector image
                    self.set_data(self.data)
                else:
                    logger.error("command unknown")

            else:  # special case for returning to client (Slicer) - currently SlicerDaemon used
                if not self.issent:
                    self.data = self.recv(SIZE)
                    cmd = string.strip(self.data)
                    cmd = string.split(cmd)
                    if len(cmd) != 1:
                        logger.info("command awaited!")
                    else:
                        logger.info("command : %s" % cmd[0])
                        if cmd[0] == 'get':
                            logger.info("send back data!")
                            self.data = self.res.tostring()  # 'PACK'
                            self.issent = True
                        else:
                            logger.error("command unknown")
                else:
                    logger.info("closing!")
                    self.result = False

        # determine response
        if self.data and not self.isarray and not self.result:
            self.buffer += 'ACK'
            self.is_writable = True
            self.data = ""
        elif (self.data or self.ldata) and self.isarray and not self.result:
            logger.debug("acquiring array")
            if self.isPartial:
                self.buffer += 'ACK'
                self.is_writable = True
                self.isPartial = False
        elif self.data and self.result:
            self.buffer = self.data
            self.is_writable = True

            # reset
            if self.issent:
                self.data = ""  # set previously
                self.ntype = ""

                self.init = False

                self.isarray = False
                self.nflag = False

                self.params = nrrd.nrrd()
                self.nimage = nrrd.nrrd()
                self.roiA = nrrd.nrrd()
                self.roiB = nrrd.nrrd()
                self.wm = nrrd.nrrd()

                self.res = numpy.empty(0)

                self.issent = False
                logger.debug("data size : %s" % len(self.buffer))

            logger.info("ready to handle write!")

        else:
            logger.info("got null data")
def main (\
             inputSHost = 'localhost',\
             inputSPort = 18943,\

             inputPar0 = "",\
             inputVol0 = "",\
             inputVol1 = "",\
             inputVol2 = "",\
             inputVol3 = ""
             ):

    
  if not inputPar0:
      return  

  if not inputVol0:
      return

  host = inputSHost
  port = inputSPort

  parName = inputPar0


  dwiName = inputVol0


  roiAName = ""
  roiBName = ""
  wmName = ""

  if inputVol1:
      roiAName = inputVol1

  if inputVol2:
      roiBName = inputVol2

  if inputVol3: 
      wmName = inputVol3

  #if inputVol4:
  #    ten = scene.GetNodeByID(inputVol4)
  #    tenName = ten.GetName()
  
  
  paramsN = nrrd.nrrd()
  dwiN = nrrd.nrrd()
  roiAN = nrrd.nrrd()
  roiBN = nrrd.nrrd()
  wmN = nrrd.nrrd()

  paramsN.set('location', os.getcwd())


  dwiN = recvVolume(dwiName, 'dwi')
  paramsN.set('dwi', dwiName)

  if roiAName:
     roiAN = recvVolume(roiAName, 'roi')
     paramsN.set('roiA', roiAName)

  if roiBName:
     roiBN = recvVolume(roiBName, 'roi')
     paramsN.set('roiB', roiBName)

  if wmName:
     wmN = recvVolume(wmName, 'wm')
     paramsN.set('wm', wmName)

  #if tenName:
  #   s.send('tensor ' + str(tenName) + '\n')
  #   ack = s.recv(SIZE)

  print "Params loaded from : %s" % str(parName)
  params = numpy.fromfile(parName, 'float')
  
  paramsN.set('pipeline', 'STOCHASTIC')
  print "Pipeline?? : %s" % str(paramsN.get('pipeline'))

  # smoothing
  paramsN.set('smoothEnabled', int(params[0]))


  stdD = numpy.array([params[1], params[2], params[3]], 'float')
  paramsN.set('stdDev', stdD)

  # brain
  paramsN.set('wmEnabled', int(params[4]))

  paramsN.set('infWMThres', params[5])

  paramsN.set('supWMThres', params[6])

  # tensor
  paramsN.set('tensEnabled', int(params[7]))

  bLine = 0
  paramsN.set('bLine', params[8])

  paramsN.set('faEnabled', int(params[9]))

  paramsN.set('traceEnabled', int(params[10]))

  paramsN.set('modeEnabled', int(params[11]))

  # stochastic tracto
  paramsN.set('stEnabled', int(params[12]))

  paramsN.set('totalTracts', params[13])

  paramsN.set('maxLength', params[14])

  paramsN.set('stepSize', params[15])

  paramsN.set('spaceEnabled', int(params[16]))
 
  paramsN.set('stopEnabled', int(params[17]))


  paramsN.set('fa', params[18])

  # connectivity
  paramsN.set('cmEnabled', int(params[19]))

  probMode = int(params[20])
  if probMode == 0:
   probMode = 'binary'
  elif probMode == 1:
   probMode = 'cumulative'
  elif probMode == 2:
   probMode = 'weighted'

  paramsN.set('probMode', probMode)

  paramsN.set('lengthEnabled', int(params[21]))


  lengthClass = int(params[22])
  if lengthClass == 0:
   lengthClass = 'dThird'
  elif lengthClass == 1:
   lengthClass = 'mThird'
  elif lengthClass == 2:
   lengthClass = 'uThird'
  
  paramsN.set('lengthClass', lengthClass)

 
  pipeline(host, port, paramsN, dwiN, roiAN, roiBN, wmN)

  inputPar0 = ""
  inputVol0 = ""
  inputVol1 = ""
  inputVol2 = ""
  inputVol3 = ""


  return
def recvVolume(volName, type, isDti=False):

  volN = nrrd.nrrd()

  print "Load data from : %s" % str(volName)

  # load auxiliary files
  rootName = os.path.join(os.path.dirname(volName), os.path.basename(volName).split('.' + os.path.basename(volName).split('.')[-1])[0])
  
  # take dimensions of the image
  print "Load dims from : %s" %  str(rootName + '.dims')
  dims = numpy.fromfile(rootName + '.dims', 'uint16')

  print "Dims of data : %s" % str(dims) 

  if len(dims) == 5:
    dtype = vtk_types [ int(dims[4]) ]
    data = numpy.fromfile(volName, dtype) 
    data = data.reshape(dims[0], dims[1], dims[2], dims[3])

  elif len(dims) == 3:
    dtype = vtk_types [ int(dims[2]) ]
    data = numpy.fromfile(volName, dtype) 
    data = data.reshape(dims[0], dims[1])

  elif len(dims) == 4:
    dtype = vtk_types [ int(dims[3]) ]
    data = numpy.fromfile(volName, dtype) 
    data = data.reshape(dims[0], dims[1], dims[2])
    
  # should return if dims is different

  shape = data.shape
  dtype = data.dtype

  print "Data shape : %s" % str(shape)
  print "Data type : %s" % str(dtype)
  


  # set data into the nrrd object
  volN.setImage(data)

  volN.set('name', volName)
  volN.set('fullname', volName)

  volN.set('type', dtype)
  volN.set('dimensions', shape)

  org = numpy.fromfile(rootName + '.org', 'float')
  volN.set('origin', org)

  spa = numpy.fromfile(rootName + '.spa', 'float')
  volN.set('spacing', spa)

  I2R = numpy.fromfile(rootName + '.ijk', 'float')
  I2R = I2R.reshape(4,4)
  volN.set('ijk2ras', I2R)

  R2I = numpy.fromfile(rootName + '.ras', 'float')
  R2I = R2I.reshape(4,4)
  volN.set('ras2ijk', R2I)

  isDwi = False
  if len(shape)==4:
     isDwi = True

     I2RD = numpy.fromfile(rootName + '.ijkd', 'float')
     I2RD = I2RD.reshape(4,4)
     volN.set('ijk2rasd', I2RD)

     G = numpy.fromfile(rootName + '.grad', 'float')
     G = G.astype('float')
     volN.set('grads', G)

     b = numpy.fromfile(rootName + '.bval', 'float')
     b = b.astype('float')
     volN.set('bval', b)

     M2R = numpy.fromfile(rootName + '.mu', 'float')
     M2R = M2R.reshape(4,4)
     volN.set('mu', M2R)
 
  return volN 
Example #8
0
    def get(self, id):
        """get and return the image from slicer with the given id
        """
        # create a socket
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect( (self.host, self.port) )
        s.send('get ' + str(id) + ' \n') # send 

        nimage = nrrd.nrrd()

        fp = s.makefile();
        line = string.strip(fp.readline())

        name = string.strip(fp.readline())
        nimage.set('name', name)
        name = string.split(name)
        logger.debug( "Name : %s" % name)

        scalar_type = string.strip(fp.readline())
        nimage.set('scalar_type', scalar_type)
        scalar_type = string.split(scalar_type)
        logger.debug( "Type : %s" % scalar_type)

        dimensions = string.strip(fp.readline())
        nimage.set('dimensions', dimensions)
        dimensions = string.split(dimensions)

        if len(dimensions)==4:
            logger.debug( "Dimensions : %s:%s:%s" % (dimensions[1], dimensions[2], dimensions[3]))

        if len (dimensions)==5:
            logger.debug( "Dimensions : %s:%s:%s:%s" % (dimensions[1], dimensions[2], dimensions[3], dimensions[4]))

        space_origin = string.strip(fp.readline())
        nimage.set('space_origin', space_origin)
        space_origin = string.split(space_origin)

        space_directions = string.strip(fp.readline())
        nimage.set('space_directions', space_directions)
        space_directions = string.split(space_directions)

        kinds = string.strip(fp.readline())
        nimage.set('kinds', kinds)
        kinds = string.split(kinds)

        isDti = False
        if kinds[1] =='3D-masked-symmetric-matrix':
            mu = string.strip(fp.readline())
            nimage.set('measurement_frame', mu)
            mu = string.split(mu)
            isDti = True

        isDwi = False
        if kinds[1] =='vector':
            mu = string.strip(fp.readline())
            nimage.set('measurement_frame', mu)
            mu = string.split(mu)
            isDwi = True

        dtype = vtk_types [ int(scalar_type[1]) ]
        size = numpy_sizes [ dtype ]
        if isDti:
           size = size * int(dimensions[1]) * int(dimensions[4]) * int(dimensions[3]) * int(dimensions[2])
        elif isDwi:
           size = size * int(dimensions[4]) * int(dimensions[3]) * int(dimensions[2]) * int(dimensions[1])
        else:
           size = size * int(dimensions[3]) * int(dimensions[2]) * int(dimensions[1])

        data = s.recv(size)
        while len(data) != size:
          data += s.recv(size)

        im = numpy.fromstring (data, dtype)
        if isDti:
           im = im.reshape( int(dimensions[1]), int(dimensions[4]) * int(dimensions[3]) * int(dimensions[2]) )
        elif isDwi:
           im = im.reshape( int(dimensions[4]), int(dimensions[3]), int(dimensions[2]) , int(dimensions[1]) )
        else:
           im = im.reshape( int(dimensions[3]), int(dimensions[2]), int(dimensions[1]) )

        s.close()

        nimage.setImage(im)
        return nimage
def main (\
             inputPar0 = "",\
             inputVol0 = "",\
             inputVol1 = "",\
             inputVol2 = "",\
             inputVol3 = ""
             ):

    
  if not inputPar0:
      return  

  if not inputVol0:
      return

  parName = inputPar0


  dwiName = inputVol0


  roiAName = ""
  roiBName = ""
  wmName = ""

  if inputVol1:
      roiAName = inputVol1

  if inputVol2:
      roiBName = inputVol2

  if inputVol3: 
      wmName = inputVol3

  #if inputVol4:
  #    ten = scene.GetNodeByID(inputVol4)
  #    tenName = ten.GetName()
  
  paramsN = nrrd.nrrd()
  dwiN = nrrd.nrrd()
  roiAN = nrrd.nrrd()
  roiBN = nrrd.nrrd()
  wmN = nrrd.nrrd()

  paramsN.set('location', os.getcwd())

  dwiN = recvVolume(dwiName, 'dwi')
  paramsN.set('dwi', dwiName)

  if roiAName:
     roiAN = recvVolume(roiAName, 'roi')
     paramsN.set('roiA', roiAName)

  if roiBName:
     roiBN = recvVolume(roiBName, 'roi')
     paramsN.set('roiB', roiBName)

  if wmName:
     wmN = recvVolume(wmName, 'wm')
     paramsN.set('wm', wmName)

  #if tenName:
  #   s.send('tensor ' + str(tenName) + '\n')
  #   ack = s.recv(SIZE)

  print "Params loaded from : %s" % str(parName)
  params = numpy.fromfile(parName, 'float')
  
  paramsN.set('pipeline', 'STOCHASTIC')
  print "Pipeline?? : %s" % str(paramsN.get('pipeline'))

  # smoothing
  paramsN.set('smoothEnabled', int(params[0]))


  stdD = numpy.array([params[1], params[2], params[3]], 'float')
  paramsN.set('stdDev', stdD)

  # brain
  paramsN.set('wmEnabled', int(params[4]))

  paramsN.set('infWMThres', params[5])

  paramsN.set('supWMThres', params[6])

  # tensor
  paramsN.set('tensEnabled', int(params[7]))

  bLine = 0
  paramsN.set('bLine', params[8])

  paramsN.set('faEnabled', int(params[9]))

  paramsN.set('traceEnabled', int(params[10]))

  paramsN.set('modeEnabled', int(params[11]))

  # stochastic tracto
  paramsN.set('stEnabled', int(params[12]))

  paramsN.set('totalTracts', params[13])

  paramsN.set('maxLength', params[14])

  paramsN.set('stepSize', params[15])

  paramsN.set('spaceEnabled', int(params[16]))
 
  paramsN.set('stopEnabled', int(params[17]))


  paramsN.set('fa', params[18])

  # connectivity
  paramsN.set('cmEnabled', int(params[19]))

  probMode = int(params[20])
  if probMode == 0:
   probMode = 'binary'
  elif probMode == 1:
   probMode = 'cumulative'
  elif probMode == 2:
   probMode = 'weighted'

  paramsN.set('probMode', probMode)

  paramsN.set('lengthEnabled', int(params[21]))


  lengthClass = int(params[22])
  if lengthClass == 0:
   lengthClass = 'dThird'
  elif lengthClass == 1:
   lengthClass = 'mThird'
  elif lengthClass == 2:
   lengthClass = 'uThird'
  
  paramsN.set('lengthClass', lengthClass)

 
  pipeline(paramsN, dwiN, roiAN, roiBN, wmN)

  inputPar0 = ""
  inputVol0 = ""
  inputVol1 = ""
  inputVol2 = ""
  inputVol3 = ""


  return
def recvVolume(volName, type, isDti=False):

  volN = nrrd.nrrd()

  print "Load data from : %s" % str(volName)

  # load auxiliary files
  rootName = os.path.join(os.path.dirname(volName), os.path.basename(volName).split('.' + os.path.basename(volName).split('.')[-1])[0])
  
  # take dimensions of the image
  print "Load dims from : %s" %  str(rootName + '.dims')
  dims = numpy.fromfile(rootName + '.dims', 'uint16')

  print "Dims of data : %s" % str(dims) 

  if len(dims) == 5:
    dtype = vtk_types [ int(dims[4]) ]
    data = numpy.fromfile(volName, dtype) 
    data = data.reshape(dims[0], dims[1], dims[2], dims[3])

  elif len(dims) == 3:
    dtype = vtk_types [ int(dims[2]) ]
    data = numpy.fromfile(volName, dtype) 
    data = data.reshape(dims[0], dims[1])

  elif len(dims) == 4:
    dtype = vtk_types [ int(dims[3]) ]
    data = numpy.fromfile(volName, dtype) 
    data = data.reshape(dims[0], dims[1], dims[2])
    
  # should return if dims is different

  shape = data.shape
  dtype = data.dtype

  print "Data shape : %s" % str(shape)
  print "Data type : %s" % str(dtype)
  

  # set data into the nrrd object
  volN.setImage(data)

  volN.set('name', volName)
  volN.set('fullname', volName)

  volN.set('type', dtype)
  volN.set('dimensions', shape)

  org = numpy.fromfile(rootName + '.org', 'float')
  volN.set('origin', org)

  spa = numpy.fromfile(rootName + '.spa', 'float')
  volN.set('spacing', spa)

  I2R = numpy.fromfile(rootName + '.ijk', 'float')
  I2R = I2R.reshape(4,4)
  volN.set('ijk2ras', I2R)


  R2I = numpy.fromfile(rootName + '.ras', 'float')
  R2I = R2I.reshape(4,4)
  volN.set('ras2ijk', R2I)


  isDwi = False
  if len(shape)==4:
     isDwi = True

     I2RD = numpy.fromfile(rootName + '.ijkd', 'float')
     I2RD = I2RD.reshape(4,4)
     volN.set('ijk2rasd', I2RD)

     G = numpy.fromfile(rootName + '.grad', 'float')
     G = G.astype('float')
     volN.set('grads', G)

     b = numpy.fromfile(rootName + '.bval', 'float')
     b = b.astype('float')
     volN.set('bval', b)

     M2R = numpy.fromfile(rootName + '.mu', 'float')
     M2R = M2R.reshape(4,4)
     volN.set('mu', M2R)
 
  return volN 
Example #11
0
    def get(self, id):
        """get and return the image from slicer with the given id
        """
        # create a socket
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((self.host, self.port))
        s.send('get ' + str(id) + ' \n')  # send

        nimage = nrrd.nrrd()

        fp = s.makefile()
        line = string.strip(fp.readline())

        name = string.strip(fp.readline())
        nimage.set('name', name)
        name = string.split(name)
        logger.debug("Name : %s" % name)

        scalar_type = string.strip(fp.readline())
        nimage.set('scalar_type', scalar_type)
        scalar_type = string.split(scalar_type)
        logger.debug("Type : %s" % scalar_type)

        dimensions = string.strip(fp.readline())
        nimage.set('dimensions', dimensions)
        dimensions = string.split(dimensions)

        if len(dimensions) == 4:
            logger.debug("Dimensions : %s:%s:%s" %
                         (dimensions[1], dimensions[2], dimensions[3]))

        if len(dimensions) == 5:
            logger.debug(
                "Dimensions : %s:%s:%s:%s" %
                (dimensions[1], dimensions[2], dimensions[3], dimensions[4]))

        space_origin = string.strip(fp.readline())
        nimage.set('space_origin', space_origin)
        space_origin = string.split(space_origin)

        space_directions = string.strip(fp.readline())
        nimage.set('space_directions', space_directions)
        space_directions = string.split(space_directions)

        kinds = string.strip(fp.readline())
        nimage.set('kinds', kinds)
        kinds = string.split(kinds)

        isDti = False
        if kinds[1] == '3D-masked-symmetric-matrix':
            mu = string.strip(fp.readline())
            nimage.set('measurement_frame', mu)
            mu = string.split(mu)
            isDti = True

        isDwi = False
        if kinds[1] == 'vector':
            mu = string.strip(fp.readline())
            nimage.set('measurement_frame', mu)
            mu = string.split(mu)
            isDwi = True

        dtype = vtk_types[int(scalar_type[1])]
        size = numpy_sizes[dtype]
        if isDti:
            size = size * int(dimensions[1]) * int(dimensions[4]) * int(
                dimensions[3]) * int(dimensions[2])
        elif isDwi:
            size = size * int(dimensions[4]) * int(dimensions[3]) * int(
                dimensions[2]) * int(dimensions[1])
        else:
            size = size * int(dimensions[3]) * int(dimensions[2]) * int(
                dimensions[1])

        data = s.recv(size)
        while len(data) != size:
            data += s.recv(size)

        im = numpy.fromstring(data, dtype)
        if isDti:
            im = im.reshape(
                int(dimensions[1]),
                int(dimensions[4]) * int(dimensions[3]) * int(dimensions[2]))
        elif isDwi:
            im = im.reshape(int(dimensions[4]), int(dimensions[3]),
                            int(dimensions[2]), int(dimensions[1]))
        else:
            im = im.reshape(int(dimensions[3]), int(dimensions[2]),
                            int(dimensions[1]))

        s.close()

        nimage.setImage(im)
        return nimage
Example #12
0
   def handle_read(self):
        # handle incomings
        if  self.nimage.hasKey('size') and not self.result:
             self.isarray = True
             size = self.nimage.get('size')
             dims = self.nimage.get('dimensions')
             nvols = int(dims[3])

             sizePerVol = size/nvols

             if not self.nflag:
                  self.data = ""
                  self.nflag = True

             self.ldata += self.recv(sizePerVol)

             if len(self.ldata)==sizePerVol:
                  self.isPartial = True
                  self.data += self.ldata
                  self.pvol.append(self.ldata)
                  self.nVols +=1
                  self.ldata = ""

             # get DWI and run pipeline 
             if self.nVols==nvols:
                  logger.debug("volume acquired!")
  
                  self.set_data(self.data)

                  self.pvol = []
                  self.isPartial = False
                  self.nVols = 0

                  self.data = ""
                  logger.info("pipeline launchned")
                  self.res = self.pipeline(self.nimage.getImage())
                  logger.debug("result shape : %s:%s:%s" % (self.res.shape[0] , self.res.shape[1] , self.res.shape[2] ))
                  logger.debug("result type : %s" % self.res.dtype)
                  logger.info("pipeline completed")
                  self.data = 'FACK'
                  self.result = True
                  logger.debug("ready for sending!")
        else:
            if not self.result:
                  self.isarray = False
                  self.data = self.recv(SIZE)
      
                  if not self.init: # first get parameters of the pipeline
                     self.set_params(self.data)
                  elif self.data:  # second get data associated to the vector image
                     self.set_data(self.data)
                  else:
                     logger.error("command unknown")
        
            else: # special case for returning to client (Slicer) - currently SlicerDaemon used
                  if not self.issent:
                      self.data = self.recv(SIZE)
                      cmd = string.strip(self.data)
                      cmd = string.split(cmd)
                      if len(cmd)!=1:
                         logger.info("command awaited!")
                      else:
                         logger.info("command : %s" % cmd[0])
                         if cmd[0]=='get':
                             logger.info("send back data!")
                             self.data = self.res.tostring() # 'PACK'
                             self.issent = True
                         else:
                             logger.error("command unknown")
                  else:
                      logger.info("closing!")
                      self.result = False

        # determine response
        if self.data and not self.isarray and not self.result:
             self.buffer += 'ACK'
             self.is_writable = True
             self.data = ""
        elif (self.data or self.ldata) and self.isarray and not self.result:
             logger.debug("acquiring array")
             if self.isPartial:
                 self.buffer += 'ACK'
                 self.is_writable = True
                 self.isPartial = False
        elif self.data and self.result:
             self.buffer = self.data 
             self.is_writable = True

             # reset
             if self.issent:
                  self.data             = ""        # set previously
                  self.ntype            = ""

                  self.init             = False

                  self.isarray          = False
                  self.nflag            = False

                  self.params           = nrrd.nrrd()
                  self.nimage           = nrrd.nrrd()
                  self.roiA             = nrrd.nrrd()
                  self.roiB             = nrrd.nrrd()
                  self.wm               = nrrd.nrrd()

                  self.res              = numpy.empty(0)

                  self.issent           = False
                  logger.debug("data size : %s" %len(self.buffer))


             logger.info("ready to handle write!")

        else:
             logger.info("got null data")