Exemplo n.º 1
0
def _fromJavaArray(obj, customConverter=None):
    '''
    Converts from a Java array to a Python list.
    '''
    retVal = []
    size = Array.getLength(obj)
    for i in range(size):
        retVal.append(JUtil.javaObjToPyVal(Array.get(obj, i), customConverter))
    return retVal
Exemplo n.º 2
0
def upload_image(gateway, path, host, dataset_id):

    user = gateway.getLoggedInUser()
    ctx = SecurityContext(user.getGroupId())
    session_key = gateway.getSessionId(user)
    
    str2d = Array.newInstance(String,[1])
    str2d[0] = path
    
    config = ImportConfig()

    config.email.set("")
    config.sendFiles.set('true')
    config.sendReport.set('false')
    config.contOnError.set('false')
    config.debug.set('false')
    config.hostname.set(host)
    config.sessionKey.set(session_key)
    config.targetClass.set("omero.model.Dataset")
    config.targetId.set(dataset_id)

    loci.common.DebugTools.enableLogging("DEBUG")

    store = config.createStore()
    reader = OMEROWrapper(config)

    library = ImportLibrary(store,reader)
    error_handler = ErrorHandler(config)

    library.addObserver(LoggingImportMonitor())
    candidates = ImportCandidates(reader, str2d, error_handler)
    reader.setMetadataOptions(DefaultMetadataOptions(MetadataLevel.ALL))
    print('Importing image: ' + str2d[0])
    success = library.importCandidates(config, candidates)
    return success
Exemplo n.º 3
0
    def test_java_object_arrays(self):
        jStringArr = array(String, [String("a"), String("b"), String("c")])
        self.assert_(
            Arrays.equals(jStringArr.typecode, 'java.lang.String'),
               "String array typecode of wrong type, expected %s, found %s" % 
               (jStringArr.typecode, str(String)))
        self.assertEqual(zeros(String, 5), Array.newInstance(String, 5))

        import java.lang.String # require for eval to work
        self.assertEqual(jStringArr, eval(str(jStringArr)))
Exemplo n.º 4
0
def test_java_object_arrays():
   jStringArr = array(String, [String("a"), String("b"), String("c")])
   verify(Arrays.equals(jStringArr.typecode, str(String)), 
         "String array typecode of wrong type, expected %s, found %s" % 
         (jStringArr.typecode, str(String)))
   verify(zeros(String, 5) == Array.newInstance(String, 5))

   import java # require for eval to work
   if jStringArr != eval(str(jStringArr)):
      raise TestFailed, "eval(str(%s)) <> %s" % (jStringArr,)*2
Exemplo n.º 5
0
    def test_java_object_arrays(self):
        jStringArr = array(String, [String("a"), String("b"), String("c")])
        self.assert_(
            Arrays.equals(jStringArr.typecode, 'java.lang.String'),
            "String array typecode of wrong type, expected %s, found %s" %
            (jStringArr.typecode, str(String)))
        self.assertEqual(zeros(String, 5), Array.newInstance(String, 5))

        import java.lang.String  # require for eval to work
        self.assertEqual(jStringArr, eval(str(jStringArr)))
