示例#1
0
文件: t_calc.py 项目: FNNDSC/scripts
    def run(self, input, output, mode, verbose, jobs):

        if len(input) < 2:
            c.error("Please specify at least two *.trk files as input!")
            sys.exit(2)

        if os.path.exists(output):
            # abort if file already exists
            c.error("File " + str(output) + " already exists..")
            c.error("Aborting..")
            sys.exit(2)

        jobs = int(jobs)

        if jobs < 1 or jobs > 32:
            jobs = 1

        # load 'master'
        mTracks = io.loadTrk(input[0])

        # copy the tracks and the header from the 'master'
        c.info("Master is " + input[0])
        outputTracks = mTracks[0]
        c.info("Number of tracks: " + str(len(outputTracks)))
        header = mTracks[1]

        # remove the first input
        input.pop(0)

        if mode == "add":
            #
            # ADD
            #

            for i in input:
                iTracks = io.loadTrk(i)

                # add the tracks
                c.debug("Adding " + str(len(iTracks[0])) + " tracks from " + i + " to master..", verbose)
                outputTracks = TrackvisCalcLogic.add(outputTracks, iTracks[0])

            c.debug("Number of output tracks after final addition: " + str(len(outputTracks)), verbose)

        elif mode == "sub":
            #
            # SUB
            #

            c.debug("Using " + str(jobs) + " threads..", verbose)

            mergedOutputTracks = outputTracks[:]

            for i in input:
                iTracks = io.loadTrk(i)

                # subtract the tracks
                c.info("Subtracting " + i + " (" + str(len(iTracks[0])) + " tracks) from master..")

                #
                # THREADED COMPONENT
                #
                numberOfThreads = jobs
                c.info("Splitting master into " + str(jobs) + " pieces..")
                splittedOutputTracks = u.split_list(mergedOutputTracks, numberOfThreads)

                # list of threads
                t = [None] * numberOfThreads

                # list of alive flags
                a = [None] * numberOfThreads

                # list of tempFiles
                f = [None] * numberOfThreads

                for n in xrange(numberOfThreads):
                    # mark thread as alive
                    a[n] = True
                    # fire the thread and give it a filename based on the number
                    tmpFile = tempfile.mkstemp(".trk", "t_calc")[1]
                    f[n] = tmpFile
                    t[n] = Process(
                        target=TrackvisCalcLogic.sub,
                        args=(splittedOutputTracks[n][:], iTracks[0][:], tmpFile, verbose, "Thread-" + str(n + 1)),
                    )
                    c.info("Starting Thread-" + str(n + 1) + "...")
                    t[n].start()

                allDone = False

                while not allDone:

                    time.sleep(1)

                    for n in xrange(numberOfThreads):

                        a[n] = t[n].is_alive()

                    if not any(a):
                        # if no thread is alive
                        allDone = True

                #
                # END OF THREADED COMPONENT
                #
                c.info("All Threads done!")

                c.info("Merging output..")
                # now read all the created tempFiles and merge'em to one
                # first thread output is the master here
                tmpMaster = f[0]
                tMasterTracks = io.loadTrk(tmpMaster)
                for tmpFileNo in xrange(1, len(f)):
                    tTracks = io.loadTrk(f[tmpFileNo])

                    # add them
                    mergedOutputTracks = TrackvisCalcLogic.add(tMasterTracks[0], tTracks[0])

                c.info("Merging done!")

            # some stats
            c.info("Number of output tracks after final removal: " + str(len(mergedOutputTracks)))
            outputTracks = mergedOutputTracks

        # now save the outputTracks
        io.saveTrk(output, outputTracks, header)

        c.info("All done!")
