def configure_resultproducer(self): """ Configures and returns the ResultProducer and PropertyPath as tuple. :return: producer and property path :rtype: tuple """ rproducer = javabridge.make_instance("weka/experiment/RandomSplitResultProducer", "()V") javabridge.call(rproducer, "setRandomizeData", "(Z)V", not self.preserve_order) javabridge.call(rproducer, "setTrainPercent", "(D)V", self.percentage) speval, classifier = self.configure_splitevaluator() javabridge.call(rproducer, "setSplitEvaluator", "(Lweka/experiment/SplitEvaluator;)V", speval) prop_path = javabridge.get_env().make_object_array( 2, javabridge.get_env().find_class("weka/experiment/PropertyNode")) cls = javabridge.get_env().find_class("weka/experiment/RandomSplitResultProducer") desc = javabridge.make_instance( "java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "splitEvaluator", cls) node = javabridge.make_instance( "weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V", speval, desc, cls) javabridge.get_env().set_object_array_element(prop_path, 0, node) cls = javabridge.get_env().get_object_class(speval) desc = javabridge.make_instance( "java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "classifier", cls) node = javabridge.make_instance( "weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V", javabridge.call(speval, "getClass", "()Ljava/lang/Class;"), desc, cls) javabridge.get_env().set_object_array_element(prop_path, 1, node) return rproducer, prop_path
def __init__(self, jobject=None, tag_id=None, tag_text=None, tags=None): """ Initializes the wrapper with the specified Java object or tags and either tag_id or tag_text. :param jobject: the java object to wrap :type jobject: JB_Object :param tag_id: the integer associated with the tag :type tag_id: int :param tag_text: the text associated with the tag :type tag_text: str :param tags: list of Tag objects or Tags wrapper object :type tags: list or Tags """ if isinstance(tags, Tags): tobj = tags.jobject else: tobj = tags if jobject is None: if tag_id is None: jobject = javabridge.make_instance( "weka/core/SelectedTag", "(Ljava/lang/String;[Lweka/core/Tag;)V", tag_text, tobj) else: jobject = javabridge.make_instance( "weka/core/SelectedTag", "(I[Lweka/core/Tag;)V", tag_id, tobj) else: self.enforce_type(jobject, "weka.core.SelectedTag") super(SelectedTag, self).__init__(jobject)
def test_09_03_set_field(self): class_name = "org/cellprofiler/javabridge/test/RealRect" o = javabridge.make_instance(class_name, "()V") test_cases = ( ("f_boolean", "Z", True), # <AK> added ("f_char", "C", "A"), ("f_byte", "B", 3), ("f_short", "S", 15), ("f_int", "I", 392), ("f_long", "J", -14), ("f_float", "F", 1.03), ("f_double", "D", -889.1), ("f_object", "Ljava/lang/Object;", javabridge.make_instance("java/lang/Integer", "(I)V", 15)), ("f_object", "Ljava/lang/Object;", None)) for field_name, signature, value in test_cases: javabridge.set_field(o, field_name, signature, value) v = javabridge.get_field(o, field_name, signature) if isinstance(value, float): self.assertAlmostEqual(v, value) elif isinstance(value, javabridge.JB_Object): self.assertTrue( javabridge.call(value, "equals", "(Ljava/lang/Object;)Z", v)) else: self.assertEqual(v, value)
def start_vm(args=None, class_path=None, max_heap_size=None, run_headless=False): """ Start the JVM via Javabridge. """ if class_path is None: class_path = get_java_class_path() # Start the JVM. javabridge.start_vm(args=args, class_path=class_path, max_heap_size=max_heap_size, run_headless=run_headless) # Suppress Java logging to stdout. java_stack = javabridge.make_instance('java/io/ByteArrayOutputStream', "()V") java_stack_ps = javabridge.make_instance('java/io/PrintStream', "(Ljava/io/OutputStream;)V", java_stack) javabridge.static_call('Ljava/lang/System;', "setErr", '(Ljava/io/PrintStream;)V', java_stack_ps) java_out = javabridge.make_instance('java/io/ByteArrayOutputStream', "()V") java_out_ps = javabridge.make_instance('java/io/PrintStream', "(Ljava/io/OutputStream;)V", java_out) javabridge.static_call('Ljava/lang/System;', "setOut", '(Ljava/io/PrintStream;)V', java_out_ps) javabridge.attach()
def configure_resultproducer(self): """ Configures and returns the ResultProducer and PropertyPath as tuple. :return: producer and property path :rtype: tuple """ rproducer = javabridge.make_instance("weka/experiment/CrossValidationResultProducer", "()V") javabridge.call(rproducer, "setNumFolds", "(I)V", self.folds) speval, classifier = self.configure_splitevaluator() javabridge.call(rproducer, "setSplitEvaluator", "(Lweka/experiment/SplitEvaluator;)V", speval) prop_path = javabridge.get_env().make_object_array( 2, javabridge.get_env().find_class("weka/experiment/PropertyNode")) cls = javabridge.get_env().find_class("weka/experiment/CrossValidationResultProducer") desc = javabridge.make_instance( "java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "splitEvaluator", cls) node = javabridge.make_instance( "weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V", speval, desc, cls) javabridge.get_env().set_object_array_element(prop_path, 0, node) cls = javabridge.get_env().get_object_class(speval) desc = javabridge.make_instance( "java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "classifier", cls) node = javabridge.make_instance( "weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V", javabridge.get_env().get_object_class(speval), desc, cls) javabridge.get_env().set_object_array_element(prop_path, 1, node) return rproducer, prop_path
def copy_instances(cls, dataset, from_row=None, num_rows=None): """ Creates a copy of the Instances. If either from_row or num_rows are None, then all of the data is being copied. :param dataset: the original dataset :type dataset: Instances :param from_row: the 0-based start index of the rows to copy :type from_row: int :param num_rows: the number of rows to copy :type num_rows: int :return: the copy of the data :rtype: Instances """ if from_row is None or num_rows is None: return Instances( javabridge.make_instance("weka/core/Instances", "(Lweka/core/Instances;)V", dataset.jobject)) else: dataset = cls.copy_instances(dataset) return Instances( javabridge.make_instance("weka/core/Instances", "(Lweka/core/Instances;II)V", dataset.jobject, from_row, num_rows))
def configure_resultproducer(self): """ Configures and returns the ResultProducer and PropertyPath as tuple. :return: producer and property path :rtype: tuple """ rproducer = javabridge.make_instance("weka/experiment/RandomSplitResultProducer", "()V") javabridge.call(rproducer, "setRandomizeData", "(Z)V", not self.preserve_order) javabridge.call(rproducer, "setTrainPercent", "(D)V", self.percentage) speval, classifier = self.configure_splitevaluator() javabridge.call(rproducer, "setSplitEvaluator", "(Lweka/experiment/SplitEvaluator;)V", speval) prop_path = javabridge.get_env().make_object_array( 2, javabridge.get_env().find_class("weka/experiment/PropertyNode")) cls = javabridge.get_env().find_class("weka/experiment/RandomSplitResultProducer") desc = javabridge.make_instance( "java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "splitEvaluator", cls) node = javabridge.make_instance( "weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V", speval, desc, cls) javabridge.get_env().set_object_array_element(prop_path, 0, node) cls = javabridge.get_env().get_object_class(speval) desc = javabridge.make_instance( "java/beans/PropertyDescriptor", "(Ljava/lang/String;Ljava/lang/Class;)V", "classifier", cls) node = javabridge.make_instance( "weka/experiment/PropertyNode", "(Ljava/lang/Object;Ljava/beans/PropertyDescriptor;Ljava/lang/Class;)V", javabridge.get_env().get_object_class(speval), desc, cls) javabridge.get_env().set_object_array_element(prop_path, 1, node) return rproducer, prop_path
def copy_instances(cls, dataset, from_row=None, num_rows=None): """ Creates a copy of the Instances. If either from_row or num_rows are None, then all of the data is being copied. :param dataset: the original dataset :type dataset: Instances :param from_row: the 0-based start index of the rows to copy :type from_row: int :param num_rows: the number of rows to copy :type num_rows: int :return: the copy of the data :rtype: Instances """ if from_row is None or num_rows is None: return Instances( javabridge.make_instance( "weka/core/Instances", "(Lweka/core/Instances;)V", dataset.jobject)) else: dataset = cls.copy_instances(dataset) return Instances( javabridge.make_instance( "weka/core/Instances", "(Lweka/core/Instances;II)V", dataset.jobject, from_row, num_rows))
def test_08_04_addAll(self): c1 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c2.add("Baz") c2.addAll(c1.o) self.assertIn("Foo", c2)
def test_08_09_removeAll(self): c1 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c2.add("Foo") c1.removeAll(c2) self.assertNotIn("Foo", c1)
def test_08_07_contains_all(self): c1 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c2.add("Baz") self.assertFalse(c2.containsAll(c1.o)) c2 += c1 self.assertTrue(c2.containsAll(c1.o))
def setup(self): """ Initializes the experiment. """ # basic options javabridge.call( self.jobject, "setPropertyArray", "(Ljava/lang/Object;)V", javabridge.get_env().make_object_array(0, javabridge.get_env().find_class("weka/classifiers/Classifier"))) javabridge.call( self.jobject, "setUsePropertyIterator", "(Z)V", True) javabridge.call( self.jobject, "setRunLower", "(I)V", 1) javabridge.call( self.jobject, "setRunUpper", "(I)V", self.runs) # setup result producer rproducer, prop_path = self.configure_resultproducer() javabridge.call( self.jobject, "setResultProducer", "(Lweka/experiment/ResultProducer;)V", rproducer) javabridge.call( self.jobject, "setPropertyPath", "([Lweka/experiment/PropertyNode;)V", prop_path) # classifiers classifiers = javabridge.get_env().make_object_array( len(self.classifiers), javabridge.get_env().find_class("weka/classifiers/Classifier")) for i, classifier in enumerate(self.classifiers): if type(classifier) is Classifier: javabridge.get_env().set_object_array_element( classifiers, i, classifier.jobject) else: javabridge.get_env().set_object_array_element( classifiers, i, from_commandline(classifier).jobject) javabridge.call( self.jobject, "setPropertyArray", "(Ljava/lang/Object;)V", classifiers) # datasets datasets = javabridge.make_instance("javax/swing/DefaultListModel", "()V") for dataset in self.datasets: f = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", dataset) javabridge.call(datasets, "addElement", "(Ljava/lang/Object;)V", f) javabridge.call( self.jobject, "setDatasets", "(Ljavax/swing/DefaultListModel;)V", datasets) # output file if str(self.result).lower().endswith(".arff"): rlistener = javabridge.make_instance("weka/experiment/InstancesResultListener", "()V") elif str(self.result).lower().endswith(".csv"): rlistener = javabridge.make_instance("weka/experiment/CSVResultListener", "()V") else: raise Exception("Unhandled output format for results: " + self.result) rfile = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", self.result) javabridge.call( rlistener, "setOutputFile", "(Ljava/io/File;)V", rfile) javabridge.call( self.jobject, "setResultListener", "(Lweka/experiment/ResultListener;)V", rlistener)
def test_01_02_make_instance(self): jobject = javabridge.make_instance("java/lang/Object", "()V") self.assertTrue( javabridge.to_string(jobject).startswith("java.lang.Object")) # <AK> added with self.assertRaisesRegex( javabridge.JavaError, 'Could not find constructor with signature = ' '"\(\)V"'): jobject = javabridge.make_instance("java/lang/Class", "()V")
def test_08_06__iadd__(self): c1 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c2.add("Baz") c2 += c1 for k in ("Foo", "Bar", "Baz"): self.assertIn(k, c2) c2 += ["Hello", "World"] self.assertIn("Hello", c2) self.assertIn("World", c2)
def send_to_java(prim_val): if isinstance(prim_val, str) or isinstance(prim_val,unicode): return javabridge.make_instance("java/lang/String", "(Ljava/lang/String;)V",prim_val) elif isinstance(prim_val, int): return javabridge.make_instance("java/lang/Integer", "(Ljava/lang/Integer;)V",prim_val) elif isinstance(prim_val, float): return javabridge.make_instance("java/lang/Double", "(Ljava/lang/Double;)V",prim_val) else: return prim_val
def configure_splitevaluator(self): """ Configures and returns the SplitEvaluator and Classifier instance as tuple. :return: evaluator and classifier :rtype: tuple """ if self.classification: speval = javabridge.make_instance("weka/experiment/ClassifierSplitEvaluator", "()V") else: speval = javabridge.make_instance("weka/experiment/RegressionSplitEvaluator", "()V") classifier = javabridge.call(speval, "getClassifier", "()Lweka/classifiers/Classifier;") return speval, classifier
def make_bit_img(shape): '''Make an imglib img of BitType with the given shape shape - a sequence of image dimensions ''' imgFactory = J.make_instance( "net/imglib2/img/planar/PlanarImgFactory", "()V") bit_type = J.make_instance("net/imglib2/type/logic/BitType", "()V") img = J.call( imgFactory, "create", "([JLnet/imglib2/type/NativeType;)Lnet/imglib2/img/planar/PlanarImg;", np.array(shape), bit_type) return img
def test_08_05__add__(self): c1 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") c2 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c2.add("Baz") c3 = c1 + c2 for k in ("Foo", "Bar", "Baz"): self.assertIn(k, c3) c4 = c3 + ["Hello", "World"] self.assertIn("Hello", c4) self.assertIn("World", c4)
def make_bit_img(shape): '''Make an imglib img of BitType with the given shape shape - a sequence of image dimensions ''' imgFactory = J.make_instance("net/imglib2/img/planar/PlanarImgFactory", "()V") bit_type = J.make_instance("net/imglib2/type/logic/BitType", "()V") img = J.call( imgFactory, "create", "([JLnet/imglib2/type/NativeType;)Lnet/imglib2/img/planar/PlanarImg;", np.array(shape), bit_type) return img
def create_sparse_instance(cls, values, max_values, classname="weka.core.SparseInstance", weight=1.0): """ Creates a new sparse instance. :param values: the list of tuples (0-based index and internal format float). The indices of the tuples must be in ascending order and "max_values" must be set to the maximum number of attributes in the dataset. :type values: list :param max_values: the maximum number of attributes :type max_values: int :param classname: the classname of the instance (eg weka.core.SparseInstance). :type classname: str :param weight: the weight of the instance :type weight: float """ jni_classname = classname.replace(".", "/") indices = [] vals = [] for (i, v) in values: indices.append(i) vals.append(float(v)) indices = numpy.array(indices, dtype=numpy.int32) vals = numpy.array(vals) return Instance( javabridge.make_instance( jni_classname, "(D[D[II)V", weight, javabridge.get_env().make_double_array(vals), javabridge.get_env().make_int_array(indices), max_values))
def getColorModel(color_space, has_alpha=False, is_alpha_premultiplied = False, transparency = OPAQUE, transfer_type = TYPE_BYTE): '''Return a java.awt.image.ColorModel color model color_space - a java.awt.color.ColorSpace such as returned by getGrayColorSpace or getRGBColorSpace has_alpha - True if alpha channel is specified is_alpha_premultiplied - True if other channel values have already been reduced by the alpha multiplier, False if the channel values are independent of the multiplier. transparency - one of BITMASK, OPAQUE or TRANSPARENT. transfer_type - one of TYPE_BYTE, TYPE_USHORT, TYPE_INT ''' jtransparency = jutil.get_static_field('java/awt/Transparency', transparency, 'I') jtransfer_type = jutil.get_static_field('java/awt/image/DataBuffer', transfer_type, 'I') return jutil.make_instance('java/awt/image/ComponentColorModel', '(Ljava/awt/color/ColorSpace;ZZII)V', color_space, has_alpha, is_alpha_premultiplied, jtransparency, jtransfer_type)
def prepare_run(self, workspace): '''Create an IPD for every url that passes the filter''' if workspace.pipeline.in_batch_mode(): return True file_list = workspace.pipeline.file_list if self.filter_choice != FILTER_CHOICE_NONE: if self.filter_choice == FILTER_CHOICE_IMAGES: expression = FILTER_DEFAULT else: expression = self.filter.value_text env = J.get_env() ifcls = J.class_for_name("org.cellprofiler.imageset.ImageFile") scls = env.find_class("java/lang/String") iffilter = J.make_instance( "org/cellprofiler/imageset/filter/Filter", "(Ljava/lang/String;Ljava/lang/Class;)V", expression, ifcls) file_array = env.make_object_array(len(file_list), scls) for i, url in enumerate(file_list): if isinstance(url, unicode): ourl = env.new_string(url) else: ourl = env.new_string_utf(url) env.set_object_array_element(file_array, i, ourl) passes_filter = J.call( iffilter, "filterURLs", "([Ljava/lang/String;)[Z", file_array) if isinstance(passes_filter, J.JB_Object): passes_filter = J.get_env().get_boolean_array_elements( passes_filter) file_list = [f for f, passes in zip(file_list, passes_filter) if passes] workspace.pipeline.set_filtered_file_list(file_list, self) return True
def install_package(pkge, version="Latest"): """ The list of packages to install. :param pkge: the name of the repository package, a URL (http/https) or a zip file :type pkge: str :param version: in case of the repository packages, the version :type version: str :return: whether successfully installed :rtype: bool """ establish_cache() if pkge.startswith("http://") or pkge.startswith("https://"): url = javabridge.make_instance( "java/net/URL", "(Ljava/lang/String;)V", javabridge.get_env().new_string_utf(pkge)) return not javabridge.static_call( "weka/core/WekaPackageManager", "installPackageFromURL", "(Ljava/net/URL;[Ljava/io/PrintStream;)Ljava/lang/String;", url, []) is None elif pkge.lower().endswith(".zip"): return not javabridge.static_call( "weka/core/WekaPackageManager", "installPackageFromArchive", "(Ljava/lang/String;[Ljava/io/PrintStream;)Ljava/lang/String;", pkge, []) is None else: return javabridge.static_call( "weka/core/WekaPackageManager", "installPackageFromRepository", "(Ljava/lang/String;Ljava/lang/String;[Ljava/io/PrintStream;)Z", pkge, version, [])
def __init__(self, datasets, classifiers, jobject=None, classification=True, runs=10, result=None): """ Initializes the experiment. :param datasets: the filenames of datasets to use in the experiment :type datasets: list :param classifiers: the Classifier objects or commandline strings to use in the experiment :type classifiers: list :param jobject: the Java Object to use :type jobject: JB_Object :param classification: whether to perform classification or regression :type classification:bool :param runs: the number of runs to perform :type runs: int :param result: the filename of the file to store the results in :type result: str """ if not jobject is None: self.enforce_type(jobject, "weka.experiment.Experiment") if jobject is None: jobject = javabridge.make_instance("weka/experiment/Experiment", "()V") self.classification = classification self.runs = runs self.datasets = datasets[:] self.classifiers = classifiers[:] self.result = result super(SimpleExperiment, self).__init__(jobject=jobject)
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.call(interp, "run", "(Ljava/lang/String;)V", macro_text)
def __init__(self): env = jutil.get_env() class_name = 'loci/formats/ImageReader' klass = env.find_class(class_name) base_klass = env.find_class('loci/formats/IFormatReader') self.o = jutil.make_instance( "loci/formats/ClassList", "(Ljava/lang/String;" "Ljava/lang/Class;" # base "Ljava/lang/Class;)V", # location in jar "readers.txt", base_klass, klass) problem_classes = [ # BDReader will read all .tif files in an experiment if it's # called to load a .tif. # 'loci.formats.in.BDReader', # # MRCReader will read .stk files which should be read # by MetamorphReader # 'loci.formats.in.MRCReader' ] for problem_class in problem_classes: # Move to back klass = jutil.class_for_name(problem_class) self.remove_class(klass) self.add_class(klass)
def __init__(self, jobject=None, index=None): """ Initializes the wrapper with the specified Java object or string index. :param jobject: the java object to wrap :type jobject: JB_Object :param index: the string index to use :type index: str """ if jobject is None: if index is None: jobject = javabridge.make_instance("weka/core/SingleIndex", "()V") else: jobject = javabridge.make_instance("weka/core/SingleIndex", "(Ljava/lang/String;)V", index) else: self.enforce_type(jobject, "weka.core.SingleIndex") super(SingleIndex, self).__init__(jobject)
def __init__(self, jobject=None, ranges=None): """ Initializes the wrapper with the specified Java object or string range. :param jobject: the java object to wrap :type jobject: JB_Object :param ranges: the string range to use :type ranges: str """ if jobject is None: if ranges is None: jobject = javabridge.make_instance("weka/core/Range", "()V") else: jobject = javabridge.make_instance("weka/core/Range", "(Ljava/lang/String;)V", ranges) else: self.enforce_type(jobject, "weka.core.Range") super(Range, self).__init__(jobject)
def __call__(self, *args): '''Constructors''' env = J.get_env() jconstructors = self.klass.getConstructors() for jconstructor in env.get_object_array_elements(jconstructors): constructor = J.get_constructor_wrapper(jconstructor) params = env.get_object_array_elements( constructor.getParameterTypes()) is_var_args = J.call(constructor.o, "isVarArgs", "()Z") if len(args) < len(params) - (1 if is_var_args else 0): continue if len(args) > len(params) and not is_var_args: continue if is_var_args: pm1 = len(params)-1 args1 = args[:pm1] + [args[pm1:]] else: args1 = args try: cargs = [cast(o, klass) for o, klass in zip(args1, params)] except: last_e = sys.exc_info()[1] continue args_sig = "".join(map(sig, params)) msig = "(%s)V" % (args_sig) result = J.make_instance(self.cname, msig, *cargs) result = JWrapper(result) return result raise TypeError("No matching constructor found")
def test_08_01_wrap_collection(self): c = javabridge.make_instance("java/util/HashSet", "()V") w = javabridge.get_collection_wrapper(c) self.assertFalse(hasattr(w, "addI")) self.assertEqual(w.size(), 0) self.assertEqual(len(w), 0) self.assertTrue(w.isEmpty())
def allowOpenToCheckType(self, allow): '''Allow the "isThisType" function to open files For the cluster, you want to tell potential file formats not to open the image file to test if it's their format. ''' if not hasattr(self, "allowOpenToCheckType_method"): self.allowOpenToCheckType_method = None class_wrapper = jutil.get_class_wrapper(self.o) methods = class_wrapper.getMethods() for method in jutil.get_env().get_object_array_elements( methods): m = jutil.get_method_wrapper(method) if m.getName() in ('allowOpenToCheckType', 'setAllowOpenFiles'): self.allowOpenToCheckType_method = m if self.allowOpenToCheckType_method is not None: object_class = env.find_class('java/lang/Object') jexception = jutil.get_env().exception_occurred() if jexception is not None: raise jutil.JavaException(jexception) boolean_value = jutil.make_instance('java/lang/Boolean', '(Z)V', allow) args = jutil.get_env().make_object_array(1, object_class) jexception = jutil.get_env().exception_occurred() if jexception is not None: raise jutil.JavaException(jexception) jutil.get_env().set_object_array_element( args, 0, boolean_value) jexception = jutil.get_env().exception_occurred() if jexception is not None: raise jutil.JavaException(jexception) self.allowOpenToCheckType_method.invoke(self.o, args)
def test_08_03_contains(self): c = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c.add("Foo") self.assertTrue(c.contains("Foo")) self.assertFalse(c.contains("Bar")) self.assertIn("Foo", c) self.assertNotIn("Bar", c)
def load_file(self, dfile, incremental=False): """ Loads the specified file and returns the Instances object. In case of incremental loading, only the structure. :param dfile: the file to load :type dfile: str :param incremental: whether to load the dataset incrementally :type incremental: bool :return: the full dataset or the header (if incremental) :rtype: Instances :raises Exception: if the file does not exist """ self.enforce_type(self.jobject, "weka.core.converters.FileSourcedConverter") self.incremental = incremental if not javabridge.is_instance_of(dfile, "Ljava/io/File;"): dfile = javabridge.make_instance( "Ljava/io/File;", "(Ljava/lang/String;)V", javabridge.get_env().new_string_utf(str(dfile))) javabridge.call(self.jobject, "reset", "()V") # check whether file exists, otherwise previously set file gets loaded again sfile = javabridge.to_string(dfile) if not os.path.exists(sfile): raise Exception("Dataset file does not exist: " + str(sfile)) javabridge.call(self.jobject, "setFile", "(Ljava/io/File;)V", dfile) if incremental: self.structure = Instances(javabridge.call(self.jobject, "getStructure", "()Lweka/core/Instances;")) return self.structure else: return Instances(javabridge.call(self.jobject, "getDataSet", "()Lweka/core/Instances;"))
def getColorModel(color_space, has_alpha=False, is_alpha_premultiplied=False, transparency=OPAQUE, transfer_type=TYPE_BYTE): '''Return a java.awt.image.ColorModel color model color_space - a java.awt.color.ColorSpace such as returned by getGrayColorSpace or getRGBColorSpace has_alpha - True if alpha channel is specified is_alpha_premultiplied - True if other channel values have already been reduced by the alpha multiplier, False if the channel values are independent of the multiplier. transparency - one of BITMASK, OPAQUE or TRANSPARENT. transfer_type - one of TYPE_BYTE, TYPE_USHORT, TYPE_INT ''' jtransparency = jutil.get_static_field('java/awt/Transparency', transparency, 'I') jtransfer_type = jutil.get_static_field('java/awt/image/DataBuffer', transfer_type, 'I') return jutil.make_instance('java/awt/image/ComponentColorModel', '(Ljava/awt/color/ColorSpace;ZZII)V', color_space, has_alpha, is_alpha_premultiplied, jtransparency, jtransfer_type)
def start_vm( args=None, class_path=None, max_heap_size=None, run_headless=False ): """ Start the JVM via Javabridge. """ if class_path is None: class_path = get_java_class_path() # Start the JVM. javabridge.start_vm( args=args, class_path=class_path, max_heap_size=max_heap_size, run_headless=run_headless ) # Suppress Java logging to stdout. java_stack = javabridge.make_instance( 'java/io/ByteArrayOutputStream', "()V" ) java_stack_ps = javabridge.make_instance( 'java/io/PrintStream', "(Ljava/io/OutputStream;)V", java_stack ) javabridge.static_call( 'Ljava/lang/System;', "setErr", '(Ljava/io/PrintStream;)V', java_stack_ps ) java_out = javabridge.make_instance( 'java/io/ByteArrayOutputStream', "()V" ) java_out_ps = javabridge.make_instance( 'java/io/PrintStream', "(Ljava/io/OutputStream;)V", java_out ) javabridge.static_call( 'Ljava/lang/System;', "setOut", '(Ljava/io/PrintStream;)V', java_out_ps ) javabridge.attach()
def load_imageplus(file_name): """Create an ImagePlus instance from a file :param file_name: """ imageplus_obj = J.make_instance('ij/ImagePlus', '(Ljava/lang/String;)V', file_name) return get_imageplus_wrapper(imageplus_obj)
def test_08_11_toArray(self): c1 = javabridge.get_collection_wrapper(javabridge.make_instance("java/util/HashSet", "()V")) c1.add("Foo") c1.add("Bar") result = [javabridge.to_string(x) for x in c1.toArray()] self.assertIn("Foo", result) self.assertIn("Bar", result)
def load_file(self, dfile, incremental=False): """ Loads the specified file and returns the Instances object. In case of incremental loading, only the structure. :param dfile: the file to load :type dfile: str :param incremental: whether to load the dataset incrementally :type incremental: bool :return: the full dataset or the header (if incremental) :rtype: Instances """ self.enforce_type(self.jobject, "weka.core.converters.FileSourcedConverter") self.incremental = incremental if not javabridge.is_instance_of(dfile, "Ljava/io/File;"): dfile = javabridge.make_instance( "Ljava/io/File;", "(Ljava/lang/String;)V", javabridge.get_env().new_string_utf(str(dfile))) javabridge.call(self.jobject, "reset", "()V") javabridge.call(self.jobject, "setFile", "(Ljava/io/File;)V", dfile) if incremental: self.structure = Instances( javabridge.call(self.jobject, "getStructure", "()Lweka/core/Instances;")) return self.structure else: return Instances( javabridge.call(self.jobject, "getDataSet", "()Lweka/core/Instances;"))
def deepcopy(obj): """ Creates a deep copy of the JavaObject (or derived class) or JB_Object. :param obj: the object to create a copy of :type obj: object :return: the copy, None if failed to copy :rtype: object """ if isinstance(obj, JavaObject): wrapped = True jobject = obj.jobject else: wrapped = False jobject = obj try: serialized = javabridge.make_instance("weka/core/SerializedObject", "(Ljava/lang/Object;)V", jobject) jcopy = javabridge.call(serialized, "getObject", "()Ljava/lang/Object;") if wrapped: jcopy = obj.__class__(jobject=jcopy) return jcopy except JavaException as e: print("Failed to create copy of " + classes.get_classname(obj) + ": " + str(e)) return None
def load_file(self, dfile, incremental=False): """ Loads the specified file and returns the Instances object. In case of incremental loading, only the structure. :param dfile: the file to load :type dfile: str :param incremental: whether to load the dataset incrementally :type incremental: bool :return: the full dataset or the header (if incremental) :rtype: Instances :raises Exception: if the file does not exist """ self.enforce_type(self.jobject, "weka.core.converters.FileSourcedConverter") self.incremental = incremental if not javabridge.is_instance_of(dfile, "Ljava/io/File;"): dfile = javabridge.make_instance( "Ljava/io/File;", "(Ljava/lang/String;)V", javabridge.get_env().new_string_utf(str(dfile))) javabridge.call(self.jobject, "reset", "()V") # check whether file exists, otherwise previously set file gets loaded again sfile = javabridge.to_string(dfile) if not os.path.exists(sfile): raise Exception("Dataset file does not exist: " + str(sfile)) javabridge.call(self.jobject, "setFile", "(Ljava/io/File;)V", dfile) if incremental: self.structure = Instances( javabridge.call(self.jobject, "getStructure", "()Lweka/core/Instances;")) return self.structure else: return Instances( javabridge.call(self.jobject, "getDataSet", "()Lweka/core/Instances;"))
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 prepare_run(self, workspace): '''Create an IPD for every url that passes the filter''' if workspace.pipeline.in_batch_mode(): return True file_list = workspace.pipeline.file_list if self.filter_choice != FILTER_CHOICE_NONE: if self.filter_choice == FILTER_CHOICE_IMAGES: expression = FILTER_DEFAULT else: expression = self.filter.value_text env = J.get_env() ifcls = J.class_for_name("org.cellprofiler.imageset.ImageFile") scls = env.find_class("java/lang/String") iffilter = J.make_instance( "org/cellprofiler/imageset/filter/Filter", "(Ljava/lang/String;Ljava/lang/Class;)V", expression, ifcls) file_array = env.make_object_array(len(file_list), scls) for i, url in enumerate(file_list): if isinstance(url, unicode): ourl = env.new_string(url) else: ourl = env.new_string_utf(url) env.set_object_array_element(file_array, i, ourl) passes_filter = J.call(iffilter, "filterURLs", "([Ljava/lang/String;)[Z", file_array) if isinstance(passes_filter, J.JB_Object): passes_filter = J.get_env().get_boolean_array_elements( passes_filter) file_list = [ f for f, passes in zip(file_list, passes_filter) if passes ] workspace.pipeline.set_filtered_file_list(file_list, self) return True
def __init__(self, base_class_name, d=None): '''Initialize the proxy with the interface name and methods :param base_class_name: the class name of the interface to implement in dotted form (e.g. java.lang.Runnable) :param d: an optional dictionary of method name to implementation ''' self.ref_id, self.ref = J.create_jref(self) self.__d = d or {} jclass = J.class_for_name(base_class_name) loader = J.call(jclass, "getClassLoader", "()Ljava/lang/ClassLoader;") env = J.get_env() classes = env.make_object_array(1, env.find_class("java/lang/Class")) env.set_object_array_element(classes, 0, jclass) handler = J.make_instance( "org/cellprofiler/javabridge/CPythonInvocationHandler", "(Ljava/lang/String;)V", self.ref_id) self.o = J.static_call( "java/lang/reflect/Proxy", "newProxyInstance", "(Ljava/lang/ClassLoader;" "[Ljava/lang/Class;" "Ljava/lang/reflect/InvocationHandler;)" "Ljava/lang/Object;", loader, classes, handler)
def __call__(self, *args): '''Constructors''' env = J.get_env() jconstructors = self.klass.getConstructors() for jconstructor in env.get_object_array_elements(jconstructors): constructor = J.get_constructor_wrapper(jconstructor) params = env.get_object_array_elements( constructor.getParameterTypes()) is_var_args = J.call(constructor.o, "isVarArgs", "()Z") if len(args) < len(params) - (1 if is_var_args else 0): continue if len(args) > len(params) and not is_var_args: continue if is_var_args: pm1 = len(params) - 1 args1 = args[:pm1] + [args[pm1:]] else: args1 = args try: cargs = [cast(o, klass) for o, klass in zip(args1, params)] except: last_e = sys.exc_info()[1] continue args_sig = "".join(map(sig, params)) msig = "(%s)V" % (args_sig) result = J.make_instance(self.cname, msig, *cargs) result = JWrapper(result) return result raise TypeError("No matching constructor found")
def __init__(self, seed): """ The seed value. :param seed: the seed value :type seed: int """ super(Random, self).__init__(javabridge.make_instance("Ljava/util/Random;", "(J)V", seed))