Exemplo n.º 6
0
def create_registered_hyperstack(imp, target_folder, channel):
  """ Takes the imp, which contains a virtual hyper stack,
  and determines the x,y,z drift for each pair of time points,
  using the preferred given channel,
  and output one image for each slide into the target folder."""
  print "starting to calculate translations..."
  shifts = compute_frame_translations(imp, channel)
  # Make shifts relative to 0,0,0 of the original imp:
  shifts = concatenate_shifts(shifts)
  print "shifts concatenated:"
  for s in shifts:
    print s.x, s.y, s.z
  # Compute bounds of the new volume,
  # which accounts for all translations:
  minx, miny, minz, maxx, maxy, maxz = compute_min_max(shifts)
  # Make shifts relative to new canvas dimensions
  # so that the min values become 0,0,0
  for shift in shifts:
    shift.x -= minx
    shift.y -= miny
    shift.z -= minz
  print "shifts relative to new dimensions:"
  for s in shifts:
    print s.x, s.y, s.z
  writer = CSVWriter(FileWriter(target_folder+"/shifts.csv"), ',')
  data = Array.newInstance(Class.forName("java.lang.String"), 3)  
  for s in shifts:
     data[0] = str(s.x)
     data[1] = str(s.y)
     data[2] = str(s.z)
     writer.writeNext(data)
  writer.close()
  # new canvas dimensions:
  width = imp.width + maxx - minx
  height = maxy - miny + imp.height
  slices = maxz - minz + imp.getNSlices()

  print "New dimensions:", width, height, slices
  # Count number of digits of each dimension, to output zero-padded numbers:
  slice_digits = len(str(slices))
  frame_digits = len(str(imp.getNFrames()))
  channel_digits = len(str(imp.getNChannels()))
  # List to accumulate all created names:
  names = []
  # Prepare empty slice to pad in Z when necessary
  empty = imp.getProcessor().createProcessor(width, height)
  # if it's RGB, fill the empty slice with blackness
  if isinstance(empty, ColorProcessor):
    empty.setValue(0)
    empty.fill()
  # Write all slices to files:
  stack = imp.getStack()
  for frame in range(1, imp.getNFrames()+1):
    shift = shifts[frame-1]
    fr = "t" + zero_pad(frame, frame_digits)
    # Pad with mpty slices before reaching the first slice
    for s in range(shift.z):
      ss = "_z" + zero_pad(s + 1, slice_digits) # slices start at 1
      for ch in range(1, imp.getNChannels()+1):
        name = fr + ss + "_c" + zero_pad(ch, channel_digits) +".tif"
        names.append(name)
        FileSaver(ImagePlus("", empty)).saveAsTiff(target_folder + "/" + name)
    # Add all proper slices
    for s in range(1, imp.getNSlices()+1):
      ss = "_z" + zero_pad(s + shift.z, slice_digits)
      for ch in range(1, imp.getNChannels()+1):
         ip = stack.getProcessor(imp.getStackIndex(ch, s, frame))
         ip2 = ip.createProcessor(width, height) # potentially larger
         ip2.insert(ip, shift.x, shift.y)
         name = fr + ss + "_c" + zero_pad(ch, channel_digits) +".tif"
         names.append(name)
         FileSaver(ImagePlus("", ip2)).saveAsTiff(target_folder + "/" + name)
    # Pad the end
    for s in range(shift.z + imp.getNSlices(), slices):
      ss = "_z" + zero_pad(s + 1, slice_digits)
      for ch in range(1, imp.getNChannels()+1):
        name = fr + ss + "_c" + zero_pad(ch, channel_digits) +".tif"
        names.append(name)
        FileSaver(ImagePlus("", empty)).saveAsTiff(target_folder + "/" + name)
  
  # Create virtual hyper stack with the result
  vs = VirtualStack(width, height, None, target_folder)
  for name in names:
    vs.addSlice(name)
  vs_imp = ImagePlus("registered time points", vs)
  vs_imp.setDimensions(imp.getNChannels(), len(names) / (imp.getNChannels() * imp.getNFrames()), imp.getNFrames())
  vs_imp.setOpenAsHyperStack(True)
  IJ.log("\nHyperstack dimensions: time frames:" + str(vs_imp.getNFrames()) + ", slices: " + str(vs_imp.getNSlices()) + ", channels: " + str(vs_imp.getNChannels()))
  if 1 == vs_imp.getNSlices():
    return vs_imp
  # Else, as composite
  mode = CompositeImage.COLOR;
  if isinstance(imp, CompositeImage):
    mode = imp.getMode()
  else:
    return vs_imp
  return CompositeImage(vs_imp, mode)
Exemplo n.º 7
0
def TrackMate_main(infile, outfile):
    file = File(infile)

    # We have to feed a logger to the reader.
    logger = Logger.IJ_LOGGER

    #-------------------
    # Instantiate reader
    #-------------------

    reader = TmXmlReader(file)
    if not reader.isReadingOk():
        sys.exit(reader.getErrorMessage())
    #-----------------
    # Get a full model
    #-----------------

    # This will return a fully working model, with everything
    # stored in the file. Missing fields (e.g. tracks) will be
    # null or None in python
    model = reader.getModel()
    model.setLogger(Logger.IJ_LOGGER)
    # model is a fiji.plugin.trackmate.Model

    #---------------------------------------
    # Building a settings object from a file
    #---------------------------------------

    # We start by creating an empty settings object
    settings = Settings()

    # Then we create all the providers, and point them to the target model:
    detectorProvider = DetectorProvider()
    trackerProvider = TrackerProvider()
    spotAnalyzerProvider = SpotAnalyzerProvider()
    edgeAnalyzerProvider = EdgeAnalyzerProvider()
    trackAnalyzerProvider = TrackAnalyzerProvider()

    reader.readSettings(settings, detectorProvider, trackerProvider,
                        spotAnalyzerProvider, edgeAnalyzerProvider,
                        trackAnalyzerProvider)

    #----------------
    # Save results
    #----------------

    # The feature model, that stores edge and track features.
    fm = model.getFeatureModel()

    f = open(outfile, 'wb')

    for id in model.getTrackModel().trackIDs(True):
        track = model.getTrackModel().trackSpots(id)
        for spot in track:
            sid = spot.ID()
            # Fetch spot features directly from spot.
            x = spot.getFeature('POSITION_X')
            y = spot.getFeature('POSITION_Y')
            t = spot.getFeature('FRAME')
            q = spot.getFeature('QUALITY')
            snr = spot.getFeature('SNR')
            mean = spot.getFeature('MEAN_INTENSITY')

            semiaxislength_c = spot.getFeature('ELLIPSOIDFIT_SEMIAXISLENGTH_C')
            if semiaxislength_c is None:
                semiaxislength_c = 0

            semiaxislength_b = spot.getFeature('ELLIPSOIDFIT_SEMIAXISLENGTH_B')
            if semiaxislength_b is None:
                semiaxislength_b = 0

            phi_b = spot.getFeature('ELLIPSOIDFIT_AXISPHI_B')
            if phi_b is None:
                phi_b = 0

            data = Array.newInstance(Class.forName("java.lang.String"), 9)
            #String[] entries = "first#second#third".split("#");
            data[0] = str(sid)
            data[1] = str(id)
            data[2] = str(x)
            data[3] = str(y)
            data[4] = str(t)
            data[5] = str(semiaxislength_c)
            data[6] = str(semiaxislength_b)
            data[7] = str(phi_b)
            data[8] = str(mean)

            # create csv writer
            writer = csv.writer(f)

            row = [
                data[0], data[1], data[2], data[3], data[4], data[5], data[6],
                data[7], data[8]
            ]
            writer.writerow(row)

    f.close()
    print('Saved ' + str(model.getTrackModel().nTracks(True)) + ' tracks.')