示例#2
0
    def run(self, input, output, mode, verbose, jobs):

        if len(input) < 2:
            c.error('Please specify at least two *.trk files as input!')
            sys.exit(2)

        if os.path.exists(output):
            # abort if file already exists
            c.error('File ' + str(output) + ' already exists..')
            c.error('Aborting..')
            sys.exit(2)

        jobs = int(jobs)

        if jobs < 1 or jobs > 32:
            jobs = 1

        # load 'master'
        mTracks = io.loadTrk(input[0])

        # copy the tracks and the header from the 'master'
        c.info('Master is ' + input[0])
        outputTracks = mTracks[0]
        c.info('Number of tracks: ' + str(len(outputTracks)))
        header = mTracks[1]

        # remove the first input
        input.pop(0)

        if mode == 'add':
            #
            # ADD
            #

            for i in input:
                iTracks = io.loadTrk(i)

                # add the tracks
                c.debug(
                    'Adding ' + str(len(iTracks[0])) + ' tracks from ' + i +
                    ' to master..', verbose)
                outputTracks = TrackvisCalcLogic.add(outputTracks, iTracks[0])

            c.debug(
                'Number of output tracks after final addition: ' +
                str(len(outputTracks)), verbose)

        elif mode == 'sub':
            #
            # SUB
            #

            c.debug('Using ' + str(jobs) + ' threads..', verbose)

            mergedOutputTracks = outputTracks[:]

            for i in input:
                iTracks = io.loadTrk(i)

                # subtract the tracks
                c.info('Subtracting ' + i + ' (' + str(len(iTracks[0])) +
                       ' tracks) from master..')

                #
                # THREADED COMPONENT
                #
                numberOfThreads = jobs
                c.info('Splitting master into ' + str(jobs) + ' pieces..')
                splittedOutputTracks = u.split_list(mergedOutputTracks,
                                                    numberOfThreads)

                # list of threads
                t = [None] * numberOfThreads

                # list of alive flags
                a = [None] * numberOfThreads

                # list of tempFiles
                f = [None] * numberOfThreads

                for n in xrange(numberOfThreads):
                    # mark thread as alive
                    a[n] = True
                    # fire the thread and give it a filename based on the number
                    tmpFile = tempfile.mkstemp('.trk', 't_calc')[1]
                    f[n] = tmpFile
                    t[n] = Process(target=TrackvisCalcLogic.sub,
                                   args=(splittedOutputTracks[n][:],
                                         iTracks[0][:], tmpFile, verbose,
                                         'Thread-' + str(n + 1)))
                    c.info("Starting Thread-" + str(n + 1) + "...")
                    t[n].start()

                allDone = False

                while not allDone:

                    time.sleep(1)

                    for n in xrange(numberOfThreads):

                        a[n] = t[n].is_alive()

                    if not any(a):
                        # if no thread is alive
                        allDone = True

                #
                # END OF THREADED COMPONENT
                #
                c.info("All Threads done!")

                c.info("Merging output..")
                # now read all the created tempFiles and merge'em to one
                # first thread output is the master here
                tmpMaster = f[0]
                tMasterTracks = io.loadTrk(tmpMaster)
                for tmpFileNo in xrange(1, len(f)):
                    tTracks = io.loadTrk(f[tmpFileNo])

                    # add them
                    mergedOutputTracks = TrackvisCalcLogic.add(
                        tMasterTracks[0], tTracks[0])

                c.info("Merging done!")

            # some stats
            c.info('Number of output tracks after final removal: ' +
                   str(len(mergedOutputTracks)))
            outputTracks = mergedOutputTracks

        # now save the outputTracks
        io.saveTrk(output, outputTracks, header)

        c.info('All done!')
示例#3
0
  def run( self, input, output, matrix, jobs ):
    '''
    '''

    if os.path.exists( output ):
      # abort if file already exists
      c.error( 'File ' + str( output ) + ' already exists..' )
      c.error( 'Aborting..' )
      sys.exit( 2 )

    if not os.path.isfile( matrix ):
      # abort if the matrix does not exist
      c.error( 'Matrix-File ' + str( matrix ) + ' does not exist..' )
      c.error( 'Aborting..' )
      sys.exit( 2 )

    jobs = int( jobs )

    if jobs < 1 or  jobs > 32:
      jobs = 1

    # read
    c.info( 'Loading ' + input + '..' )

    t = io.loadTrk( input )
    tracks = t[0]
    header = t[1]
    #.. copy the current header
    newHeader = numpy.copy( header )

    # print old matrix in header
    # 
    # WARNING: this matrix is actually never used by TrackVis (see email from Ruopeng).
    # We still modify it to keep it in sync with the transformations which we apply point wise.
    #
    if hasattr( header, 'vox_to_ras' ):
      oldMatrix = header['vox_to_ras']
      c.info( 'Old transformation matrix:' )
      c.info( '    ' + str( oldMatrix[0] ) )
      c.info( '    ' + str( oldMatrix[1] ) )
      c.info( '    ' + str( oldMatrix[2] ) )
      c.info( '    ' + str( oldMatrix[3] ) )

    #
    # load our transformation Matrix
    #
    newMatrix = numpy.loadtxt( matrix, float, '#', ' ' )


    #
    # THREADED COMPONENT
    #
    numberOfThreads = jobs
    c.info( 'Splitting the input into ' + str( jobs ) + ' pieces..' )
    splittedOutputTracks = u.split_list( tracks, numberOfThreads )

    # list of threads
    t = [None] * numberOfThreads

    # list of alive flags
    a = [None] * numberOfThreads

    # list of tempFiles
    f = [None] * numberOfThreads

    for n in xrange( numberOfThreads ):
      # mark thread as alive
      a[n] = True
      # fire the thread and give it a filename based on the number
      tmpFile = tempfile.mkstemp( '.trk', 't_transform' )[1]
      f[n] = tmpFile
      t[n] = Process( target=TrackvisTransformLogic.transform, args=( splittedOutputTracks[n][:], newMatrix, tmpFile, False, 'Thread-' + str( n + 1 ) ) )
      c.info( "Starting Thread-" + str( n + 1 ) + "..." )
      t[n].start()

    allDone = False

    while not allDone:

      time.sleep( 1 )

      for n in xrange( numberOfThreads ):

        a[n] = t[n].is_alive()

      if not any( a ):
        # if no thread is alive
        allDone = True

    #
    # END OF THREADED COMPONENT
    #
    c.info( "All Threads done!" )

    c.info( "Merging output.." )
    # now read all the created tempFiles and merge'em to one
    # first thread output is the master here
    tmpMaster = f[0]
    tMasterTracks = io.loadTrk( tmpMaster )
    for tmpFileNo in xrange( 1, len( f ) ):
      tTracks = io.loadTrk( f[tmpFileNo] )

      # add them
      tracks = TrackvisCalcLogic.add( tMasterTracks[0], tTracks[0] )

    c.info( "Merging done!" )

    #
    # replace the matrix in the header with a transformed one even if it will never be used by TrackVis
    #
    if hasattr( header, 'vox_to_ras' ):
      result = numpy.dot( oldMatrix, newMatrix )
      c.info( 'New transformation matrix:' )
      c.info( '    ' + str( result[0] ) )
      c.info( '    ' + str( result[1] ) )
      c.info( '    ' + str( result[2] ) )
      c.info( '    ' + str( result[3] ) )
      newHeader['vox_to_ras'] = result

    # write
    c.info( 'Saving ' + output + '..' )
    io.saveTrk( output, tracks, newHeader )

    c.info( 'All done!' )
