def identstr(self, value): """ Sets the ID string. :param value: the new ID string :type value: str """ javabridge.call(self.jobject, "setIDStr", "(Ljava/lang/String;)V", value)
def select_attributes_cv_split(self, instances): """ Performs attribute selection on the given cross-validation split. :param instances: the data to process :type instances: Instances """ javabridge.call(self.jobject, "selectAttributesCVSplit", "(Lweka/core/Instances;)V", instances.jobject)
def set_crossvalidation(self, crossvalidation): """ Sets whether to perform cross-validation. :param crossvalidation: whether to perform cross-validation :type crossvalidation: bool """ javabridge.call(self.jobject, "setXval", "(Z)V", crossvalidation)
def readable(self, value): """ Sets the 'human readable' string. :param value: the new readable string :type value: str """ javabridge.call(self.jobject, "setReadable", "(Ljava/lang/String;)V", value)
def select_attributes(self, instances): """ Performs attribute selection on the given dataset. :param instances: the data to process :type instances; Instances """ javabridge.call(self.jobject, "SelectAttributes", "(Lweka/core/Instances;)V", instances.jobject)
def set_ranking(self, ranking): """ Sets whether to perform a ranking, if possible. :param ranking: whether to perform a ranking :type ranking: bool """ javabridge.call(self.jobject, "setRanking", "(Z)V", ranking)
def set_seed(self, seed): """ Sets the seed for cross-validation. :param seed: the seed value :type seed: int """ javabridge.call(self.jobject, "setSeed", "(I)V", seed)
def set_search(self, search): """ Sets the search algorithm to use. :param search: the search algorithm :type search: ASSearch """ javabridge.call(self.jobject, "setSearch", "(Lweka/attributeSelection/ASSearch;)V", search.jobject)
def set_folds(self, folds): """ Sets the number of folds to use for cross-validation. :param folds: the number of folds :type folds: int """ javabridge.call(self.jobject, "setFolds", "(I)V", folds)
def build_evaluator(self, data): """ Builds the evaluator with the data. :param data: the data to use :type data: Instances """ javabridge.call(self.jobject, "buildEvaluator", "(Lweka/core/Instances;)V", data.jobject)
def set_package(self, pkge): """ Sets the package. :param pkge: the package :type pkge: Package """ javabridge.call(self.jobject, "setPackage", "(Lorg/pentaho/packageManagement/Package;)V", pkge.jobject)
def weight(self, weight): """ Sets the weight of the attribute. :param weight: the weight of the attribute :type weight: float """ javabridge.call(self.jobject, "setWeight", "(D)V", weight)
def set_evaluator(self, evaluator): """ Sets the evaluator to use. :param evaluator: the evaluator to use. :type evaluator: ASEvaluation """ javabridge.call(self.jobject, "setEvaluator", "(Lweka/attributeSelection/ASEvaluation;)V", evaluator.jobject)
def password(self, password): """ Sets the database password. :param password: the database password :type password: str """ javabridge.call(self.jobject, "setPassword", "(Ljava/lang/String;)V", password)
def db_url(self, url): """ Sets the database URL. :param url: the database URL :type url: str """ javabridge.call(self.jobject, "setDatabaseURL", "(Ljava/lang/String;)V", url)
def upper(self, upper): """ Sets the upper limit. :param upper: the upper limit :type upper: int """ javabridge.call(self.jobject, "setUpper", "(I)V", upper)
def user(self, user): """ Sets the database user. :param user: the database user :type user: str """ javabridge.call(self.jobject, "setUsername", "(Ljava/lang/String;)V", user)
def sparse_data(self, sparse): """ Sets whether to generate sparse data. :param sparse: whether to generated sparse data :type sparse: bool """ javabridge.call(self.jobject, "setSparseData", "(Z)V", sparse)
def cp_stop_vm(kill=True): '''Shut down the Java VM Check for headlessness and the state of ImageJ and take whatever action is needed to stop AWT and the JVM. ''' from imagej.imagej2 import allow_quit, the_imagej_context try: ij1 = javabridge.JClassWrapper("ij.IJ").getInstance() except javabridge.JavaException as e: logger.debug("No available instance: %s" % str(e)) ij1 = None if the_imagej_context is not None: # # Tell the app service that it's OK to quit without prompt # allow_quit() javabridge.call(the_imagej_context.getContext(), "dispose", "()V") if ij1 is not None: # # Yes, the proper way to get ImageJ to quit is # to start it. # ij1.run() if kill: javabridge.kill_vm()
def dataset_format(self, inst): """ Sets the dataset format. :param inst: the Instances to use as dataset format :type inst: Instances """ javabridge.call(self.jobject, "setDatasetFormat", "(Lweka/core/Instances;)V", inst.jobject)
def query(self, query): """ Sets the SQL query to execute. :param query: the SQL query :type query: str """ javabridge.call(self.jobject, "setQuery", "(Ljava/lang/String;)V", query)
def ident(self, value): """ Sets the integer ID of the tag. :param value: the new ID :type value: int """ javabridge.call(self.jobject, "setID", "(I)V", value)
def run(self, module_info, pre = None, post = None, **kwargs): '''Run a module module_info - the module_info of the module to run pre - list of PreprocessorPlugins to run before running module post - list of PostprocessorPlugins to run after running module *kwargs - names and values for input parameters ''' input_map = J.make_map(kwargs) if pre is not None: pre = J.static_call("java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", pre) if post is not None: post = J.static_call("java/util/Arrays", "asList", "([Ljava/lang/Object;)Ljava/util/List;", post) future = J.call( self.o, "run", "(Lorg/scijava/module/ModuleInfo;" "Ljava/util/List;" "Ljava/util/List;" "Ljava/util/Map;)" "Ljava/util/concurrent/Future;", module_info, pre, post, input_map) return J.call( self.o, "waitFor", "(Ljava/util/concurrent/Future;)Lorg/scijava/module/Module;", future)
def getModules(self): modules = J.call(o, "getModules", "()Ljava/util/List;") if modules is None: return [] module_iterator = J.call(modules, "iterator", "()Ljava/util/Iterator;") return [wrap_module_info(x) for x in J.iterate_java(module_iterator)]
def invert(self, invert): """ Sets the invert state. :param invert: whether to invert or not :type invert: bool """ javabridge.call(self.jobject, "setInvert", "(Z)V", invert)
def single_index(self, index): """ Sets the string index. :param index: the 1-based string index ::type index: str """ javabridge.call(self.jobject, "setSingleIndex", "(Ljava/lang/String;)V", index)
def ranges(self, rng): """ Sets the string range. :param rng: the range to set :type rng: str """ javabridge.call(self.jobject, "setRanges", "(Ljava/lang/String;)V", rng)
def sig(klass): '''Return the JNI signature for a class''' name = J.call(klass, "getName", "()Ljava/lang/String;") if not (J.call(klass, "isPrimitive", "()Z") or J.call(klass, "isArray", "()Z")): name = "L%s;" % name if name == 'void': return "V" if name == 'int': return "I" if name == 'byte': return "B" if name == 'boolean': return "Z" if name == 'long': return "J" if name == 'float': return "F" if name == 'double': return "D" if name == 'char': return "C" if name == 'short': return "S" return name.replace(".", "/")
def __call_static(self, method_name, *args): '''Call the appropriate overloaded method with the given name :param method_name: the name of the method to call :param *args: the arguments to the method, which are used to disambiguate between similarly named methods ''' env = J.get_env() last_e = None for method in self.methods[method_name]: params = env.get_object_array_elements(method.getParameterTypes()) is_var_args = J.call(method.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 rtype = J.call(method.o, "getReturnType", "()Ljava/lang/Class;") args_sig = "".join(map(sig, params)) rsig = sig(rtype) msig = "(%s)%s" % (args_sig, rsig) result = J.static_call(self.cname, method_name, msig, *cargs) if isinstance(result, J.JB_Object): result = JWrapper(result) return result raise TypeError("No matching method found for %s" % method_name)
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 summary(cls, inst): """ Generates a summary of the dataset. :param inst: the dataset :type inst: Instances :return: the summary :rtype: str """ return javabridge.call(inst.jobject, "toSummaryString", "()Ljava/lang/String;")
def reduce_dimensionality(self, data): """ Reduces the dimensionality of the provided Instance or Instances object. :param data: the data to process :type data: Instances :return: the reduced dataset :rtype: Instances """ if type(data) is Instance: return Instance( javabridge.call(self.jobject, "reduceDimensionality", "(Lweka/core/Instance;)Lweka/core/Instance;", data.jobject)) else: return Instances( javabridge.call( self.jobject, "reduceDimensionality", "(Lweka/core/Instances;)Lweka/core/Instances;", data.jobject))
def getService(self, class_name): '''Get a service with the given class name class_name - class name in dotted form returns the class or None if no implementor loaded. ''' klass = J.class_for_name(class_name) return J.call( self.o, 'get', '(Ljava/lang/Class;)Lorg/scijava/service/Service;', klass)
def multi_resultset_summary(self, comparison_column): """ Carries out a comparison between all resultsets, counting the number of datsets where one resultset outperforms the other. :param comparison_column: the 0-based index of the column to compare against :type comparison_column: int :return: the summary :rtype: str """ return javabridge.call(self.jobject, "multiResultsetSummary", "(I)Ljava/lang/String;", comparison_column)
def metric_value(self, name): """ Returns the named metric value for the rule. :param name: the name of the metric :type name: str :return: the metric value :rtype: float """ return javabridge.call(self.jobject, "getNamedMetricValue", "(Ljava/lang/String;)D", name)
def parse_date(self, s): """ Parses the date string and returns the internal format value. :param s: the date string :type s: str :return: the internal format :rtype: float """ return javabridge.call(self.jobject, "parseDate", "(Ljava/lang/String;)D", s)
def add_string_value(self, s): """ Adds the string value, returns the index. :param s: the string to add :type s: str :return: the index :rtype: int """ return javabridge.call(self.jobject, "addStringValue", "(Ljava/lang/String;)I", s)
def __compareto__(self, other): """ Return the comparison result with the other rule. :param other: the other rule to compare with :type other: Item :return: the integer result, <0 is less than, =0 is equal to, >0 is greater than :rtype: int """ return javabridge.call(self.jobject, "compareTo", "(Lweka/associations/Item;)I", other.jobject)
def add_relation(self, instances): """ Adds the relation value, returns the index. :param instances: the Instances object to add :type instances: Instances :return: the index :rtype: int """ return javabridge.call(self.jobject, "addRelation", "(Lweka/core/Instances;)I", instances.jobject)
def value(self, index): """ Returns the label for the index. :param index: the 0-based index of the label to return :type index: int :return: the label :rtype: str """ return javabridge.call(self.jobject, "value", "(I)Ljava/lang/String;", index)
def equals(self, att): """ Checks whether this attributes is the same as the provided one. :param att: the Attribute to check against :type att: Attribute :return: whether the same :rtype: bool """ return javabridge.call(self.jobject, "equals", "(Lweka/core/Attribute;)Z", att.jobject)
def __eq__(self, other): """ Returns whether this object is the same as the other one. :param other: the object to compare with :type other: AssociationRule :return: True if the same :rtype: bool """ return javabridge.call(self.jobject, "equals", "(Ljava/lang/Object;)Z", other.jobject)
def index_of(self, label): """ Returns the index of the label in this attribute. :param label: the string label to get the index for :type label: str :return: the 0-based index :rtype: int """ return javabridge.call(self.jobject, "indexOfValue", "(Ljava/lang/String;)I", label)
def get_stdev(self, col, row): """ Returns the standard deviation at this location (if valid location). :param col: the 0-based column index :type col: int :param row: the 0-based row index :type row: int :return: the standard deviation :rtype: float """ return javabridge.call(self.jobject, "getStdDev", "(II)D", col, row)
def multi_resultset_ranking(self, comparison_column): """ Creates a ranking. :param comparison_column: the 0-based index of the column to compare against :type comparison_column: int :return: the ranking :rtype: str """ return javabridge.call(self.jobject, "multiResultsetRanking", "(I)Ljava/lang/String;", comparison_column)
def header(self, comparison_column): """ Creates a "header" string describing the current resultsets. :param comparison_column: the index of the column to compare against :type comparison_column: int :return: the header :rtype: str """ self.init_columns() return javabridge.call(self.jobject, "header", "(I)Ljava/lang/String;", comparison_column)
def test_read_write(self): """ Tests methods read and write. """ fname = self.tempfile("readwrite.ser") self.delfile(fname) lin = ["A", "B", "C", "D"] vin = javabridge.make_instance("java/util/Vector", "()V") for element in lin: javabridge.call(vin, "add", "(Ljava/lang/Object;)Z", element) serialization.write(fname, vin) self.assertTrue(os.path.exists(fname), msg="Failed to write to " + fname + "?") vout = serialization.read(fname) self.assertIsNotNone(vout, msg="Failed to read from " + fname + "?") enm = javabridge.call(vin, "elements", "()Ljava/util/Enumeration;") lout = typeconv.enumeration_to_list(enm) self.delfile(fname) self.assertEqual(lin, lout, msg="Input/output differ")
def get_mean(self, col, row): """ Returns the mean at this location (if valid location). :param col: the 0-based column index :type col: int :param row: the 0-based row index :type row: int :return: the mean :rtype: float """ return javabridge.call(self.jobject, "getMean", "(II)D", col, row)
def get_ranked_attributes(self): """ Returns the matrix of ranked attributes from the last run. :return: the Numpy matrix :rtype: ndarray """ matrix = javabridge.call(self.jobject, "rankedAttributes", "()[[D") if matrix is None: return None else: return arrays.double_matrix_to_ndarray(matrix)
def get_col_name(self, index): """ Returns the column name. :param index: the 0-based row index :type index: int :return: the column name, None if invalid index :rtype: str """ return javabridge.call(self.jobject, "getColName", "(I)Ljava/lang/String;", index)
def url(self): """ Returns the URL of the package. :return: the url :rtype: str """ return str( JavaObject( javabridge.call(self.jobject, "getPackageURL", "()Ljava/net/URL;")))
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 check_constraint(self, pkge=None, constr=None): """ Checks the constraints. :param pkge: the package to check :type pkge: Package :param constr: the package constraint to check :type constr: PackageConstraint """ if not pkge is None: return javabridge.call(self.jobject, "checkConstraint", "(Lweka/core/packageManagement/Package;)Z", pkge.jobject) if not constr is None: return javabridge.call( self.jobject, "checkConstraint", "(Lweka/core/packageManagement/PackageConstraint;)Z", pkge.jobject) raise Exception( "Either package or package constraing must be provided!")
def get_selected_attributes(self): """ Returns the selected attributes from the last run. :return: the Numpy array of 0-based indices :rtype: ndarray """ array = javabridge.call(self.jobject, "selectedAttributes", "()[I") if array is None: return None else: return javabridge.get_env().get_int_array_elements(array)
def can_produce_rules(self): """ Checks whether association rules can be generated. :return: whether scheme implements AssociationRulesProducer interface and association rules can be generated :rtype: bool """ if not self.check_type(self.jobject, "weka.associations.AssociationRulesProducer"): return False return javabridge.call(self.jobject, "canProduceRules", "()Z")
def target(self): """ Returns the target package constraint. :return: the package constraint :rtype: PackageConstraint """ return PackageConstraint( javabridge.call( self.jobject, "getTarget", "()Lweka/core/packageManagement/PackageConstraint;"))
def graph(self): """ Returns the graph if classifier implements weka.core.Drawable, otherwise None. :return: the graph or None if not available :rtype: str """ if self.is_drawable: return javabridge.call(self.jobject, "graph", "()Ljava/lang/String;") else: return None
def get_outputformat(self): """ Returns the output format. :return: the output format :rtype: Instances """ inst = javabridge.call(self.jobject, "getOutputFormat", "()Lweka/core/Instances;") if inst is None: return None else: return Instances(inst)
def graph_type(self): """ Returns the graph type if classifier implements weka.core.Drawable, otherwise -1. :return: the type :rtype: int """ if self.is_drawable: return javabridge.call(self.jobject, "graphType", "()I") else: return -1
def executeKFoldClassifier(self, featureInclusion, kFold): deleteFeatures = 0 for i in range(0, len(featureInclusion)): if featureInclusion[i]: self.instances.deleteAttributeAt(i - deleteFeatures) deleteFeatures += 1 self.instances.setClassIndex(self.instances.numAttributes - 1) cvParameterSelection = javabridge.make_instance( "weka/classifiers/meta/CVParameterSelection", "()V") javabridge.call(cvParameterSelection, "setNumFolds", "(I)V", kFold) javabridge.call(cvParameterSelection, "buildClassifier(weka/core/Instances)V", self.instances) eval = Evaluation(self.instances) eval.crossvalidate_model(cvParameterSelection, self.instances, kFold, random()) return eval.percent_correct()