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 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 init_logger(): rootLoggerName = javabridge.get_static_field("org/slf4j/Logger", "ROOT_LOGGER_NAME", "Ljava/lang/String;") rootLogger = javabridge.static_call("org/slf4j/LoggerFactory", "getLogger", "(Ljava/lang/String;)Lorg/slf4j/Logger;", rootLoggerName) logLevel = javabridge.get_static_field("ch/qos/logback/classic/Level", "WARN", "Lch/qos/logback/classic/Level;") javabridge.call(rootLogger, "setLevel", "(Lch/qos/logback/classic/Level;)V", logLevel)
def __init__(self, tetradGraph, dfs, dataType='continuous', numCategoriesToDiscretize=4, rule='R1', score='andersonDarling', alpha=0.01, epsilon=1.0, zeta=0.0, orientStrongerDirection=False, r2Orient2Cycles=True, edgeCorrected=False, selfLoopStrength=1.0): datasets = javabridge.JClassWrapper('java.util.ArrayList')() pc = self.pc for idx in range(len(dfs)): df = dfs[idx] tetradData = None # Continuous if dataType == 'continuous': tetradData = pc.loadContinuousData(df, outputDataset=True) # Discrete elif dataType == 'discrete': tetradData = pc.loadDiscreteData(df) # Mixed else: tetradData = pc.loadMixedData(df, numCategoriesToDiscretize) datasets.add(tetradData) lofs2 = javabridge.JClassWrapper('edu.cmu.tetrad.search.Lofs2')( tetradGraph, datasets) rule = javabridge.get_static_field( 'edu/cmu/tetrad/search/Lofs2$Rule', rule, 'Ledu/cmu/tetrad/search/Lofs2$Rule;') score = javabridge.get_static_field( 'edu/cmu/tetrad/search/Lofs$Score', score, 'Ledu/cmu/tetrad/search/Lofs$Score;') lofs2.setRule(rule) lofs2.setScore(score) lofs2.setAlpha(alpha) lofs2.setEpsilon(epsilon) lofs2.setZeta(zeta) lofs2.setOrientStrongerDirection(orientStrongerDirection) lofs2.setR2Orient2Cycles(r2Orient2Cycles) lofs2.setEdgeCorrected(edgeCorrected) lofs2.setSelfLoopStrength(selfLoopStrength) self.tetradGraph = lofs2.orient() self.nodes = pc.extractTetradGraphNodes(self.tetradGraph) self.edges = pc.extractTetradGraphEdges(self.tetradGraph)
class ModuleItem(object): def __init__(self): self.o = instance IV_NORMAL = J.get_static_field("org/scijava/ItemVisibility", "NORMAL", "Lorg/scijava/ItemVisibility;") IV_TRANSIENT = J.get_static_field("org/scijava/ItemVisibility", "TRANSIENT", "Lorg/scijava/ItemVisibility;") IV_INVISIBLE = J.get_static_field("org/scijava/ItemVisibility", "INVISIBLE", "Lorg/scijava/ItemVisibility;") IV_MESSAGE = J.get_static_field("org/scijava/ItemVisibility", "MESSAGE", "Lorg/scijava/ItemVisibility;") def getType(self): jtype = J.call(self.o, "getType", "()Ljava/lang/Class;") type_name = J.call(jtype, "getCanonicalName", "()Ljava/lang/String;") if field_mapping.has_key(type_name): return field_mapping[type_name] for class_instance, result in field_class_mapping(): if J.call(class_instance, "isAssignableFrom", "(Ljava/lang/Class;)Z", jtype): return result return None getWidgetStyle = J.make_method("getWidgetStyle", "()Ljava/lang/String;") getMinimumValue = J.make_method("getMinimumValue", "()Ljava/lang/Object;") getMaximumValue = J.make_method("getMaximumValue", "()Ljava/lang/Object;") getStepSize = J.make_method("getStepSize", "()Ljava/lang/Number;") getColumnCount = J.make_method("getColumnCount", "()I") getChoices = J.make_method("getChoices", "()Ljava/util/List;") getValue = J.make_method("getValue", "(Lorg/scijava/module/Module;)Ljava/lang/Object;") setValue = J.make_method( "setValue", "(Lorg/scijava/module/Module;Ljava/lang/Object;)V", "Set the value associated with this item on the module") getName = J.make_method("getName", "()Ljava/lang/String;") getLabel = J.make_method("getLabel", "()Ljava/lang/String;") getDescription = J.make_method("getDescription", "()Ljava/lang/String;") loadValue = J.make_method("loadValue", "()Ljava/lang/Object;") isInput = J.make_method("isInput", "()Z") isOutput = J.make_method("isOutput", "()Z") isRequired = J.make_method("isRequired", "()Z") initialize = J.make_method("initialize", "(Lorg/scijava/module/Module;)V")
def __getattr__(self, name): try: jfield = self.klass.getField(name) except: raise AttributeError("Could not find field %s" % name) STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") if (J.call(jfield, "getModifiers", "()I") & STATIC) != STATIC: raise AttributeError("Field %s is not static" % name) klass = J.call(jfield, "getType", "()Ljava/lang/Class;") result = J.get_static_field(self.cname, name, sig(klass)) if isinstance(result, J.JB_Object): result = JWrapper(result) return result
def init_vm(): javabridge.start_vm(class_path=bioformats.JARS) #remove annoying logs myloglevel = "ERROR" # user string argument for logLevel. rootLoggerName = javabridge.get_static_field("org/slf4j/Logger", "ROOT_LOGGER_NAME", "Ljava/lang/String;") rootLogger = javabridge.static_call( "org/slf4j/LoggerFactory", "getLogger", "(Ljava/lang/String;)Lorg/slf4j/Logger;", rootLoggerName) logLevel = javabridge.get_static_field("ch/qos/logback/classic/Level", myloglevel, "Lch/qos/logback/classic/Level;") javabridge.call(rootLogger, "setLevel", "(Lch/qos/logback/classic/Level;)V", logLevel)
def test_03_08_cw_get_field(self): c = javabridge.get_class_wrapper('java.lang.String') field = c.getField('CASE_INSENSITIVE_ORDER') modifiers = javabridge.call(field, 'getModifiers', '()I') static = javabridge.get_static_field('java/lang/reflect/Modifier', 'STATIC', 'I') self.assertEqual((modifiers & static), static)
def __init__(self, o): '''Initialize the JWrapper with a Java object :param o: a Java object (class = JB_Object) ''' STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") self.o = o self.class_wrapper = J.get_class_wrapper(o) env = J.get_env() methods = env.get_object_array_elements( self.class_wrapper.getMethods()) self.methods = {} for jmethod in methods: if (J.call(jmethod, "getModifiers", "()I") & STATIC) == STATIC: continue method = J.get_method_wrapper(jmethod) name = method.getName() if name not in self.methods: self.methods[name] = [] fn = lambda naame=name: lambda *args: self.__call(naame, *args) fn = fn() fn.__doc__ = J.to_string(jmethod) setattr(self, name, fn) else: fn = getattr(self, name) fn.__doc__ = fn.__doc__ + "\n" + J.to_string(jmethod) self.methods[name].append(method) jfields = self.class_wrapper.getFields() fields = env.get_object_array_elements(jfields)
def __init__(self, class_name): '''Initialize to wrap a class name :param class_name: name of class in dotted form, e.g. java.lang.Integer ''' STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") self.cname = class_name.replace(".", "/") self.klass = J.get_class_wrapper(J.class_for_name(class_name), True) self.static_methods = {} methods = env.get_object_array_elements(self.klass.getMethods()) self.methods = {} for jmethod in methods: if (J.call(jmethod, "getModifiers", "()I") & STATIC) != STATIC: continue method = J.get_method_wrapper(jmethod) name = method.getName() if name not in self.methods: self.methods[name] = [] fn = lambda naame=name: lambda *args: self.__call_static( naame, *args) fn = fn() fn.__doc__ = J.to_string(jmethod) setattr(self, name, fn) else: fn = getattr(self, name) fn.__doc__ = fn.__doc__ + "\n" + J.to_string(jmethod) self.methods[name].append(method)
def start_jvm(): javabridge.start_vm(class_path=bioformats.JARS) log_level = 'ERROR' # reduce log level rootLoggerName = javabridge.get_static_field("org/slf4j/Logger", "ROOT_LOGGER_NAME", "Ljava/lang/String;") rootLogger = javabridge.static_call( "org/slf4j/LoggerFactory", "getLogger", "(Ljava/lang/String;)Lorg/slf4j/Logger;", rootLoggerName) logLevel = javabridge.get_static_field("ch/qos/logback/classic/Level", log_level, "Lch/qos/logback/classic/Level;") javabridge.call(rootLogger, "setLevel", "(Lch/qos/logback/classic/Level;)V", logLevel)
def test_01_05_03_set_static_field(self): class_name = "org/cellprofiler/javabridge/test/RealRect" test_cases = ( ("fs_boolean", "Z", True), # <AK> added ("fs_char", "C", "A"), ("fs_byte", "B", 3), ("fs_short", "S", 15), ("fs_int", "I", 392), ("fs_long", "J", -14), ("fs_float", "F", 1.03), ("fs_double", "D", -889.1), ("fs_object", "Ljava/lang/Object;", javabridge.make_instance("java/lang/Integer", "(I)V", 15)), ("fs_object", "Ljava/lang/Object;", None)) for field_name, signature, value in test_cases: javabridge.set_static_field(class_name, field_name, signature, value) v = javabridge.get_static_field(class_name, 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 __init__(self, class_name): '''Initialize to wrap a class name :param class_name: name of class in dotted form, e.g. java.lang.Integer ''' STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") self.cname = class_name.replace(".", "/") self.klass = J.get_class_wrapper(J.class_for_name(class_name), True) self.static_methods = {} env = J.get_env() jmethods = env.get_object_array_elements(self.klass.getMethods()) methods = {} for jmethod in jmethods: if (J.call(jmethod, "getModifiers", "()I") & STATIC) != STATIC: continue method = J.get_method_wrapper(jmethod) name = method.getName() if name not in methods: methods[name] = [] fn = lambda naame=name: lambda *args: self.__call_static(naame, *args) fn = fn() fn.__doc__ = J.to_string(jmethod) setattr(self, name, fn) else: fn = getattr(self, name) fn.__doc__ = fn.__doc__ +"\n"+J.to_string(jmethod) methods[name].append(method) self.methods = methods
def loadDiscreteData(self, df): tetradData = None if (len(df.index) * df.columns.size <= 1500): dataBox = javabridge.JClassWrapper( 'edu.cmu.tetrad.data.VerticalIntDataBox')(len(df.index), df.columns.size) node_list = javabridge.JClassWrapper('java.util.ArrayList')() col_no = 0 for col in df.columns: cat_array = sorted(set(df[col])) cat_list = javabridge.JClassWrapper('java.util.ArrayList')() for cat in cat_array: cat = str(cat) cat_list.add(cat) nodname = javabridge.JClassWrapper('java.lang.String')(col) nodi = javabridge.JClassWrapper( 'edu.cmu.tetrad.data.DiscreteVariable')(nodname, cat_list) node_list.add(nodi) for row in df.index: value = javabridge.JClassWrapper('java.lang.Integer')( cat_array.index(df.iloc[row, col_no])) dataBox.set(row, col_no, value) col_no = col_no + 1 tetradData = javabridge.JClassWrapper( 'edu.cmu.tetrad.data.BoxDataSet')(dataBox, node_list) else: # Generate random name temp_data_file = ''.join( random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) + '.csv' temp_data_path = os.path.join(tempfile.gettempdir(), temp_data_file) df.to_csv(temp_data_path, sep="\t", index=False) # Read Data from File f = javabridge.JClassWrapper('java.io.File')(temp_data_path) delimiter = javabridge.get_static_field( 'edu/pitt/dbmi/data/Delimiter', 'TAB', 'Ledu/pitt/dbmi/data/Delimiter;') dataReader = javabridge.JClassWrapper( 'edu.pitt.dbmi.data.reader.tabular.VerticalDiscreteTabularDataReader' )(f, delimiter) tetradData = dataReader.readInData() tetradData = javabridge.static_call( 'edu/cmu/tetrad/util/DataConvertUtils', 'toDataModel', '(Ledu/pitt/dbmi/data/Dataset;)Ledu/cmu/tetrad/data/DataModel;', tetradData) os.remove(temp_data_path) return tetradData
def __init__(self, o): '''Initialize the JWrapper with a Java object :param o: a Java object (class = JB_Object) ''' STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") self.o = o self.class_wrapper = J.get_class_wrapper(o) env = J.get_env() jmethods = env.get_object_array_elements(self.class_wrapper.getMethods()) methods = {} for jmethod in jmethods: if (J.call(jmethod, "getModifiers", "()I") & STATIC) == STATIC: continue method = J.get_method_wrapper(jmethod) name = method.getName() if name not in methods: methods[name] = [] fn = lambda naame=name: lambda *args: self.__call(naame, *args) fn = fn() fn.__doc__ = J.to_string(jmethod) setattr(self, name, fn) else: fn = getattr(self, name) fn.__doc__ = fn.__doc__ +"\n"+J.to_string(jmethod) methods[name].append(method) self.methods = methods
def update_never_remind(): '''Tell ImageJ never to remind us of updates Not as harsh as it sounds - this is done with headless preferences which go to /dev/null. ''' never = J.get_static_field("java/lang/Long", "MAX_VALUE", "J") J.static_call("net/imagej/updater/UpToDate", "setLatestNag", "(J)V", never)
def _init_logger(): """This is so that Javabridge doesn't spill out a lot of DEBUG messages during runtime. From CellProfiler/python-bioformats. """ rootLoggerName = jb.get_static_field("org/slf4j/Logger", "ROOT_LOGGER_NAME", "Ljava/lang/String;") rootLogger = jb.static_call("org/slf4j/LoggerFactory", "getLogger", "(Ljava/lang/String;)Lorg/slf4j/Logger;", rootLoggerName) logLevel = jb.get_static_field("ch/qos/logback/classic/Level", "WARN", "Lch/qos/logback/classic/Level;") jb.call(rootLogger, "setLevel", "(Lch/qos/logback/classic/Level;)V", logLevel)
def test_selectedtag(self): """ Tests the SelectedTag class. """ tags = classes.Tags(jobject=javabridge.get_static_field("Lweka/classifiers/functions/SMO;", "TAGS_FILTER", "[Lweka/core/Tag;")) stag = classes.SelectedTag(tag_id=1, tags=tags) self.assertEqual(1, stag.selected.ident, "ID differs") stag = classes.SelectedTag(tag_text="2", tags=tags) self.assertEqual(2, stag.selected.ident, "ID differs")
def loadContinuousData(self, df, outputDataset=False): tetradData = None if (len(df.index) * df.columns.size <= 1500): dataBox = javabridge.JClassWrapper( 'edu.cmu.tetrad.data.DoubleDataBox')(len(df.index), df.columns.size) node_list = javabridge.JClassWrapper('java.util.ArrayList')() col_no = 0 for col in df.columns: nodi = javabridge.JClassWrapper( 'edu.cmu.tetrad.data.ContinuousVariable')(col) node_list.add(nodi) for row in df.index: value = javabridge.JClassWrapper('java.lang.Double')( df.iloc[row, col_no]) dataBox.set(row, col_no, value) col_no = col_no + 1 tetradData = javabridge.JClassWrapper( 'edu.cmu.tetrad.data.BoxDataSet')(dataBox, node_list) else: #Generate random name temp_data_file = ''.join( random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) + '.csv' temp_data_path = os.path.join(tempfile.gettempdir(), temp_data_file) df.to_csv(temp_data_path, sep='\t', index=False) # Read Data from File f = javabridge.JClassWrapper('java.io.File')(temp_data_path) path = f.toPath() delimiter = javabridge.get_static_field( 'edu/pitt/dbmi/data/reader/Delimiter', 'TAB', 'Ledu/pitt/dbmi/data/reader/Delimiter;') dataReader = javabridge.JClassWrapper( 'edu.pitt.dbmi.data.reader.tabular.ContinuousTabularDatasetFileReader' )(path, delimiter) tetradData = dataReader.readInData() tetradData = javabridge.static_call( 'edu/cmu/tetrad/util/DataConvertUtils', 'toDataModel', '(Ledu/pitt/dbmi/data/reader/Data;)Ledu/cmu/tetrad/data/DataModel;', tetradData) os.remove(temp_data_path) if (not outputDataset): tetradData = javabridge.JClassWrapper( 'edu.cmu.tetrad.data.CovarianceMatrixOnTheFly')(tetradData) return tetradData
def getGrayColorSpace(): '''Get a Java object that represents an RGB color space See java.awt.color.ColorSpace: this returns the linear RGB color space ''' cs_gray = jutil.get_static_field('java/awt/color/ColorSpace', 'CS_GRAY', 'I') return jutil.static_call('java/awt/color/ColorSpace', 'getInstance', '(I)Ljava/awt/color/ColorSpace;', cs_gray)
def __init__(self, df, dataType = 'continuous', numCategoriesToDiscretize = 4, depth = 3, alpha = 0.05, priorKnowledge = None, numBootstrap = -1, ensembleMethod = 'Highest'): tetradData = None indTest = None pc = self.pc # Continuous if dataType == 'continuous': if numBootstrap < 1: tetradData = pc.loadContinuousData(df) indTest = javabridge.JClassWrapper('edu.cmu.tetrad.search.IndTestFisherZ')(tetradData, alpha) else: tetradData = pc.loadContinuousData(df, outputDataset = True) indTest = javabridge.JClassWrapper('edu.cmu.tetrad.algcomparison.independence.FisherZ')() # Discrete elif dataType == 'discrete': tetradData = pc.loadDiscreteData(df) if numBootstrap < 1: indTest = javabridge.JClassWrapper('edu.cmu.tetrad.search.IndTestChiSquare')(tetradData, alpha) else: indTest = javabridge.JClassWrapper('edu.cmu.tetrad.algcomparison.independence.ChiSquare')() # Mixed else: tetradData = pc.loadMixedData(df, numCategoriesToDiscretize) if numBootstrap < 1: indTest = javabridge.JClassWrapper('edu.cmu.tetrad.search.IndTestConditionalGaussianLRT')(tetradData, alpha, False) else: indTest = javabridge.JClassWrapper('edu.cmu.tetrad.algcomparison.independence.ConditionalGaussianLRT')() ccd = None if numBootstrap < 1: ccd = javabridge.JClassWrapper('edu.cmu.tetrad.search.Ccd')(indTest) ccd.setDepth(depth) else: algorithm = javabridge.JClassWrapper('edu.cmu.tetrad.algcomparison.algorithm.oracle.pag.Ccd')(indTest) parameters = javabridge.JClassWrapper('edu.cmu.tetrad.util.Parameters')() parameters.set('depth', depth) parameters.set('alpha', alpha) ccd = javabridge.JClassWrapper('edu.pitt.dbmi.algo.bootstrap.GeneralBootstrapTest')(tetradData, algorithm, numBootstrap) edgeEnsemble = javabridge.get_static_field('edu/pitt/dbmi/algo/bootstrap/BootstrapEdgeEnsemble', ensembleMethod, 'Ledu/pitt/dbmi/algo/bootstrap/BootstrapEdgeEnsemble;') ccd.setEdgeEnsemble(edgeEnsemble) ccd.setParameters(parameters) if priorKnowledge is not None: ccd.setKnowledge(priorKnowledge) self.tetradGraph = ccd.search() self.nodes = pc.extractTetradGraphNodes(self.tetradGraph) self.edges = pc.extractTetradGraphEdges(self.tetradGraph) self.graph = pc.generatePyDotGraph(self.nodes,self.edges,self.tetradGraph)
def begin(self): javabridge.static_call("org/apache/log4j/BasicConfigurator", "configure", "()V") log4j_logger = javabridge.static_call("org/apache/log4j/Logger", "getRootLogger", "()Lorg/apache/log4j/Logger;") warn_level = javabridge.get_static_field("org/apache/log4j/Level","WARN", "Lorg/apache/log4j/Level;") javabridge.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V", warn_level)
def test_03_09_cw_get_method(self): sclass = javabridge.class_for_name('java.lang.String') iclass = javabridge.get_static_field('java/lang/Integer', 'TYPE', 'Ljava/lang/Class;') c = javabridge.get_class_wrapper('java.lang.String') m = c.getMethod('charAt', [ iclass ]) self.assertEqual(javabridge.to_string(javabridge.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'char') m = c.getMethod('concat', [ sclass]) self.assertEqual(javabridge.to_string(javabridge.call(m, 'getReturnType', '()Ljava/lang/Class;')), 'class java.lang.String')
def begin(self): javabridge.static_call("org/apache/log4j/BasicConfigurator", "configure", "()V") log4j_logger = javabridge.static_call("org/apache/log4j/Logger", "getRootLogger", "()Lorg/apache/log4j/Logger;") warn_level = javabridge.get_static_field("org/apache/log4j/Level", "WARN", "Lorg/apache/log4j/Level;") javabridge.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V", warn_level)
def __setattr__(self, name, value): try: jfield = self.klass.getField(name) except: return object.__setattr__(self, name, value) STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") if (J.call(jfield, "getModifiers", "()I") & STATIC) != STATIC: raise AttributeError() klass = J.call(jfield, "getType", "()Ljava/lang/Class;") result = J.set_static_field(self.cname, name, sig(klass), value)
def _start_lif_reader(self): jv.start_vm(class_path=bf.JARS) log_level = 'ERROR' # reduce log level rootLoggerName = jv.get_static_field("org/slf4j/Logger", "ROOT_LOGGER_NAME", "Ljava/lang/String;") rootLogger = jv.static_call("org/slf4j/LoggerFactory", "getLogger", "(Ljava/lang/String;)Lorg/slf4j/Logger;", rootLoggerName) logLevel = jv.get_static_field("ch/qos/logback/classic/Level", log_level, "Lch/qos/logback/classic/Level;") jv.call(rootLogger, "setLevel", "(Lch/qos/logback/classic/Level;)V", logLevel) self.ir = bf.ImageReader(self.lif_file_path, perform_init=True) mdroot = et.ElementTree.fromstring(bf.get_omexml_metadata(self.lif_file_path)) mds = list(map(lambda e: e.attrib, mdroot.iter('{http://www.openmicroscopy.org/Schemas/OME/2016-06}Pixels'))) # lif can contain multiple images, select one that is likely to be the timeseries self.metadata = None self.lif_stack_idx = 0 for idx, md in enumerate(mds): if int(md['SizeT']) > 1: self.lif_stack_idx = idx self.metadata = md if not self.metadata: raise ValueError('lif does not contain an image with sizeT > 1')
def wrapped(*args, **kwargs): try: javabridge.start_vm(class_path=bioformats.JARS) myloglevel = "ERROR" # user string argument for logLevel. rootLoggerName = javabridge.get_static_field( "org/slf4j/Logger", "ROOT_LOGGER_NAME", "Ljava/lang/String;") rootLogger = javabridge.static_call( "org/slf4j/LoggerFactory", "getLogger", "(Ljava/lang/String;)Lorg/slf4j/Logger;", rootLoggerName, ) logLevel = javabridge.get_static_field( "ch/qos/logback/classic/Level", myloglevel, "Lch/qos/logback/classic/Level;", ) javabridge.call(rootLogger, "setLevel", "(Lch/qos/logback/classic/Level;)V", logLevel) return func(*args, **kwargs) finally: javabridge.kill_vm()
def test_tags(self): """ Tests the Tags class. """ tag1 = classes.Tag(ident=1, ident_str="tag1", readable="blah 1") tag2 = classes.Tag(ident=2, ident_str="tag2", readable="blah 2") tag3 = classes.Tag(ident=3, ident_str="tag3", readable="blah 3") tags = classes.Tags(tags=[tag1, tag2, tag3]) self.assertEqual(3, len(tags), "Number of tags differs!") self.assertEqual("TAG1|TAG2|TAG3", str(tags), msg="String differs") smo = classes.JavaObject(classes.JavaObject.new_instance(classname="weka.classifiers.functions.SMO")) tags = classes.Tags(jobject=javabridge.get_static_field("Lweka/classifiers/functions/SMO;", "TAGS_FILTER", "[Lweka/core/Tag;")) self.assertEqual(3, len(tags), "Number of tags differs!") self.assertEqual("0|1|2", str(tags), msg="String differs")
def test_10_04_engine_factory_wrapper(self): svc = ij2.get_script_service(self.context) factory = svc.getByName("ECMAScript") factory.getEngineName() factory.getEngineVersion() factory.getExtensions() factory.getMimeTypes() factory.getNames() factory.getLanguageName() factory.getLanguageVersion() factory.getParameter(J.get_static_field('javax/script/ScriptEngine', 'NAME', 'Ljava/lang/String;')) factory.getMethodCallSyntax("myobject", "mymethod", ["param1", "param2"]) factory.getOutputStatement("Hello, world") factory.getProgram(["I.do.this()", "I.do.that()"]) factory.getScriptEngine()
def __setattr__(self, name, value): if name in ("o", "class_wrapper", "methods") or \ not hasattr(self, "methods"): object.__setattr__(self, name, value) return try: jfield = self.class_wrapper.getField(name) except: object.__setattr__(self, name, value) return STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") if (J.call(jfield, "getModifiers", "()I") & STATIC) == STATIC: raise AttributeError() klass = J.call(jfield, "getType", "()Ljava/lang/Class;") result = J.set_field(self.o, name, sig(klass), value)
def __setattr__(self, name, value): if name in ("o", "class_wrapper", "methods", "field_names") or \ not hasattr(self, "methods"): object.__setattr__(self, name, value) return try: jfield = self.class_wrapper.getField(name) except: object.__setattr__(self, name, value) return STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") if (J.call(jfield, "getModifiers", "()I") & STATIC) == STATIC: raise AttributeError() klass = J.call(jfield, "getType", "()Ljava/lang/Class;") result = J.set_field(self.o, name, sig(klass), value)
def loadDiscreteData(self, df): tetradData = None if(len(df.index)*df.columns.size <= 1500): dataBox = javabridge.JClassWrapper('edu.cmu.tetrad.data.VerticalIntDataBox')(len(df.index),df.columns.size) node_list = javabridge.JClassWrapper('java.util.ArrayList')() col_no = 0 for col in df.columns: cat_array = sorted(set(df[col])) cat_list = javabridge.JClassWrapper('java.util.ArrayList')() for cat in cat_array: cat = str(cat) cat_list.add(cat) nodname = javabridge.JClassWrapper('java.lang.String')(col) nodi = javabridge.JClassWrapper('edu.cmu.tetrad.data.DiscreteVariable')(nodname,cat_list) node_list.add(nodi) for row in df.index: value = javabridge.JClassWrapper('java.lang.Integer')(cat_array.index(df.iloc[row,col_no])) dataBox.set(row,col_no,value) col_no = col_no + 1 tetradData = javabridge.JClassWrapper('edu.cmu.tetrad.data.BoxDataSet')(dataBox, node_list) else: # Generate random name temp_data_file = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) + '.csv' temp_data_path = os.path.join(tempfile.gettempdir(), temp_data_file) df.to_csv(temp_data_path, sep = "\t", index = False) # Read Data from File f = javabridge.JClassWrapper('java.io.File')(temp_data_path) path = f.toPath() delimiter = javabridge.get_static_field('edu/pitt/dbmi/data/reader/Delimiter','TAB','Ledu/pitt/dbmi/data/reader/Delimiter;') dataReader = javabridge.JClassWrapper('edu.pitt.dbmi.data.reader.tabular.VerticalDiscreteTabularDatasetFileReader')(path,delimiter) tetradData = dataReader.readInData() tetradData = javabridge.static_call('edu/cmu/tetrad/util/DataConvertUtils','toDataModel','(Ledu/pitt/dbmi/data/reader/Data;)Ledu/cmu/tetrad/data/DataModel;', tetradData) os.remove(temp_data_path) return tetradData
def test_tags(self): """ Tests the Tags class. """ tag1 = classes.Tag(ident=1, ident_str="tag1", readable="blah 1") tag2 = classes.Tag(ident=2, ident_str="tag2", readable="blah 2") tag3 = classes.Tag(ident=3, ident_str="tag3", readable="blah 3") tags = classes.Tags(tags=[tag1, tag2, tag3]) self.assertEqual(3, len(tags), "Number of tags differs!") self.assertEqual("TAG1|TAG2|TAG3", str(tags), msg="String differs") tags = classes.Tags(jobject=javabridge.get_static_field("Lweka/classifiers/functions/SMO;", "TAGS_FILTER", "[Lweka/core/Tag;")) self.assertEqual(3, len(tags), "Number of tags differs!") self.assertEqual("0|1|2", str(tags), msg="String differs") tags = classes.Tags.get_tags("weka.classifiers.functions.SMO", "TAGS_FILTER") self.assertEqual(3, len(tags), "Number of tags differs!") self.assertEqual("0|1|2", str(tags), msg="String differs") self.assertIsNotNone(tags.find("2"), msg="Should have found tag") self.assertIsNone(tags.find("blah"), msg="Should not have found tag")
def __getattr__(self, name): if name in ("o", "class_wrapper", "methods"): raise AttributeError() if not hasattr(self, "methods"): # not initialized raise AttributeError() try: jfield = self.class_wrapper.getField(name) except: raise AttributeError() STATIC = J.get_static_field("java/lang/reflect/Modifier", "STATIC", "I") if (J.call(jfield, "getModifiers", "()I") & STATIC) == STATIC: raise AttributeError() klass = J.call(jfield, "getType", "()Ljava/lang/Class;") result = J.get_field(self.o, name, sig(klass)) if isinstance(result, J.JB_Object): result = JWrapper(result) return result
def loadContinuousData(self, df, outputDataset = False): tetradData = None if(len(df.index)*df.columns.size <= 1500): dataBox = javabridge.JClassWrapper('edu.cmu.tetrad.data.DoubleDataBox')(len(df.index),df.columns.size) node_list = javabridge.JClassWrapper('java.util.ArrayList')() col_no = 0 for col in df.columns: nodi = javabridge.JClassWrapper('edu.cmu.tetrad.data.ContinuousVariable')(col) node_list.add(nodi) for row in df.index: value = javabridge.JClassWrapper('java.lang.Double')(df.iloc[row,col_no]) dataBox.set(row,col_no,value) col_no = col_no + 1 tetradData = javabridge.JClassWrapper('edu.cmu.tetrad.data.BoxDataSet')(dataBox, node_list) else: #Generate random name temp_data_file = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) + '.csv' temp_data_path = os.path.join(tempfile.gettempdir(), temp_data_file) df.to_csv(temp_data_path, sep = '\t', index = False) # Read Data from File f = javabridge.JClassWrapper('java.io.File')(temp_data_path) path = f.toPath() delimiter = javabridge.get_static_field('edu/pitt/dbmi/data/reader/Delimiter','TAB','Ledu/pitt/dbmi/data/reader/Delimiter;') dataReader = javabridge.JClassWrapper('edu.pitt.dbmi.data.reader.tabular.ContinuousTabularDatasetFileReader')(path,delimiter) tetradData = dataReader.readInData() tetradData = javabridge.static_call('edu/cmu/tetrad/util/DataConvertUtils','toDataModel','(Ledu/pitt/dbmi/data/reader/Data;)Ledu/cmu/tetrad/data/DataModel;', tetradData) os.remove(temp_data_path) if(not outputDataset): tetradData = javabridge.JClassWrapper('edu.cmu.tetrad.data.CovarianceMatrixOnTheFly')(tetradData) return tetradData
def _init_toolbar(self): self.toolbar = javabridge.JClassWrapper('javax.swing.JToolBar')() self.toolbar.setFloatable(False) self.radio_button_group = javabridge.JClassWrapper( 'javax.swing.ButtonGroup')() for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.toolbar.addSeparator() continue callback = getattr(self, callback, None) if callback is None: continue if text in ("Pan", "Zoom"): self.add_radio_button(callback, image_file) else: self.add_button(callback, image_file) north = javabridge.get_static_field('java/awt/BorderLayout', 'NORTH', 'Ljava/lang/String;') javabridge.call(self._frame.o, "add", "(Ljava/awt/Component;Ljava/lang/Object;)V", self.toolbar.o, north)
def test_01_05_03_set_static_field(self): class_name = "org/cellprofiler/javabridge/test/RealRect" test_cases = ( ("fs_char", "C", "A"), ("fs_byte", "B", 3), ("fs_short", "S", 15), ("fs_int", "I", 392), ("fs_long", "J", -14), ("fs_float", "F", 1.03), ("fs_double", "D", -889.1), ("fs_object", "Ljava/lang/Object;", javabridge.make_instance("java/lang/Integer", "(I)V", 15)), ("fs_object", "Ljava/lang/Object;", None)) for field_name, signature, value in test_cases: javabridge.set_static_field(class_name, field_name, signature, value) v = javabridge.get_static_field(class_name, 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 test_01_05_00_get_static_field(self): klass = self.env.find_class("java/lang/Short") self.assertEqual(javabridge.get_static_field(klass, "MAX_VALUE", "S"), 2**15 - 1)
def get_named_axis(self, axis_name): return J.get_static_field("net/imglib2/meta/Axes", axis_name, "Lnet/imglib2/meta/AxisType;")
def fn(): javabridge.get_static_field('java/lang/Object', "NoSuchField", "I")
def fn(): javabridge.get_static_field( 'no/such/class', "field", "I")
def fn(): javabridge.get_static_field( 'java/lang/Object', "NoSuchField", "I")
def test_03_08_cw_get_field(self): c = javabridge.get_class_wrapper('java.lang.String') field = c.getField('CASE_INSENSITIVE_ORDER') modifiers = javabridge.call(field, 'getModifiers', '()I') static = javabridge.get_static_field('java/lang/reflect/Modifier','STATIC','I') self.assertEqual((modifiers & static), static)