Exemplo n.º 8
0
    # 		  [ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0],
    # 		  [ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0],
    # 		  [ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0],
    # 		  [ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0],
    # 		  [ 0, 1, 0, 1, 0, 0, 0, 0, 1, 0],
    # 		  [ 0, 1, 0, 1, 1, 1, 1, 1, 1, 0],
    # 		  [ 0, -3, 0, 0, 0, 0, 0, 0, 0, 0],
    # 		  ]

    userMap = [[0, 3, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
               [0, -1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
               [0, 1, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
               [0, 1, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
               [0, 1, 1, 1, 1, 1, 1, 1, 1, -3], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
    n = len(userMap)
    tmp = reflectArray.newInstance(java.lang.Integer.TYPE, [n, n])
    for i in range(n):
        for j in range(n):
            tmp[i][j] = userMap[i][j]
    userMap = MapPrinter().mapToMatrix(tmp)
    maxX = maxY = n - 1

    gen = BasicGridWorld(userMap, maxX, maxY)
    domain = gen.generateDomain()
    initialState = gen.getExampleState(domain)

    rf = BasicRewardFunction(maxX, maxY, userMap)
    tf = BasicTerminalFunction(maxX, maxY)
    env = SimulatedEnvironment(domain, rf, tf, initialState)
    #    Print the map that is being analyzed
    print "/////{} Grid World Analysis/////\n".format(world)
Exemplo n.º 9
0
from org.csstudio.opibuilder.scriptUtil import PVUtil, ScriptUtil, FileUtil,\
    ConsoleUtil

import csv
from array import zeros, array
from java.lang import String
from java.util import Arrays
from java.lang.reflect import Array
table = display.getWidget("ScanTable1").getTable()

inWorkspace=display.getWidget("inWorkspace").getValue()

path = FileUtil.openFileDialog(inWorkspace)
if path != None and path.endswith('csv'):    
    if inWorkspace:
        path = FileUtil.workspacePathToSysPath(path)
    reader = csv.reader(open(path))
    lineList=[]
    for row in reader:
       lineList.append(row)
    content = Array.newInstance(String, len(lineList), len(row))
    for r in range(len(lineList)):
        for c in range(len(row)):
            content[r][c] = lineList[r][c]
    table.setContent(content)

    
Exemplo n.º 10
0
from org.csstudio.opibuilder.scriptUtil import PVUtil, ScriptUtil, FileUtil,\
    ConsoleUtil

import csv
from array import zeros, array
from java.lang import String
from java.util import Arrays
from java.lang.reflect import Array
table = display.getWidget("ScanTable1").getTable()

inWorkspace = display.getWidget("inWorkspace").getValue()

path = FileUtil.openFileDialog(inWorkspace)
if path != None and path.endswith('csv'):
    if inWorkspace:
        path = FileUtil.workspacePathToSysPath(path)
    reader = csv.reader(open(path))
    lineList = []
    for row in reader:
        lineList.append(row)
    content = Array.newInstance(String, len(lineList), len(row))
    for r in range(len(lineList)):
        for c in range(len(row)):
            content[r][c] = lineList[r][c]
    table.setContent(content)
Exemplo n.º 11
0
def arraySize(array):
    import java.lang.reflect.Array
    return Array.getLength(array);