示例#4
0
文件: fyborg.py 项目: FNNDSC/fyborg
def fyborg( trkFile, outputTrkFile, actions, *args ):

  if not actions:
    c.error( "We gotta do something.." )
    return

  showDebug = 'debug' in args

  singleThread = 'singlethread' in args

  c.debug( "trkFile:" + str( trkFile ), showDebug )
  c.debug( "outputTrkFile:" + str( outputTrkFile ), showDebug )
  c.debug( "args:" + str( args ), showDebug )



  # load trk file
  s = io.loadTrk( trkFile )
  tracks = s[0]
  origHeader = s[1]
  tracksHeader = numpy.copy( s[1] )
  numberOfScalars = origHeader['n_scalars']
  scalars = origHeader['scalar_name'].tolist()
  numberOfTracks = origHeader['n_count']

  # show some file informations
  printTrkInfo( tracksHeader, trkFile )

  # grab the scalarNames
  scalarNames = []
  for a in actions:
    if a.scalarName() != FyAction.NoScalar:
      scalarNames.append( a.scalarName() )

  # increase the number of scalars
  tracksHeader['n_scalars'] += len( scalarNames )

  # .. attach the new scalar names
  for i in range( len( scalarNames ) ):
    tracksHeader['scalar_name'][numberOfScalars + i] = scalarNames[i]

  #
  # THREADED COMPONENT
  #
  if singleThread:
    numberOfThreads = 1
  else:
    numberOfThreads = multiprocessing.cpu_count()
  c.info( 'Splitting master into ' + str( numberOfThreads ) + ' pieces..' )
  splittedOutputTracks = u.split_list( tracks[:], numberOfThreads )

  # list of threads
  t = [None] * numberOfThreads

  # list of alive flags
  a = [None] * numberOfThreads

  # list of tempFiles
  f = [None] * numberOfThreads

  for n in xrange( numberOfThreads ):
    # configure actions
    __actions = []
    for act in actions:
      __actions.append( act )

    # mark thread as alive
    a[n] = True
    # fire the thread and give it a filename based on the number
    tmpFile = tempfile.mkstemp( '.trk', 'fyborg' )[1]
    f[n] = tmpFile
    t[n] = Process( target=fyborgLooper_, args=( splittedOutputTracks[n][:], tracksHeader, tmpFile, __actions, showDebug, n + 1 ) )
    c.info( "Starting Thread-" + str( n + 1 ) + "..." )
    t[n].start()

  allDone = False

  while not allDone:

    time.sleep( 1 )

    for n in xrange( numberOfThreads ):

      a[n] = t[n].is_alive()

    if not any( a ):
      # if no thread is alive
      allDone = True

  #
  # END OF THREADED COMPONENT
  #
  c.info( "All Threads done!" )

  #
  # Merging stage
  #
  c.info( "Merging tracks.." )

  outputTracks = []
  # now read all the created tempFiles and merge'em to one
  for tmpFileNo in xrange( 0, len( f ) ):
    tTracks = io.loadTrk( f[tmpFileNo] )

    # add them
    outputTracks.extend( tTracks[0] )

  c.info( "Merging done!" )

  io.saveTrk( outputTrkFile, outputTracks, tracksHeader, None, True )

  c.info( "All done!" )