def test_01_04_call_varargs(self): sclass = J.JWrapper(J.class_for_name("java.lang.String")) for constructor in J.get_env().get_object_array_elements( sclass.getConstructors().o): wconstructor = J.JWrapper(constructor) parameter_types = J.get_env().get_object_array_elements( wconstructor.getParameterTypes().o) c1 = sclass.getConstructor(*parameter_types) self.assertTrue(c1.equals(constructor))
def test_01_01_init(self): def whatever(): pass proxy = J.JProxy('java.lang.Runnable', dict(run=whatever)) # <AK> added J.JWrapper(proxy.o).run()
def test_01_01_init(self): jobj = J.get_env().new_string(u"Hello, world.") obj = J.JWrapper(jobj) self.assertEquals(jobj, obj.o) # <AK> added self.assertEquals(repr(obj), "Instance of java.lang.String: Hello, world.")
def class_attribute(self): return javabridge.JWrapper( javabridge.call( self._class_attribute_field, "get", "(Ljava/lang/Object;)Ljava/lang/Object;", self.jwrapper, ))
def test_01_03_call_args(self): jobj = J.get_env().new_string(u"Hello, world.") obj = J.JWrapper(jobj) result = obj.replace("Hello,", "Goodbye cruel") self.assertEquals(result, "Goodbye cruel world.") # <AK> added with self.assertRaisesRegex(TypeError, "No matching method found for replace"): obj.replace()
def test_01_04_args(self): my_observable = J.make_instance("java/util/Observable", "()V") def update(observable, obj): self.assertTrue(J.JWrapper(observable).equals(my_observable)) self.assertTrue(J.JWrapper(obj).equals("bar")) proxy = J.JProxy('java.util.Observer', dict(update=update)) J.JWrapper(proxy.o).update(my_observable, "bar")
def test_01_02_runnable(self): magic = [] def whatever(magic=magic): magic.append("bus") runnable = J.JProxy('java.lang.Runnable', dict(run=whatever)) J.JWrapper(runnable.o).run() self.assertEqual(magic[0], "bus")
def get_decompounder(): """ Restarts the JVM with the decompounder. It is necessary once in a while. """ javabridge.start_vm( class_path=["tf/jwordsplitter/target/jwordsplitter-4.2-SNAPSHOT.jar"]) java_instance = javabridge.make_instance( "de/danielnaber/jwordsplitter/GermanWordSplitter", "(Z)V", False) decompounder = javabridge.JWrapper(java_instance) return decompounder
def get_java_metadata_store(imagefile): if not VM_STARTED: start_jvm() if VM_KILLED: jvm_error() # get the actual image reader rdr = bioformats.get_image_reader(None, path=imagefile) # for "whatever" reason the number of total series can only be accessed here ... try: totalseries = np.int(rdr.rdr.getSeriesCount()) except: totalseries = 1 # in case there is only ONE series try: for sc in range(0, totalseries): rdr.rdr.setSeries(sc) resolutioncount = rdr.rdr.getResolutionCount() print('Resolution count for series #', sc, ' = ' + resolutioncount) for res in range(0, resolutioncount): rdr.rdr.setResolution(res) print('Resolution #', res, ' dimensions = ', rdr.getSizeX(), ' x ', rdr.getSizeY()) except: print('Multi-Resolution API not enabled yet.') series_dimensions = [] # cycle through all the series and check the dimensions for sc in range(0, totalseries): rdr.rdr.setSeries(sc) dimx = rdr.rdr.getSizeX() dimy = rdr.rdr.getSizeY() series_dimensions.append((dimx, dimy)) if len(series_dimensions) == 1: multires = False elif len(series_dimensions) > 1: if len(set(series_dimensions)) > 1: multires = True elif len(set(series_dimensions)) == 1: multires = False # rdr.rdr is the actual BioFormats reader. rdr handles its lifetime javametadata = jv.JWrapper(rdr.rdr.getMetadataStore()) imagecount = javametadata.getImageCount() imageIDs = [] for id in range(0, imagecount): imageIDs.append(id) rdr.close() return javametadata, totalseries, imageIDs, series_dimensions, multires
def test_01_03_runnable_class(self): class MyProxy(J.JProxy): def __init__(self): J.JProxy.__init__(self, 'java.lang.Runnable') self.esteem = 0 def run(self): self.esteem = "through the roof" proxy = MyProxy() J.JWrapper(proxy.o).run() self.assertEqual(proxy.esteem, "through the roof")
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 __init__(self, path, heap_size=4): self.path = path self.filename = os.path.basename(self.path) self.heap_size = heap_size # GB javabridge.start_vm(class_path=javabridge.JARS + JARS,run_headless=True,max_heap_size=f'{self.heap_size}G') javabridge.attach() DebugTools = javabridge.JClassWrapper("loci.common.DebugTools") DebugTools.setRootLevel("OFF") self.rdr = _formatreader.ImageReader(self.path, perform_init=True) self.reader = self.rdr.rdr self.J = javabridge.JWrapper(self.reader.getMetadataStore()) self.ids = [] self.datas = []
def get_java_metadata_store(imagefile): if not VM_STARTED: start_jvm() if VM_KILLED: jvm_error() rdr = bioformats.get_image_reader(None, path=imagefile) # for "whatever" reason the number of total series can only be accessed here ... try: totalseries = np.int(rdr.rdr.getSeriesCount()) except: totalseries = 1 # in case there is only ONE series # rdr.rdr is the actual BioFormats reader. rdr handles its lifetime jmd = jv.JWrapper(rdr.rdr.getMetadataStore()) imagecount = jmd.getImageCount() IMAGEID = imagecount - 1 rdr.close() return jmd, totalseries, IMAGEID
def __init__(self, df, penaltydiscount=4, depth=3, faithfulness=True, verbose=False, java_max_heap_size=None): tetrad_libdir = os.path.join(os.path.dirname(__file__), 'lib') # print 'tetrad_libdir: %s' % tetrad_libdir for l in glob.glob(tetrad_libdir + os.sep + "*.jar"): javabridge.JARS.append(str(l)) javabridge.start_vm(run_headless=True, max_heap_size=java_max_heap_size) javabridge.attach() tetradData = None if (len(df.index) * df.columns.size <= 1500): node_list = javabridge.JWrapper( javabridge.make_instance("java/util/ArrayList", "()V")) for col in df.columns: nodname = javabridge.make_instance("java/lang/String", "(Ljava/lang/String;)V", col) nodi = javabridge.make_instance( "edu/cmu/tetrad/graph/GraphNode", "(Ljava/lang/String;)V", nodname) node_list.add(nodi) tetradMatrix = javabridge.JWrapper( javabridge.make_instance("edu/cmu/tetrad/util/TetradMatrix", "(II)V", len(df.index), df.columns.size)) for row in df.index: for col in range(0, df.columns.size): tetradMatrix.set(row, col, df.ix[row][col]) tetradData = javabridge.static_call( "edu/cmu/tetrad/data/ColtDataSet", "makeContinuousData", "(Ljava/util/List;Ledu/cmu/tetrad/util/TetradMatrix;)Ledu/cmu/tetrad/data/DataSet;", node_list, tetradMatrix) else: #Generate random name temp_data_file = ''.join( random.choice(string.lowercase) for i in range(10)) + '.csv' temp_data_path = os.path.join(tempfile.gettempdir(), temp_data_file) df.to_csv(temp_data_path, sep="\t") f = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", temp_data_path) excludeVar = javabridge.JWrapper( javabridge.make_instance("java/util/HashSet", "()V")) excludeVar.add("MULT") tetradData = javabridge.static_call( "edu/cmu/tetrad/data/BigDataSetUtility", "readInContinuousData", "(Ljava/io/File;CLjava/util/Set;)Ledu/cmu/tetrad/data/DataSet;", f, "\t", excludeVar) os.remove(temp_data_path) fgs = javabridge.make_instance("edu/cmu/tetrad/search/Fgs", "(Ledu/cmu/tetrad/data/DataSet;)V", tetradData) fgs = javabridge.JWrapper(fgs) fgs.setPenaltyDiscount( penaltydiscount ) # set to 2 if variable# <= 50 otherwise set it to 4 fgs.setDepth(depth) #-1 fgs.setNumPatternsToStore(0) fgs.setFaithfulnessAssumed(faithfulness) fgs.setVerbose(verbose) tetradGraph = fgs.search() graph = pydot.Dot(graph_type='digraph') n = tetradGraph.getNodeNames().toString() n = n[1:len(n) - 1] n = n.split(",") nodes = [] for i in range(0, len(n)): node = n[i] n[i] = node.strip() nodes.append(pydot.Node(n[i])) graph.add_node(nodes[i]) self.nodes = n e = tetradGraph.getEdges().toString() e = e[1:len(e) - 1] e = e.split(",") for i in range(0, len(e)): e[i] = e[i].strip() token = e[i].split(" ") if (len(token) == 3): src = token[0] arc = token[1] dst = token[2] if (pycausal.isNodeExisting(n, src) and pycausal.isNodeExisting(n, dst)): edge = pydot.Edge(nodes[n.index(src)], nodes[n.index(dst)]) if (arc == "---"): edge.set_arrowhead("none") graph.add_edge(edge) self.edges = e javabridge.detach() javabridge.kill_vm() self.graph = graph
def save_to_ome(input_file_path, output_file_path='', file_name_for_metadata=None, resolutions=np.array([]), units=np.array([]), pixel_type='float', logging_level='INFO', bioformats_logging='OFF'): """ :param input_file_path: Input NPY file. Expected XYZCT 5-D data. :param output_file_path: /path/to/output.ome Can be OME or OMETIFF. By default: Input file name with changed extension. :param file_name_for_metadata: Will copy the metadata info of this file to the output file :param resolutions: Pixel physical size can be inserted here :param units: Pixel physical size units :param pixel_type: Pixel type :param logging_level: level of logging: DEBUG, INFO, WARNING, ERROR :param bioformats_logging: Bioformats logging level :return: """ dir_data = os.path.dirname(input_file_path) filename = os.path.basename(input_file_path) logging.basicConfig(filename=os.path.join(dir_data, 'loci_writer.log'), level=logging_level) if output_file_path == '': output_file_path = os.path.join(dir_data, filename[:filename.find(".")] + '.ome') logging.info('Saving to {} ...'.format(output_file_path)) loci_logging(bioformats_logging) image5d = np.load(input_file_path) image_writer = bioformats.formatwriter.make_image_writer_class() writer = image_writer() if file_name_for_metadata is not None: rdr = bioformats.ImageReader(file_name_for_metadata, perform_init=True) jmd = javabridge.JWrapper(rdr.rdr.getMetadataStore()) pixel_type = jmd.getPixelsType(0).getValue() omexml = ome.OMEXML() omexml.image(0).Name = os.path.split(output_file_path)[1] p = omexml.image(0).Pixels assert isinstance(p, ome.OMEXML.Pixels) p.node.set("PhysicalSizeX", str(jmd.getPixelsPhysicalSizeX(0).value())) p.node.set("PhysicalSizeY", str(jmd.getPixelsPhysicalSizeY(0).value())) p.node.set("PhysicalSizeZ", str(jmd.getPixelsPhysicalSizeZ(0).value())) p.node.set("PhysicalSizeXUnit", jmd.getPixelsPhysicalSizeX(0).unit().getSymbol()) p.node.set("PhysicalSizeYUnit", jmd.getPixelsPhysicalSizeY(0).unit().getSymbol()) p.node.set("PhysicalSizeZUnit", jmd.getPixelsPhysicalSizeZ(0).unit().getSymbol()) p.SizeX = image5d.shape[1] p.SizeY = image5d.shape[0] p.SizeC = image5d.shape[3] p.SizeT = image5d.shape[4] p.SizeZ = image5d.shape[2] p.PixelType = pixel_type else: resolutions = np.array(resolutions) units = np.array(units) omexml = ome.OMEXML() omexml.image(0).Name = os.path.split(output_file_path)[1] p = omexml.image(0).Pixels assert isinstance(p, ome.OMEXML.Pixels) if resolutions.size: rx, ry, rz = resolutions p.node.set("PhysicalSizeX", str(rx)) p.node.set("PhysicalSizeY", str(ry)) p.node.set("PhysicalSizeZ", str(rz)) if units.size: ux, uy, uz = units p.node.set("PhysicalSizeXUnit", ux) p.node.set("PhysicalSizeYUnit", uy) p.node.set("PhysicalSizeZUnit", uz) p.SizeX = image5d.shape[1] p.SizeY = image5d.shape[0] p.SizeC = image5d.shape[3] p.SizeZ = image5d.shape[2] p.SizeT = image5d.shape[4] p.PixelType = pixel_type p.channel_count = image5d.shape[3] xml = omexml.to_xml() script = """ importClass(Packages.loci.formats.services.OMEXMLService, Packages.loci.common.services.ServiceFactory, Packages.loci.formats.MetadataTools, Packages.loci.formats.meta.IMetadata); service = new ServiceFactory().getInstance(OMEXMLService); metadata = service.createOMEXMLMetadata(xml); """ meta = javabridge.run_script(script, dict(xml=xml)) if os.path.isfile(output_file_path): os.remove(output_file_path) writer.setMetadataRetrieve(meta) writer.setId(output_file_path) nz, nc, nt = image5d.shape[2:] for t in range(nt): logging.debug('Saving frame {} ...'.format(t)) for c in range(nc): for z in range(nz): index = z + nz * c + nz * nc * t save_im = bioformats.formatwriter.convert_pixels_to_buffer( image5d[..., z, c, t], p.PixelType) writer.saveBytesIB(index, save_im) writer.close() logging.info('File {} successfully saved.'.format(output_file_path))
def test_01_03_call_args(self): jobj = J.get_env().new_string(u"Hello, world.") obj = J.JWrapper(jobj) result = obj.replace("Hello,", "Goodbye cruel") self.assertEquals(result, "Goodbye cruel world.")
def test_01_02_call_noargs(self): jobj = J.get_env().new_string(u"Hello, world.") obj = J.JWrapper(jobj) self.assertEquals(obj.toLowerCase(), "hello, world.")
def test_01_01_init(self): jobj = J.get_env().new_string(u"Hello, world.") obj = J.JWrapper(jobj) self.assertEquals(jobj, obj.o)
def test_01_05_return_value(self): def call(): return "foo" proxy = J.JProxy('java.util.concurrent.Callable', dict(call=call)) self.assertEquals(J.JWrapper(proxy.o).call(), "foo")
def update(observable, obj): self.assertTrue(J.JWrapper(observable).equals(my_observable)) self.assertTrue(J.JWrapper(obj).equals("bar"))
def main(args): javabridge.activate_awt() cpython = javabridge.make_instance( "org/cellprofiler/javabridge/CPython", "()V") script = """ //-------------------------------------- // // The anonymous callable runs on the thread // that started Java - that's the rule with AWT. // // The callable returns a Java Map whose keys // have the labels of objects like "qUp" for // the upward queue. Python can then fetch // whichever ones it wants and do Java stuff // with them. // //-------------------------------------- new java.util.concurrent.Callable() { call: function() { importClass(javax.swing.SpringLayout); importClass(javax.swing.JFrame); importClass(javax.swing.JTextField); importClass(javax.swing.JButton); importClass(javax.swing.JScrollPane); importClass(javax.swing.JTextArea); importClass(java.util.Hashtable); importClass(java.util.ArrayList); importClass(java.util.concurrent.CountDownLatch); importClass(java.awt.event.ActionListener); importClass(java.awt.event.WindowAdapter); d = new Hashtable(); signal = new CountDownLatch(1); d.put("signal", signal); frame = new JFrame("Callbacks in Java"); d.put("frame", frame); contentPane = frame.getContentPane(); layout = new SpringLayout(); contentPane.setLayout(layout); textField = new JTextField("'Hello, world.'", 60); d.put("textField", textField); contentPane.add(textField); execButton = new JButton("Exec"); contentPane.add(execButton); evalButton = new JButton("Eval"); contentPane.add(evalButton); result = new JTextArea("None"); scrollPane = new JScrollPane(result) contentPane.add(scrollPane); d.put("result", result); //----------------------------------------------------- // // The layout is: // // [ textField] [execButton] [evalButton] // [ scrollPane ] // //----------------------------------------------------- layout.putConstraint(SpringLayout.WEST, textField, 5, SpringLayout.WEST, contentPane); layout.putConstraint(SpringLayout.NORTH, textField, 5, SpringLayout.NORTH, contentPane); layout.putConstraint(SpringLayout.WEST, execButton, 5, SpringLayout.EAST, textField); layout.putConstraint(SpringLayout.NORTH, execButton, 0, SpringLayout.NORTH, textField); layout.putConstraint(SpringLayout.WEST, evalButton, 5, SpringLayout.EAST, execButton); layout.putConstraint(SpringLayout.NORTH, evalButton, 0, SpringLayout.NORTH, textField); layout.putConstraint(SpringLayout.NORTH, scrollPane, 5, SpringLayout.SOUTH, textField); layout.putConstraint(SpringLayout.WEST, scrollPane, 0, SpringLayout.WEST, textField); layout.putConstraint(SpringLayout.EAST, scrollPane, 0, SpringLayout.EAST, evalButton); layout.putConstraint(SpringLayout.EAST, contentPane, 5, SpringLayout.EAST, evalButton); layout.putConstraint(SpringLayout.SOUTH, contentPane, 20, SpringLayout.SOUTH, scrollPane); //----------------------------------------------- // // Create an action listener that binds the execButton // action to a function that instructs Python to // execute the contents of the text field. // //----------------------------------------------- alExec = new ActionListener() { actionPerformed: function(e) { try { cpython.exec(textField.getText()); result.setText("OK"); } catch(err) { result.setText(err.message); } } }; execButton.addActionListener(alExec); //----------------------------------------------- // // Create an action listener that binds the evalButton // action to a function that instructs Python to // evaluate the contents of the text field. // //----------------------------------------------- alEval = new ActionListener() { actionPerformed: function(e) { try { locals = new Hashtable(); jresult = new ArrayList(); locals.put("script", textField.getText()); locals.put("jresult", jresult); script = "import javabridge\\n" + "result=eval(javabridge.to_string(script))\\n" + "jwresult=javabridge.JWrapper(jresult)\\n" + "jwresult.add(str(result))" cpython.exec(script, locals, null); result.setText(jresult.get(0)); } catch(err) { result.setText(err.message); } } }; evalButton.addActionListener(alEval); //----------------------------------------------- // // Create a window listener that binds the frame's // windowClosing action to a function that instructs // Python to exit. // //----------------------------------------------- wl = new WindowAdapter() { windowClosing: function(e) { signal.countDown(); } }; frame.addWindowListener(wl); frame.pack(); frame.setVisible(true); return d; } };""" c = javabridge.run_script(script, dict(cpython=cpython)); f = javabridge.make_future_task(c) d = javabridge.execute_future_in_main_thread(f); d = javabridge.get_map_wrapper(d) frame = javabridge.JWrapper(d["frame"]) signal = javabridge.JWrapper(d["signal"]); signal.await(); frame.dispose();
def image_info(image): ''' Extract interesting metadata from a sincle image (not to use with batch). Returns ----- Dict with different parameters. ''' if JVM_BEGIN == False: begin_javabridge() if JVM_END == True: raise RuntimeError("The java virtual Machine has already ended" "you should restart the program") else: with bioformats.ImageReader(image) as rdr: jmd = javabridge.JWrapper(rdr.rdr.getMetadataStore()) if jmd.getPixelsTimeIncrement(0) == None: time_interval = None else: time_interval = javabridge.run_script( 'java.lang.Integer(test)', bindings_in=dict(test=jmd.getPixelsSizeT(0))) if jmd.getPixelsPhysicalSizeX(0) == None: xsize = None else: xsize = javabridge.run_script( 'java.lang.Double(test)', bindings_in=dict(test=jmd.getPixelsPhysicalSizeX(0))) if jmd.getPixelsSizeC(0) == None: channels = None else: channels = javabridge.run_script( 'java.lang.Integer(test)', bindings_in=dict(test=jmd.getPixelsSizeC(0))) if jmd.getPixelsSizeT(0) == None: time_frames = None else: time_frames = javabridge.run_script( 'java.lang.Integer(test)', bindings_in=dict(test=jmd.getPixelsSizeT(0))) if jmd.getPixelsSizeZ(0) == None: z_steps = None else: z_steps = javabridge.run_script( 'java.lang.Integer(test)', bindings_in=dict(test=jmd.getPixelsSizeZ(0))) if jmd.getPixelsPhysicalSizeZ(0) == None: z_step_size = None else: z_step_size = javabridge.run_script( 'java.lang.Double(test)', bindings_in=dict(test=jmd.getPixelsPhysicalSizeZ(0))) if jmd.getPixelsSizeX(0) == None: frame_size_x = None else: frame_size_x = javabridge.run_script( 'java.lang.Double(test)', bindings_in=dict(test=jmd.getPixelsSizeX(0))) if jmd.getPixelsSizeY(0) == None: frame_size_y = None else: frame_size_y = javabridge.run_script( 'java.lang.Double(test)', bindings_in=dict(test=jmd.getPixelsSizeY(0))) return { "xsize": xsize, "channels": channels, "time_frames": time_frames, "time_interval": time_interval, "z_steps": z_steps, "z_step_size": z_step_size, "frame_size_x": frame_size_x, "frame_size_y": frame_size_y }
#!/usr/bin/env python3 import os import javabridge from common import jar_path javabridge.start_vm(run_headless=True, class_path=javabridge.JARS + [jar_path]) try: # Bind a Java variable and run a script that uses it. print( javabridge.run_script( 'java.lang.String.format("Hello, %s!", greetee);', dict(greetee="world"))) # Wrap a Java object and call some of its methods. array_list = javabridge.JWrapper( javabridge.make_instance("java/util/ArrayList", "()V")) array_list.add("ArrayList item 1") array_list.add("ArrayList item 2") print("ArrayList size:", array_list.size()) print("First ArrayList item:", array_list.get(0)) # Wrap a Java object from our jar and call a method. main1 = javabridge.JWrapper( javabridge.make_instance("net/talvi/pythonjavabridgedemos/Main", "(Ljava/lang/String;)V", "Alice")) print(main1.greet("Hello")) # Wrap a Java object using JClassWrapper (no signature required) main2 = javabridge.JClassWrapper("net.talvi.pythonjavabridgedemos.Main")( "Bob") print(main2.greet("Hi there"))