def fn(self, *args): script = """ o.%s(%s); """ % (method, ",".join(["arg%d" % i for i in range(len(args))])) d = dict([("arg%d" % i, arg) for i, arg in enumerate(args)]) d["o"] = self.o J.run_script(script, d)
def test_05_07_get_pixel_data_3d(self): svc = ij2.get_dataset_service(self.context) result = svc.create1(np.array([10, 7, 3]), "MyDataset", [ij2.Axes().Y, ij2.Axes().X, ij2.Axes().CHANNEL], 16, False, False) imgplus = result.getImgPlus() script = """ ra = imgplus.randomAccess(); for (x=0;x<imgplus.dimension(0);x++) { ra.setPosition(x, 0); for (y=0;y<imgplus.dimension(1);y++) { ra.setPosition(y, 1); for (c=0;c<imgplus.dimension(2);c++) { ra.setPosition(c, 2); ra.get().set(x + y * 10 + c * 100); } } } """ J.run_script(script, dict(imgplus=imgplus)) pixel_data = ij2.get_pixel_data(imgplus) self.assertSequenceEqual(pixel_data.shape, [10, 7, 3]) i, j, c = np.mgrid[0:10, 0:7, 0:3] np.testing.assert_array_equal(pixel_data, i + j*10 + c*100)
def get_context(): '''Get the ImageJ context This is a singleton ImageJ context. We need a singleton for now because of http://trac.imagej.net/ticket/1413 This is an imagej.ImageJ, which at one point was the context. Call self.getContext() to get the org.scijava.Context which may be what you want. ''' global the_imagej_context if the_imagej_context is None: the_imagej_context = create_context(None) # # We have to turn off the updater and tell ImageJ to never call # System.exit. We have to tell ImageJ that we read the readme file. # # To Do: programatically turn off the updater and take control of # the quitting and exit process. # max_value = J.run_script( "java.lang.Long.toString(java.lang.Long.MAX_VALUE);") prefs = [ ("net.imagej.updater.UpToDate", "latestNag", max_value), ("net.imagej.options.OptionsMisc", "exitWhenQuitting", "false")] plugin_service = the_imagej_context.getService( "org.scijava.plugin.PluginService") ui_interface = J.class_for_name("org.scijava.ui.UserInterface") script = """ var result = java.lang.System.getProperty('ij.ui'); if (! result) { var infos = pluginService.getPluginsOfType(ui_interface); if (infos.size() > 0) { result = infos.get(0).getClassName(); } } result;""" ui_class = J.run_script(script, dict(pluginService=plugin_service, ui_interface=ui_interface)) first_run = "firstRun-"+the_imagej_context.getVersion() if ui_class: prefs.append((ui_class, first_run, "false")) for class_name, key, value in prefs: c = J.class_for_name(class_name) J.static_call( "org/scijava/util/Prefs", "put", "(Ljava/lang/Class;Ljava/lang/String;Ljava/lang/String;)V", c, key, value) return the_imagej_context
def fn_launch_frame(event): javabridge.execute_runnable_in_main_thread(javabridge.run_script(""" new java.lang.Runnable() { run: function() { with(JavaImporter(java.awt.Frame)) Frame().setVisible(true); } };"""))
def omero_login(): global __omero_config_file global __omero_session_id global __omero_server global __omero_username global __omero_port global __omero_password if __omero_config_file is not None and os.path.isfile(__omero_config_file): env = jutil.get_env() config = env.make_object_array(1, env.find_class("java/lang/String")) env.set_object_array_element( config, 0, env.new_string("--Ice.Config=%s" % __omero_config_file)) script = """ var client = Packages.omero.client(config); client.createSession(); client.getSessionId(); """ __omero_session_id = jutil.run_script(script, dict(config=config)) elif all([ x is not None for x in (__omero_server, __omero_port, __omero_username, __omero_password) ]): set_omero_credentials(__omero_server, __omero_port, __omero_username, __omero_password) else: __omero_login_fn() return __omero_session_id
def get_omero_reader(): '''Return an ``loci.ome.io.OMEROReader`` instance, wrapped as a FormatReader. ''' script = """ var rdr = new Packages.loci.ome.io.OmeroReader(); rdr.setServer(server); rdr.setPort(port); rdr.setUsername(username); rdr.setSessionID(sessionID); rdr; """ if __omero_session_id is None: omero_login() jrdr = jutil.run_script( script, dict(server=__omero_server, port=__omero_port, username=__omero_username, sessionID=__omero_session_id)) rdr = make_iformat_reader_class()() rdr.o = jrdr return rdr
def get_omexml_metadata(path=None, url=None): '''Read the OME metadata from a file using Bio-formats :param path: path to the file :param groupfiles: utilize the groupfiles option to take the directory structure into account. :returns: the metdata as XML. ''' with ImageReader(path=path, url=url, perform_init=False) as rdr: # # Below, "in" is a keyword and Rhino's parser is just a little wonky I fear. # # It is critical that setGroupFiles be set to false, goodness knows # why, but if you don't the series count is wrong for flex files. # script = """ importClass(Packages.loci.common.services.ServiceFactory, Packages.loci.formats.services.OMEXMLService, Packages.loci.formats['in'].DefaultMetadataOptions, Packages.loci.formats['in'].MetadataLevel); reader.setGroupFiles(false); reader.setOriginalMetadataPopulated(true); var service = new ServiceFactory().getInstance(OMEXMLService); var metadata = service.createOMEXMLMetadata(); reader.setMetadataStore(metadata); reader.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.ALL)); reader.setId(path); var xml = service.getOMEXML(metadata); xml; """ xml = jutil.run_script(script, dict(path=rdr.path, reader=rdr.rdr)) return xml
def set_omero_credentials(omero_server, omero_port, omero_username, omero_password): '''Set the credentials to be used to connect to the Omero server :param omero_server: DNS name of the server :param omero_port: use this port to connect to the server :param omero_username: log on as this user :param omero_password: log on using this password The session ID is valid after this function is called. An exception is thrown if the login fails. :func:`bioformats.omero_logout()` can be called to log out. ''' global __omero_server global __omero_username global __omero_session_id global __omero_port __omero_server = omero_server __omero_port = omero_port __omero_username = omero_username script = """ var client = Packages.omero.client(server, port); var serverFactory = client.createSession(user, password); client.getSessionId(); """ __omero_session_id = jutil.run_script( script, dict(server=__omero_server, port=__omero_port, user=__omero_username, password=omero_password)) return __omero_session_id
def set_omero_credentials(omero_server, omero_port, omero_username, omero_password): '''Set the credentials to be used to connect to the Omero server :param omero_server: DNS name of the server :param omero_port: use this port to connect to the server :param omero_username: log on as this user :param omero_password: log on using this password The session ID is valid after this function is called. An exception is thrown if the login fails. :func:`bioformats.omero_logout()` can be called to log out. ''' global __omero_server global __omero_username global __omero_session_id global __omero_port __omero_server = omero_server __omero_port = omero_port __omero_username = omero_username script = """ var client = Packages.omero.client(server, port); var serverFactory = client.createSession(user, password); client.getSessionId(); """ __omero_session_id = jutil.run_script(script, dict( server = __omero_server, port = __omero_port, user = __omero_username, password = omero_password)) return __omero_session_id
def omero_login(): global __omero_config_file global __omero_session_id global __omero_server global __omero_username global __omero_port global __omero_password if __omero_config_file is not None and os.path.isfile(__omero_config_file): env = jutil.get_env() config = env.make_object_array(1, env.find_class("java/lang/String")) env.set_object_array_element( config, 0, env.new_string("--Ice.Config=%s" % __omero_config_file)) script = """ var client = Packages.omero.client(config); client.createSession(); client.getSessionId(); """ __omero_session_id = jutil.run_script(script, dict(config=config)) elif all([x is not None for x in (__omero_server, __omero_port, __omero_username, __omero_password)]): set_omero_credentials(__omero_server, __omero_port, __omero_username, __omero_password) else: __omero_login_fn() return __omero_session_id
def get_omexml_metadata(path=None, url=None): '''Read the OME metadata from a file using Bio-formats :param path: path to the file :param groupfiles: utilize the groupfiles option to take the directory structure into account. :returns: the metdata as XML. ''' with ImageReader(path=path, url=url, perform_init=False) as rdr: # # Below, "in" is a keyword and Rhino's parser is just a little wonky I fear. # # It is critical that setGroupFiles be set to false, goodness knows # why, but if you don't the series count is wrong for flex files. # script = """ importClass(Packages.loci.common.services.ServiceFactory, Packages.loci.formats.services.OMEXMLService, Packages.loci.formats['in'].DefaultMetadataOptions, Packages.loci.formats['in'].MetadataLevel); reader.setGroupFiles(false); reader.setOriginalMetadataPopulated(true); var service = new ServiceFactory().getInstance(OMEXMLService); var metadata = service.createOMEXMLMetadata(); reader.setMetadataStore(metadata); reader.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.ALL)); reader.setId(path); var xml = service.getOMEXML(metadata); xml; """ xml = jutil.run_script(script, dict(path=rdr.path, reader = rdr.rdr)) return xml
def test_06_03_future_main(self): c = javabridge.run_script(""" new java.util.concurrent.Callable() { call: function() { return 2+2; }};""") result = javabridge.execute_future_in_main_thread( javabridge.make_future_task(c, fn_post_process=javabridge.unwrap_javascript)) self.assertEqual(result, 4)
def finalize(self, result): try: javabridge.deactivate_awt() import imagej.imagej2 if imagej.imagej2.the_imagej_context is not None: script = """ new java.lang.Runnable () { run: function() { ctx.getContext().dispose(); } }""" runnable = javabridge.run_script( script, dict(ctx=imagej.imagej2.the_imagej_context)) javabridge.execute_runnable_in_main_thread(runnable, True) imagej.imagej2.the_imagej_context = None javabridge.static_call("java/lang/System", "gc", "()V") except: pass try: from ilastik.core.jobMachine import GLOBAL_WM GLOBAL_WM.stopWorkers() except: logging.root.warn("Failed to stop Ilastik") try: from cellprofiler.utilities.zmqrequest import join_to_the_boundary join_to_the_boundary() except: logging.root.warn("Failed to stop zmq boundary")
def _init_writer(self): # If file already exists, delete it before initializing again. # If this is not done, then the file will be appended. if os.path.exists(self._file_path): os.remove(self._file_path) w_klass = make_ome_tiff_writer_class() w_klass.setId = jutil.make_method('setId', '(Ljava/lang/String;)V', 'Sets the current file name.') w_klass.saveBytesXYWH = jutil.make_method( 'saveBytes', '(I[BIIII)V', 'Saves the given byte array to the current file') w_klass.close = jutil.make_method( 'close', '()V', 'Closes currently open file(s) and frees allocated memory.') w_klass.setTileSizeX = jutil.make_method( 'setTileSizeX', '(I)I', 'Set tile size width in pixels.') w_klass.setTileSizeY = jutil.make_method( 'setTileSizeY', '(I)I', 'Set tile size height in pixels.') w_klass.getTileSizeX = jutil.make_method( 'getTileSizeX', '()I', 'Set tile size width in pixels.') w_klass.getTileSizeY = jutil.make_method( 'getTileSizeY', '()I', 'Set tile size height in pixels.') writer = w_klass() script = """ importClass(Packages.loci.formats.services.OMEXMLService, Packages.loci.common.services.ServiceFactory); var service = new ServiceFactory().getInstance(OMEXMLService); var metadata = service.createOMEXMLMetadata(xml); var writer = writer writer.setMetadataRetrieve(metadata); """ jutil.run_script( script, dict(path=self._file_path, xml=self._metadata.to_xml(), writer=writer)) writer.setId(self._file_path) writer.setInterleaved(False) writer.setCompression("LZW") x = writer.setTileSizeX(self._TILE_SIZE) y = writer.setTileSizeY(self._TILE_SIZE) self._pix['chunk'] = self._MAX_BYTES / ( self._pix['spp'] * self._pix['bpp'] ) # number of pixels to load at a time self.__writer = writer
def test_06_03_future_main(self): c = javabridge.run_script(""" new java.util.concurrent.Callable() { call: function() { return 2+2; }};""") result = javabridge.execute_future_in_main_thread( javabridge.make_future_task( c, fn_post_process=javabridge.unwrap_javascript)) self.assertEqual(result, 4)
def test_valid(self, pipeline): try: import javabridge as J J.run_script( """ importPackage(Packages.org.cellprofiler.imageset.filter); new Filter(expr, klass); """, dict( expr=self.value_text, klass=J.class_for_name( "org.cellprofiler.imageset.ImagePlaneDetailsStack"), ), ) except Exception as e: raise ValidationError(str(e), self)
def fn_launch_frame(event): javabridge.execute_runnable_in_main_thread( javabridge.run_script(""" new java.lang.Runnable() { run: function() { with(JavaImporter(java.awt.Frame)) Frame().setVisible(true); } };"""))
def cast(o, klass): '''Cast the given object to the given class :param o: either a Python object or Java object to be cast :param klass: a java.lang.Class indicating the target class raises a TypeError if the object can't be cast. ''' if J.call(klass, "getName", "()Ljava/lang/String;") == 'void': return None is_primitive = J.call(klass, "isPrimitive", "()Z") csig = sig(klass) if o is None: if not is_primitive: return None else: raise TypeError("Can't cast None to a primitive type") if isinstance(o, J.JB_Object): if J.call(klass, "isInstance", "(Ljava/lang/Object;)Z", o): return o classname = J.run_script("o.getClass().getCanonicalName()", dict(o=o)) klassname = J.run_script("klass.getCanonicalName()", dict(klass=klass)) raise TypeError("Object of class %s cannot be cast to %s", classname, klassname) elif hasattr(o, "o"): return cast(o.o, klass) elif not np.isscalar(o): component_type = J.call(klass, "getComponentType", "()Ljava/lang/Class;") if component_type is None: raise TypeError("Argument must not be a sequence") if len(o) > 0: # Test if an element can be cast to the array type cast(o[0], component_type) return J.get_nice_arg(o, csig) elif is_primitive or csig in \ ('Ljava/lang/String;', 'Ljava/lang/CharSequence;', 'Ljava/lang/Object;'): if csig == 'Ljava/lang/CharSequence;': csig = 'Ljava/lang/String;' elif csig == 'C' and isinstance(o, basestring) and len(o) != 1: raise TypeError("Failed to convert string of length %d to char" % len(o)) return J.get_nice_arg(o, csig) raise TypeError("Failed to convert argument to %s" % csig)
def test_07_04_make_future_task_from_callable(self): call_able = javabridge.run_script(""" new java.util.concurrent.Callable() { call: function() { return 2+2; }};""") future = javabridge.make_future_task( call_able, fn_post_process=javabridge.unwrap_javascript) future.run() self.assertEqual(future.get(), 4)
def setActiveDisplay(self, display): '''Make this the active display''' # Note: has to be run in GUI thread on mac r = J.run_script( """new java.lang.Runnable() { run:function() { displayService.setActiveDisplay(display); } } """, dict(displayService=self.o, display=display.o)) J.execute_runnable_in_main_thread(r, True)
def test_java_bridge(): javabridge.start_vm(run_headless=True) try: print( javabridge.run_script( 'java.lang.String.format("Hello, %s!", name);', dict(name='world'))) finally: javabridge.kill_vm()
def do_new_engine(payload): '''Create a new engine thread payload: first member is request queue, second is response queue ''' logger.info("Creating new engine") thread = threading.Thread(target=engine, args=list(payload[:2]), name="Scripting-CPythonEngine") thread.setDaemon(True) thread.start() J.run_script( """importPackage(Packages.org.scijava.plugins.scripting.cpython); var payload = new java.util.ArrayList(); var response = new CPythonScriptEngine.Message( CPythonScriptEngine.EngineCommands.NEW_ENGINE_RESULT, payload); CPythonScriptEngine.engineResponseQueue.put(response); """)
def engine(q_request, q_response): logger.info("Starting script engine thread") J.attach() while True: try: msg = J.run_script( """importPackage(Packages.org.scijava.plugins.scripting.cpython); q_request.take();""", dict(q_request=q_request)) if logger.level <= logging.INFO: logger.info("Received engine request: %s", J.to_string(msg)) payload = J.get_collection_wrapper( J.run_script("msg.payload", dict(msg=msg))) if J.run_script( """importPackage(Packages.org.scijava.plugins.scripting.cpython); msg.command==CPythonScriptEngine.EngineCommands.EXECUTE; """, dict(msg=msg)): response = do_execute(payload) elif J.run_script( """importPackage(Packages.org.scijava.plugins.scripting.cpython); msg.command==CPythonScriptEngine.EngineCommands.EVALUATE; """, dict(msg=msg)): response = do_evaluate(payload) elif J.run_script( """importPackage(Packages.org.scijava.plugins.scripting.cpython); msg.command==CPythonScriptEngine.EngineCommands.CLOSE_ENGINE; """, dict(msg=msg)): logger.info("Exiting script engine thread after close request") break else: logger.warn( "Received unknown command: %s" % J.run_script("msg.command.toString()", dict(msg=msg))) response = J.run_script( """importPackage(Packages.org.scijava.plugins.scripting.cpython); var exception = new java.lang.RuntimeException( java.lang.String.format('Unknown command: %s', msg.command.toString())); var payload = new java.util.ArrayList(); payload.add(exception); new CPythonScriptEngine.Message( CPythonScriptEngine.EngineCommands.EXCEPTION, payload); """, dict(msg=msg)) J.run_script("q_response.put(response);", dict(q_response=q_response, response=response)) except: # To do: how to handle failure, probably from .take() # Guessing that someone has managed to interrupt our thread logger.warn("Exiting script engine thread", exc_info=True) J.detach()
def hide(self): J.execute_runnable_in_main_thread( J.run_script( """ new java.lang.Runnable() { run: function() { o.hide(); }}""", dict(o=self.o), ), synchronous=True, )
def run_javabridge(java_code_to_run): javabridge.start_vm(run_headless=True) try: output = javabridge.run_script(java_code_to_run) print(output) # need to process and return some stuff here finally: javabridge.kill_vm()
def test_07_02_cancel_future(self): future = javabridge.run_script(""" new java.util.concurrent.FutureTask( new java.util.concurrent.Callable() { call: function() { return 2+2; }});""") wfuture = javabridge.get_future_wrapper( future, fn_post_process=javabridge.unwrap_javascript) wfuture.cancel(True) self.assertTrue(wfuture.isCancelled()) self.assertRaises(javabridge.JavaException, wfuture.get)
def execute_macro(macro_text): '''Execute a macro in ImageJ macro_text - the macro program to be run ''' interp = J.make_instance("ij/macro/Interpreter","()V"); J.execute_runnable_in_main_thread(J.run_script( """new java.lang.Runnable() { run: function() { interp.run(macro_text); }}""", dict(interp=interp, macro_text=macro_text)), synchronous=True)
def set_temp_current_image(imagej_obj): '''Set the temporary current image for the UI thread''' script = """ new java.lang.Runnable() { run: function() { Packages.ij.WindowManager.setTempCurrentImage(ip); } }; """ javabridge.execute_runnable_in_main_thread( javabridge.run_script(script, dict(ip=imagej_obj.o)), True)
def get_measurements_for_good_pipeline(nimages=1, group_numbers=None): '''Get an appropriately initialized measurements structure for the good pipeline''' path = os.path.join(tests.modules.example_images_directory(), "ExampleSBSImages") m = cellprofiler.measurement.Measurements() if group_numbers is None: group_numbers = [1] * nimages group_indexes = [1] last_group_number = group_numbers[0] group_index = 1 for group_number in group_numbers: if group_number == last_group_number: group_index += 1 else: group_index = 1 group_indexes.append(group_index) for i in range(1, nimages + 1): filename = ("Channel2-%02d-%s-%02d.tif" % (i, "ABCDEFGH"[int( (i - 1) / 12)], ((i - 1) % 12) + 1)) url = cellprofiler.modules.loadimages.pathname2url( os.path.join(path, filename)) m[cellprofiler.measurement.IMAGE, cellprofiler.measurement.C_FILE_NAME + "_DNA", i] = filename m[cellprofiler.measurement.IMAGE, cellprofiler.measurement.C_PATH_NAME + "_DNA", i] = path m[cellprofiler.measurement.IMAGE, cellprofiler.measurement.C_URL + "_DNA", i] = url m[cellprofiler.measurement.IMAGE, cellprofiler.measurement.GROUP_NUMBER, i] = group_numbers[i - 1] m[cellprofiler.measurement.IMAGE, cellprofiler.measurement.GROUP_INDEX, i] = group_indexes[i - 1] jblob = javabridge.run_script( """ importPackage(Packages.org.cellprofiler.imageset); importPackage(Packages.org.cellprofiler.imageset.filter); var imageFile=new ImageFile(new java.net.URI(url)); var imageFileDetails = new ImageFileDetails(imageFile); var imageSeries=new ImageSeries(imageFile, 0); var imageSeriesDetails = new ImageSeriesDetails(imageSeries, imageFileDetails); var imagePlane=new ImagePlane(imageSeries, 0, ImagePlane.ALWAYS_MONOCHROME); var ipd = new ImagePlaneDetails(imagePlane, imageSeriesDetails); var stack = ImagePlaneDetailsStack.makeMonochromeStack(ipd); var stacks = java.util.Collections.singletonList(stack); var keys = java.util.Collections.singletonList(imageNumber); var imageSet = new ImageSet(stacks, keys); imageSet.compress(java.util.Collections.singletonList("DNA"), null); """, dict(url=url, imageNumber=str(i))) blob = javabridge.get_env().get_byte_array_elements(jblob) m[cellprofiler.measurement.IMAGE, cellprofiler.modules.namesandtypes.M_IMAGE_SET, i, blob.dtype] = blob pipeline = cellprofiler.pipeline.Pipeline() pipeline.loadtxt(cStringIO.StringIO(GOOD_PIPELINE)) pipeline.write_pipeline_measurement(m) return m
def set_temp_current_image(imagej_obj): '''Set the temporary current image for the UI thread''' script = """ new java.lang.Runnable() { run: function() { Packages.ij.WindowManager.setTempCurrentImage(ip); } }; """ J.execute_runnable_in_main_thread( J.run_script(script, dict(ip=imagej_obj.o)), True)
def close(self): '''Close the display This is run in the UI thread with synchronization. ''' r = J.run_script( """new java.lang.Runnable() { run: function() { display.close(); } }; """, dict(display=self.o)) J.execute_runnable_in_main_thread(r, True)
def execute_macro(macro_text): '''Execute a macro in ImageJ macro_text - the macro program to be run ''' interp = javabridge.make_instance("ij/macro/Interpreter", "()V"); javabridge.execute_runnable_in_main_thread(javabridge.run_script( """new java.lang.Runnable() { run: function() { interp.run(macro_text); }}""", dict(interp=interp, macro_text=macro_text)), synchronous=True)
def get_pixel_data(self, axes=None): imgplus = self.getImgPlus() pixel_data = get_pixel_data(imgplus) script = """ var result = java.util.ArrayList(); for (i=0;i<imgplus.numDimensions();i++) result.add(imgplus.axis(i).type()); result""" inv_axes = J.run_script(script, dict(imgplus=imgplus)) inv_axes = list(J.iterate_collection(inv_axes)) transpose = calculate_transpose(inv_axes, axes) return pixel_data.transpose(transpose)
def test_07_01_wrap_future(self): future = javabridge.run_script(""" new java.util.concurrent.FutureTask( new java.util.concurrent.Callable() { call: function() { return 2+2; }});""") wfuture = javabridge.get_future_wrapper( future, fn_post_process=javabridge.unwrap_javascript) self.assertFalse(wfuture.isDone()) self.assertFalse(wfuture.isCancelled()) wfuture.run() self.assertTrue(wfuture.isDone()) self.assertEqual(wfuture.get(), 4)
def get_temp_current_image(): '''Get the temporary ImagePlus object for the current thread''' script = """ new java.util.concurrent.Callable() { call: function() { return Packages.ij.WindowManager.getTempCurrentImage(); } }; """ gtci = J.make_future_task(J.run_script(script)) imageplus_obj = J.execute_future_in_main_thread(gtci) return get_imageplus_wrapper(imageplus_obj)
def get_temp_current_image(): '''Get the temporary ImagePlus object for the current thread''' script = """ new java.util.concurrent.Callable() { call: function() { return Packages.ij.WindowManager.getTempCurrentImage(); } }; """ gtci = javabridge.make_future_task(javabridge.run_script(script)) imageplus_obj = javabridge.execute_future_in_main_thread(gtci) return imagej.imageplus.get_imageplus_wrapper(imageplus_obj)
def get_pixel_data(self, axes = None): imgplus = self.getImgPlus() pixel_data = get_pixel_data(imgplus) script = """ var result = java.util.ArrayList(); for (i=0;i<imgplus.numDimensions();i++) result.add(imgplus.axis(i).type()); result""" inv_axes = J.run_script(script, dict(imgplus=imgplus)) inv_axes = list(J.iterate_collection(inv_axes)) transpose = calculate_transpose(inv_axes, axes) return pixel_data.transpose(transpose)
def test_05_03_get_pixel_data(self): svc = ij2.get_dataset_service(self.context) result = svc.create1(np.array([10, 7]), "MyDataset", [ij2.Axes().Y, ij2.Axes().X], 8, False, False) imgplus = result.getImgPlus() script = """ ra = imgplus.randomAccess(); for (x=0;x<imgplus.dimension(0);x++) { ra.setPosition(x, 0); for (y=0;y<imgplus.dimension(1);y++) { ra.setPosition(y, 1); ra.get().set(x + y * 10); } } """ J.run_script(script, dict(imgplus=imgplus)) pixel_data = ij2.get_pixel_data(imgplus) self.assertSequenceEqual(pixel_data.shape, [10, 7]) i, j = np.mgrid[0:10, 0:7] np.testing.assert_array_equal(pixel_data, i + j * 10)
def __init__(self, figure): FigureCanvasAgg.__init__(self, figure) self.__ref_id, self.__ref = javabridge.create_jref(self) self.__cpython = javabridge.make_instance( 'org/cellprofiler/javabridge/CPython', '()V') paint_script = ( 'import javabridge\n' 'self = javabridge.redeem_jref("%s")\n' 'self.draw(javabridge.JWrapper(graphics))\n') % self.__ref_id component = javabridge.run_script( """ new javax.swing.JComponent() { paintComponent: function(graphics) { locals = new java.util.Hashtable(); locals.put("graphics", graphics); cpython.exec(script, locals, locals); } } """, dict(cpython=self.__cpython, script=paint_script)) self.__component = javabridge.JWrapper(component) self.__event_queue_class = None self.__component_listener = javabridge.JProxy( 'java.awt.event.ComponentListener', dict(componentHidden=self._on_component_hidden, componentMoved=self._on_component_moved, componentResized=self._on_component_resized, componentShown=self._on_component_shown)) self.__component.addComponentListener(self.__component_listener.o) self.__key_event_cls = javabridge.JClassWrapper( 'java.awt.event.KeyEvent') self.__key_listener = javabridge.JProxy( 'java.awt.event.KeyListener', dict(keyPressed=self._on_key_pressed, keyReleased=self._on_key_released, keyTyped=self._on_key_typed)) self.__component.addKeyListener(self.__key_listener.o) self.__component.setFocusable(True) self.__mouse_listener = javabridge.JProxy( 'java.awt.event.MouseListener', dict(mouseClicked=self._on_mouse_clicked, mouseEntered=self._on_mouse_entered, mouseExited=self._on_mouse_exited, mousePressed=self._on_mouse_pressed, mouseReleased=self._on_mouse_released)) self.__component.addMouseListener(self.__mouse_listener.o) self.__mouse_motion_listener = javabridge.JProxy( 'java.awt.event.MouseMotionListener', dict(mouseDragged=self._on_mouse_dragged, mouseMoved=self._on_mouse_moved)) self.__component.addMouseMotionListener(self.__mouse_motion_listener.o)
def fn(self, *args): script = """ new java.lang.Runnable() { run: function() { o.%s(%s); } }; """ % (method, ",".join(["arg%d" % i for i in range(len(args))])) d = dict([("arg%d" % i, arg) for i, arg in enumerate(args)]) d["o"] = self.o future = J.make_future_task(J.run_script(script, d)) J.execute_future_in_main_thread(future) return future.get()
def __init__(self): if service_classes is None: classes = None ctxt_fn = J.run_script( """new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(false); } }""") else: classes = [ J.class_for_name(x) for x in service_classes or REQUIRED_SERVICES] classes = J.make_list(classes) ctxt_fn = J.run_script( """new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(classes); } }""", dict(classes = classes.o)) self.o = J.call(ctxt_fn, 'call', '()Ljava/lang/Object;')
def fn(self, *args): script = """ new java.util.concurrent.Callable() { call: function() { return o.%s(%s); } }; """ % (method, ",".join(["arg%d" % i for i in range(len(args))])) d = dict([("arg%d" % i, arg) for i, arg in enumerate(args)]) d["o"] = self.o future = J.make_future_task(J.run_script(script, d)) J.execute_future_in_main_thread(future) return fn_post_process(future.get())
def __init__(self): if service_classes is None: classes = None ctxt_fn = J.run_script( """new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(false); } }""") else: classes = [ J.class_for_name(x) for x in service_classes or REQUIRED_SERVICES] classes = J.make_list(classes) ctxt_fn = J.run_script( """new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(classes); } }""", dict(classes = classes.o)) self.o = J.execute_future_in_main_thread( J.make_future_task(ctxt_fn))
def __init__(self): if service_classes is None: classes = None ctxt_fn = J.run_script("""new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(false); } }""") else: classes = [ J.class_for_name(x) for x in service_classes or REQUIRED_SERVICES ] classes = J.make_list(classes) ctxt_fn = J.run_script( """new java.util.concurrent.Callable() { call: function() { return new Packages.net.imagej.ImageJ(classes); } }""", dict(classes=classes.o)) self.o = J.execute_future_in_main_thread( J.make_future_task(ctxt_fn))
def test_05_06_create_dataset(self): i,j = np.mgrid[:7, :9] image = (i+j*10).astype(float) ds = ij2.create_dataset(self.context, image, "Foo") imgplus = ds.getImgPlus() script = """ var ra=imgplus.randomAccess(); ra.setPosition(x, 0); ra.setPosition(y, 1); ra.get().get()""" fn = np.frompyfunc( lambda x, y: J.run_script(script, dict(imgplus=imgplus, x=x, y=y)), 2, 1) pixel_data = fn(j, i) np.testing.assert_array_equal(image, pixel_data)
def select_overlay(display, overlay, select=True): '''Select or deselect an overlay display - the overlay's display overlay - the overlay to select ''' for view in J.get_collection_wrapper(display, fn_wrapper = wrap_data_view): if J.call(overlay, "equals", "(Ljava/lang/Object;)Z", view.getData()): J.execute_runnable_in_main_thread(J.run_script( """new java.lang.Runnable() { run: function() { view.setSelected(select);} }""", dict(view = view.o, select=select)), synchronous=True) break else: logger.info("Failed to select overlay")
def get_measurements_for_good_pipeline(nimages = 1, group_numbers = None): '''Get an appropriately initialized measurements structure for the good pipeline''' path = os.path.join(example_images_directory(), "ExampleSBSImages") m = cpmeas.Measurements() if group_numbers is None: group_numbers = [1] * nimages group_indexes = [1] last_group_number = group_numbers[0] group_index = 1 for group_number in group_numbers: if group_number == last_group_number: group_index += 1 else: group_index = 1 group_indexes.append(group_index) for i in range(1, nimages+1): filename = ("Channel2-%02d-%s-%02d.tif" % (i, "ABCDEFGH"[int((i-1) / 12)], ((i-1) % 12) + 1)) url = pathname2url(os.path.join(path, filename)) m[cpmeas.IMAGE, cpmeas.C_FILE_NAME + "_DNA", i] = filename m[cpmeas.IMAGE, cpmeas.C_PATH_NAME + "_DNA", i] = path m[cpmeas.IMAGE, cpmeas.C_URL+"_DNA", i] = url m[cpmeas.IMAGE, cpmeas.GROUP_NUMBER, i] = group_numbers[i-1] m[cpmeas.IMAGE, cpmeas.GROUP_INDEX, i] = group_indexes[i-1] jblob = J.run_script(""" importPackage(Packages.org.cellprofiler.imageset); importPackage(Packages.org.cellprofiler.imageset.filter); var imageFile=new ImageFile(new java.net.URI(url)); var imageFileDetails = new ImageFileDetails(imageFile); var imageSeries=new ImageSeries(imageFile, 0); var imageSeriesDetails = new ImageSeriesDetails(imageSeries, imageFileDetails); var imagePlane=new ImagePlane(imageSeries, 0, ImagePlane.ALWAYS_MONOCHROME); var ipd = new ImagePlaneDetails(imagePlane, imageSeriesDetails); var stack = ImagePlaneDetailsStack.makeMonochromeStack(ipd); var stacks = java.util.Collections.singletonList(stack); var keys = java.util.Collections.singletonList(imageNumber); var imageSet = new ImageSet(stacks, keys); imageSet.compress(java.util.Collections.singletonList("DNA"), null); """, dict(url=url, imageNumber = str(i))) blob = J.get_env().get_byte_array_elements(jblob) m[cpmeas.IMAGE, M_IMAGE_SET, i, blob.dtype] = blob pipeline = cpp.Pipeline() pipeline.loadtxt(StringIO(GOOD_PIPELINE)) pipeline.write_pipeline_measurement(m) return m
def set_current_image(imagej_obj): '''Set the currently active window imagej_obj - an ImagePlus to become the current image ''' javabridge.execute_runnable_in_main_thread(javabridge.run_script( """new java.lang.Runnable() { run:function() { var w = imp.getWindow(); if (w == null) { imp.show(); } else { Packages.ij.WindowManager.setCurrentWindow(w); } } } """, dict(imp=imagej_obj.o)), synchronous=True)
def createDisplay(self, name, dataset): '''Create a display that contains the given dataset''' # # Must be run on the gui thread # jcallable = J.run_script( """new java.util.concurrent.Callable() { call:function() { return displayService.createDisplay(name, dataset); } }; """, dict(displayService=self.o, name = name, dataset = dataset.o)) future = J.make_future_task(jcallable, fn_post_process = wrap_display) return J.execute_future_in_main_thread(future)
def get_current_image(): '''Get the WindowManager's current image returns a wrapped ImagePlus object ''' # # Run this on the UI thread so its thread context is the same # as the macro invocation # script = """ new java.util.concurrent.Callable() { call: function() { return Packages.ij.WindowManager.getCurrentImage(); } }; """ gci = javabridge.make_future_task(javabridge.run_script(script)) imageplus_obj = javabridge.execute_future_in_main_thread(gci) return imagej.imageplus.get_imageplus_wrapper(imageplus_obj)