code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
result = []
names = javabridge.call(self.jobject, "getVariableNames", "()Ljava/util/Set;")
for name in javabridge.iterate_collection(names):
result.append(javabridge.to_string(name))
return result | def variable_names(self) | Returns the names of all environment variables.
:return: the names of the variables
:rtype: list | 3.86736 | 3.941799 | 0.981115 |
cls = javabridge.call(self.jobject, "getClass", "()Ljava/lang/Class;")
comptype = javabridge.call(cls, "getComponentType", "()Ljava/lang/Class;")
return javabridge.call(comptype, "getName", "()Ljava/lang/String;") | def component_type(self) | Returns the classname of the elements.
:return: the class of the elements
:rtype: str | 2.605774 | 2.591824 | 1.005383 |
return javabridge.static_call(
"Ljava/lang/reflect/Array;",
"newInstance",
"(Ljava/lang/Class;I)Ljava/lang/Object;",
get_jclass(classname=classname), length) | def new_instance(cls, classname, length) | Creates a new array with the given classname and length; initial values are null.
:param classname: the classname in Java notation (eg "weka.core.DenseInstance")
:type classname: str
:param length: the length of the array
:type length: int
:return: the Java array
:rtype: JB_Object | 3.638666 | 3.842524 | 0.946947 |
cls = javabridge.call(self.jobject, "getClass", "()Ljava/lang/Class;")
clsname = javabridge.call(cls, "getName", "()Ljava/lang/String;")
l = javabridge.static_call(clsname.replace(".", "/"), "values", "()[L" + clsname.replace(".", "/") + ";")
l = javabridge.get_env().get_object_array_elements(l)
result = []
for item in l:
result.append(Enum(jobject=item))
return result | def values(self) | Returns list of all enum members.
:return: all enum members
:rtype: list | 2.821584 | 2.563605 | 1.100631 |
if n is None:
return javabridge.call(self.jobject, "nextInt", "()I")
else:
return javabridge.call(self.jobject, "nextInt", "(I)I", n) | def next_int(self, n=None) | Next random integer. if n is provided, then between 0 and n-1.
:param n: the upper limit (minus 1) for the random integer
:type n: int
:return: the next random integer
:rtype: int | 2.366568 | 2.439945 | 0.969927 |
if self.is_optionhandler:
return typeconv.string_array_to_list(javabridge.call(self.jobject, "getOptions", "()[Ljava/lang/String;"))
else:
return [] | def options(self) | Obtains the currently set options as list.
:return: the list of options
:rtype: list | 7.119604 | 7.558863 | 0.941888 |
if self.is_optionhandler:
javabridge.call(self.jobject, "setOptions", "([Ljava/lang/String;)V", typeconv.string_list_to_array(options)) | def options(self, options) | Sets the command-line options (as list).
:param options: the list of command-line options to set
:type options: list | 7.408288 | 7.97627 | 0.928791 |
result = []
result.append(self.classname)
result.append("=" * len(self.classname))
result.append("")
result.append("DESCRIPTION")
result.append("")
result.append(self.global_info())
result.append("")
result.append("OPTIONS")
result.append("")
options = javabridge.call(self.jobject, "listOptions", "()Ljava/util/Enumeration;")
enum = javabridge.get_enumeration_wrapper(options)
while enum.hasMoreElements():
opt = Option(enum.nextElement())
result.append(opt.synopsis)
result.append(opt.description)
result.append("")
return '\n'.join(result) | def to_help(self) | Returns a string that contains the 'global_info' text and the options.
:return: the generated help string
:rtype: str | 2.786333 | 2.555544 | 1.090309 |
result = super(OptionHandler, self).to_dict()
result["type"] = "OptionHandler"
result["options"] = join_options(self.options)
return result | def to_dict(self) | Returns a dictionary that represents this object, to be used for JSONification.
:return: the object dictionary
:rtype: dict | 5.018431 | 5.235815 | 0.958481 |
result = OptionHandler(cls.new_instance(d["class"]))
result.options = split_options(d["options"])
return result | def from_dict(cls, d) | Restores an object state from a dictionary, used in de-JSONification.
:param d: the object dictionary
:type d: dict
:return: the object
:rtype: object | 12.137487 | 15.280807 | 0.794296 |
result = None
for t in self.array:
if str(t) == name:
result = Tag(t.jobject)
break
return result | def find(self, name) | Returns the Tag that matches the name.
:param name: the string representation of the tag
:type name: str
:return: the tag, None if not found
:rtype: Tag | 7.879306 | 6.271979 | 1.256271 |
return Tags(jobject=javabridge.call(javaobject.jobject, methodname, "()[Lweka/core/Tag;")) | def get_object_tags(cls, javaobject, methodname) | Instantiates the Tag array obtained from the object using the specified method name.
Example:
cls = Classifier(classname="weka.classifiers.meta.MultiSearch")
tags = Tags.get_object_tags(cls, "getMetricsTags")
:param javaobject: the javaobject to obtain the tags from
:type javaobject: JavaObject
:param methodname: the method name returning the Tag array
:type methodname: str
:return: the Tags objects
:rtype: Tags | 7.474898 | 4.716753 | 1.584755 |
result = []
a = javabridge.call(self.jobject, "getTags", "()Lweka/core/Tag;]")
length = javabridge.get_env().get_array_length(a)
wrapped = javabridge.get_env().get_object_array_elements(a)
for i in range(length):
result.append(Tag(javabridge.get_env().get_string(wrapped[i])))
return result | def tags(self) | Returns the associated tags.
:return: the list of Tag objects
:rtype: list | 3.330917 | 3.285326 | 1.013877 |
jobj = javabridge.call(self.jobject, "getBaseObject", "()Ljava/io/Serializable;")
if OptionHandler.check_type(jobj, "weka.core.OptionHandler"):
return OptionHandler(jobj)
else:
return JavaObject(jobj) | def base_object(self) | Returns the base object to apply the setups to.
:return: the base object
:rtype: JavaObject or OptionHandler | 5.11627 | 4.05487 | 1.261759 |
if not obj.is_serializable:
raise Exception("Base object must be serializable: " + obj.classname)
javabridge.call(self.jobject, "setBaseObject", "(Ljava/io/Serializable;)V", obj.jobject) | def base_object(self, obj) | Sets the base object to apply the setups to.
:param obj: the object to use (must be serializable!)
:type obj: JavaObject | 4.8561 | 3.919152 | 1.239069 |
array = JavaArray(javabridge.call(self.jobject, "getParameters", "()[Lweka/core/setupgenerator/AbstractParameter;"))
result = []
for item in array:
result.append(AbstractParameter(jobject=item.jobject))
return result | def parameters(self) | Returns the list of currently set search parameters.
:return: the list of AbstractSearchParameter objects
:rtype: list | 6.418454 | 7.317327 | 0.877158 |
array = JavaArray(jobject=JavaArray.new_instance("weka.core.setupgenerator.AbstractParameter", len(params)))
for idx, obj in enumerate(params):
array[idx] = obj.jobject
javabridge.call(self.jobject, "setParameters", "([Lweka/core/setupgenerator/AbstractParameter;)V", array.jobject) | def parameters(self, params) | Sets the list of search parameters to use.
:param params: list of AbstractSearchParameter objects
:type params: list | 5.059152 | 5.884021 | 0.859812 |
result = []
has_options = self.base_object.is_optionhandler
enm = javabridge.get_enumeration_wrapper(javabridge.call(self.jobject, "setups", "()Ljava/util/Enumeration;"))
while enm.hasMoreElements():
if has_options:
result.append(OptionHandler(enm.nextElement()))
else:
result.append(JavaObject(enm.nextElement()))
return result | def setups(self) | Generates and returns all the setups according to the parameter search space.
:return: the list of configured objects (of type JavaObject)
:rtype: list | 5.138428 | 4.531825 | 1.133854 |
if isinstance(o, str) and o.startswith("@{") and o.endswith("}"):
return o
else:
return classes.to_commandline(o) | def to_commandline(o) | Turns the object into a commandline string. However, first checks whether a string represents
a internal value placeholder (@{...}).
:param o: the object to turn into commandline
:type o: object
:return: the commandline
:rtype: str | 4.446142 | 3.551415 | 1.251935 |
result = name
if self.parent is not None:
index = self.index
bname = re.sub(r'-[0-9]+$', '', name)
names = []
for idx, actor in enumerate(self.parent.actors):
if idx != index:
names.append(actor.name)
result = bname
count = 0
while result in names:
count += 1
result = bname + "-" + str(count)
return result | def unique_name(self, name) | Generates a unique name.
:param name: the name to check
:type name: str
:return: the unique name
:rtype: str | 3.352046 | 3.445946 | 0.97275 |
self._name = self.unique_name(self._name)
self._full_name = None
self._logger = None
self._parent = parent | def parent(self, parent) | Sets the parent of the actor.
:param parent: the parent
:type parent: Actor | 6.064452 | 8.335482 | 0.727547 |
if self._full_name is None:
fn = self.name.replace(".", "\\.")
parent = self._parent
if parent is not None:
fn = parent.full_name + "." + fn
self._full_name = fn
return self._full_name | def full_name(self) | Obtains the full name of the actor.
:return: the full name
:rtype: str | 3.130739 | 3.354239 | 0.933368 |
opt = "annotation"
if opt not in options:
options[opt] = None
if opt not in self.help:
self.help[opt] = "The (optional) annotation for this actor (string)."
opt = "skip"
if opt not in options:
options[opt] = False
if opt not in self.help:
self.help[opt] = "Whether to skip (disable) this actor (bool)."
return super(Actor, self).fix_config(options) | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 3.537053 | 3.646428 | 0.970005 |
result = super(Actor, self).to_dict()
result["type"] = "Actor"
result["name"] = self.name
return result | def to_dict(self) | Returns a dictionary that represents this object, to be used for JSONification.
:return: the object dictionary
:rtype: dict | 3.865102 | 3.864309 | 1.000205 |
conf = {}
for k in d["config"]:
v = d["config"][k]
if isinstance(v, dict):
if u"type" in v:
typestr = v[u"type"]
else:
typestr = v["type"]
conf[str(k)] = classes.get_dict_handler(typestr)(v)
else:
conf[str(k)] = v
return classes.get_class(d["class"])(name=d["name"], config=conf) | def from_dict(cls, d) | Restores an object state from a dictionary, used in de-JSONification.
:param d: the object dictionary
:type d: dict
:return: the object
:rtype: object | 3.305866 | 3.406315 | 0.970511 |
value = self.config[name]
if value is None:
return default
elif isinstance(value, str) \
and value.startswith("@{") \
and value.endswith("}") \
and (value.find("@{", 1) == -1):
stname = value[2:len(value)-1]
if (self.storagehandler is not None) and (stname in self.storagehandler.storage):
return self.storagehandler.storage[stname]
else:
return default
else:
return value | def resolve_option(self, name, default=None) | Resolves the option, i.e., interprets "@{...}" values and retrievs them instead from internal
storage.
:param name: the name of the option
:type name: str
:param default: the optional default value
:type default: object
:return: the resolved value
:rtype: object | 3.059749 | 2.846262 | 1.075006 |
if isinstance(self, StorageHandler):
return self
elif self.parent is not None:
return self.parent.storagehandler
else:
return None | def storagehandler(self) | Returns the storage handler available to thise actor.
:return: the storage handler, None if not available | 3.073113 | 3.575494 | 0.859493 |
if self.skip:
return None
result = self.pre_execute()
if result is None:
try:
result = self.do_execute()
except Exception as e:
result = traceback.format_exc()
print(self.full_name + "\n" + result)
if result is None:
result = self.post_execute()
return result | def execute(self) | Executes the actor.
:return: None if successful, otherwise error message
:rtype: str | 3.442988 | 3.351134 | 1.02741 |
if (self._output is None) or (len(self._output) == 0):
result = None
else:
result = self._output.pop(0)
return result | def output(self) | Returns the next available output token.
:return: the next token, None if none available
:rtype: Token | 3.306227 | 3.052227 | 1.083218 |
result = s
while result.find("@{") > -1:
start = result.index("@{")
end = result.index("}", start)
name = result[start + 2:end]
value = self.storage[name]
if value is None:
raise("Storage value '" + name + "' not present, failed to expand string: " + s)
else:
result = result[0:start] + str(value) + result[end + 1:]
return result | def expand(self, s) | Expands all occurrences of "@{...}" within the string with the actual values currently stored
in internal storage.
:param s: the string to expand
:type s: str
:return: the expanded string
:rtype: str | 3.00763 | 2.506941 | 1.199721 |
if padded.startswith("@{") and padded.endswith("}"):
return padded[2:len(padded)-1]
else:
return padded | def extract(cls, padded) | Removes the surrounding "@{...}" from the name.
:param padded: the padded string
:type padded: str
:return: the extracted name
:rtype: str | 4.688678 | 2.843696 | 1.648797 |
options = super(ActorHandler, self).fix_config(options)
opt = "actors"
if opt not in options:
options[opt] = self.default_actors()
if opt not in self.help:
self.help[opt] = "The list of sub-actors that this actor manages."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 4.863182 | 5.458702 | 0.890904 |
result = super(ActorHandler, self).to_dict()
result["type"] = "ActorHandler"
del result["config"]["actors"]
result["actors"] = []
for actor in self.actors:
result["actors"].append(actor.to_dict())
return result | def to_dict(self) | Returns a dictionary that represents this object, to be used for JSONification.
:return: the object dictionary
:rtype: dict | 3.420422 | 3.510233 | 0.974414 |
result = super(ActorHandler, cls).from_dict(d)
if "actors" in d:
l = d["actors"]
for e in l:
if u"type" in e:
typestr = e[u"type"]
else:
typestr = e["type"]
result.actors.append(classes.get_dict_handler(typestr)(e))
return result | def from_dict(cls, d) | Restores an object state from a dictionary, used in de-JSONification.
:param d: the object dictionary
:type d: dict
:return: the object
:rtype: object | 4.226474 | 4.547175 | 0.929472 |
if actors is None:
actors = self.default_actors()
self.check_actors(actors)
self.config["actors"] = actors | def actors(self, actors) | Sets the sub-actors of the actor.
:param actors: the sub-actors
:type actors: list | 3.953598 | 6.754673 | 0.585313 |
result = 0
for actor in self.actors:
if not actor.skip:
result += 1
return result | def active(self) | Returns the count of non-skipped actors.
:return: the count
:rtype: int | 5.887525 | 3.317454 | 1.774712 |
result = None
for actor in self.actors:
if not actor.skip:
result = actor
break
return result | def first_active(self) | Returns the first non-skipped actor.
:return: the first active actor, None if not available
:rtype: Actor | 5.573334 | 3.892825 | 1.431694 |
result = None
for actor in reversed(self.actors):
if not actor.skip:
result = actor
break
return result | def last_active(self) | Returns the last non-skipped actor.
:return: the last active actor, None if not available
:rtype: Actor | 6.230399 | 4.085077 | 1.525161 |
result = -1
for index, actor in enumerate(self.actors):
if actor.name == name:
result = index
break
return result | def index_of(self, name) | Returns the index of the actor with the given name.
:param name: the name of the Actor to find
:type name: str
:return: the index, -1 if not found
:rtype: int | 3.072366 | 2.513223 | 1.222481 |
result = super(ActorHandler, self).setup()
if result is None:
self.update_parent()
try:
self.check_actors(self.actors)
except Exception as e:
result = str(e)
if result is None:
for actor in self.actors:
name = actor.name
newname = actor.unique_name(actor.name)
if name != newname:
actor.name = newname
if result is None:
for actor in self.actors:
if actor.skip:
continue
result = actor.setup()
if result is not None:
break
if result is None:
result = self._director.setup()
return result | def setup(self) | Configures the actor before execution.
:return: None if successful, otherwise error message
:rtype: str | 3.429972 | 3.094355 | 1.108461 |
for actor in self.actors:
if actor.skip:
continue
actor.wrapup()
super(ActorHandler, self).wrapup() | def wrapup(self) | Finishes up after execution finishes, does not remove any graphical output. | 6.024958 | 5.6696 | 1.062678 |
for actor in self.actors:
if actor.skip:
continue
actor.cleanup()
super(ActorHandler, self).cleanup() | def cleanup(self) | Destructive finishing up after execution stopped. | 6.326975 | 5.70747 | 1.108543 |
if not (self._stopping or self._stopped):
for actor in self.owner.actors:
actor.stop_execution()
self._stopping = True | def stop_execution(self) | Triggers the stopping of the object. | 6.042375 | 5.068565 | 1.192127 |
self._stopped = False
self._stopping = False
not_finished_actor = self.owner.first_active
pending_actors = []
finished = False
actor_result = None
while not (self.is_stopping() or self.is_stopped()) and not finished:
# determing starting point of next iteration
if len(pending_actors) > 0:
start_index = self.owner.index_of(pending_actors[-1].name)
else:
start_index = self.owner.index_of(not_finished_actor.name)
not_finished_actor = None
# iterate over actors
token = None
last_active = -1
if self.owner.active > 0:
last_active = self.owner.last_active.index
for i in range(start_index, last_active + 1):
# do we have to stop the execution?
if self.is_stopped() or self.is_stopping():
break
curr = self.owner.actors[i]
if curr.skip:
continue
# no token? get pending one or produce new one
if token is None:
if isinstance(curr, OutputProducer) and curr.has_output():
pending_actors.pop()
else:
actor_result = curr.execute()
if actor_result is not None:
self.owner.logger.error(
curr.full_name + " generated following error output:\n" + actor_result)
break
if isinstance(curr, OutputProducer) and curr.has_output():
token = curr.output()
else:
token = None
# still more to come?
if isinstance(curr, OutputProducer) and curr.has_output():
pending_actors.append(curr)
else:
# process token
curr.input = token
actor_result = curr.execute()
if actor_result is not None:
self.owner.logger.error(
curr.full_name + " generated following error output:\n" + actor_result)
break
# was a new token produced?
if isinstance(curr, OutputProducer):
if curr.has_output():
token = curr.output()
else:
token = None
# still more to come?
if curr.has_output():
pending_actors.append(curr)
else:
token = None
# token from last actor generated? -> store
if (i == self.owner.last_active.index) and (token is not None):
if self._record_output:
self._recorded_output.append(token)
# no token produced, ignore rest of actors
if isinstance(curr, OutputProducer) and (token is None):
break
# all actors finished?
finished = (not_finished_actor is None) and (len(pending_actors) == 0)
return actor_result | def do_execute(self) | Actual execution of the director.
:return: None if successful, otherwise error message
:rtype: str | 3.214465 | 3.159067 | 1.017536 |
super(Flow, self).check_actors(actors)
actor = self.first_active
if (actor is not None) and not base.is_source(actor):
raise Exception("First active actor is not a source: " + actor.full_name) | def check_actors(self, actors) | Performs checks on the actors that are to be used. Raises an exception if invalid setup.
:param actors: the actors to check
:type actors: list | 6.817731 | 7.26034 | 0.939037 |
with open(fname) as f:
content = f.readlines()
return Flow.from_json(''.join(content)) | def load(cls, fname) | Loads the flow from a JSON file.
:param fname: the file to load
:type fname: str
:return: the flow
:rtype: Flow | 6.168649 | 5.677999 | 1.086412 |
result = SequentialDirector(self)
result.record_output = False
result.allow_source = False
return result | def new_director(self) | Creates the director to use for handling the sub-actors.
:return: the director instance
:rtype: Director | 16.413773 | 19.180418 | 0.855757 |
super(Sequence, self).check_actors(actors)
actor = self.first_active
if (actor is not None) and not isinstance(actor, InputConsumer):
raise Exception("First active actor does not accept input: " + actor.full_name) | def check_actors(self, actors) | Performs checks on the actors that are to be used. Raises an exception if invalid setup.
:param actors: the actors to check
:type actors: list | 6.643405 | 7.699221 | 0.862867 |
self.first_active.input = self.input
result = self._director.execute()
if result is None:
self._output.append(self.input)
return result | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 10.945373 | 11.010391 | 0.994095 |
options = super(Tee, self).fix_config(options)
opt = "condition"
if opt not in options:
options[opt] = "True"
if opt not in self.help:
self.help[opt] = "The (optional) condition for teeing off the tokens; uses the 'eval' method, "\
"ie the expression must evaluate to a boolean value; storage values placeholders "\
"'@{...}' get replaced with their string representations before evaluating the "\
"expression (string)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 12.049687 | 12.825914 | 0.93948 |
super(Tee, self).check_actors(actors)
actor = self.first_active
if actor is None:
if self._requires_active_actors:
raise Exception("No active actor!")
elif not isinstance(actor, InputConsumer):
raise Exception("First active actor does not accept input: " + actor.full_name) | def check_actors(self, actors) | Performs checks on the actors that are to be used. Raises an exception if invalid setup.
:param actors: the actors to check
:type actors: list | 6.764783 | 7.40647 | 0.913361 |
result = None
teeoff = True
cond = self.storagehandler.expand(str(self.resolve_option("condition")))
if len(cond) > 0:
teeoff = bool(eval(cond))
if teeoff:
self.first_active.input = self.input
result = self._director.execute()
if result is None:
self._output.append(self.input)
return result | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 9.326387 | 9.448761 | 0.987049 |
options = super(Trigger, self).fix_config(options)
opt = "condition"
if opt not in options:
options[opt] = "True"
if opt not in self.help:
self.help[opt] = "The (optional) condition for teeing off the tokens; uses the 'eval' method, "\
"ie the expression must evaluate to a boolean value; storage values placeholders "\
"'@{...}' get replaced with their string representations before evaluating the "\
"expression (string)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 12.137281 | 13.249087 | 0.916084 |
actors = []
for actor in self.owner.actors:
if actor.skip:
continue
actors.append(actor)
if len(actors) == 0:
return
for actor in actors:
if not isinstance(actor, InputConsumer):
raise Exception("Actor does not accept any input: " + actor.full_name) | def check_actors(self) | Checks the actors of the owner. Raises an exception if invalid. | 4.586056 | 3.684227 | 1.244781 |
result = None
self._stopped = False
self._stopping = False
for actor in self.owner.actors:
if self.is_stopping() or self.is_stopped():
break
actor.input = self.owner.input
result = actor.execute()
if result is not None:
break
return result | def do_execute(self) | Actual execution of the director.
:return: None if successful, otherwise error message
:rtype: str | 5.060192 | 4.753039 | 1.064622 |
options = super(ContainerValuePicker, self).fix_config(options)
opt = "value"
if opt not in options:
options[opt] = "Model"
if opt not in self.help:
self.help[opt] = "The name of the container value to pick from the container (string)."
opt = "switch"
if opt not in options:
options[opt] = False
if opt not in self.help:
self.help[opt] = "Whether to switch the ouputs, i.e., forward the container to the sub-flow and the " \
+ "container value to the following actor instead (bool)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 5.30996 | 5.616788 | 0.945373 |
result = None
cont = self.input.payload
name = str(self.resolve_option("value"))
value = cont.get(name)
switch = bool(self.resolve_option("switch"))
if switch:
if self.first_active is not None:
self.first_active.input = self.input
result = self._director.execute()
if result is None:
self._output.append(Token(value))
else:
if self.first_active is not None:
self.first_active.input = Token(value)
result = self._director.execute()
if result is None:
self._output.append(self.input)
return result | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 4.40064 | 4.404368 | 0.999153 |
options = super(CommandlineToAny, self).fix_config(options)
opt = "wrapper"
if opt not in options:
options[opt] = "weka.core.classes.OptionHandler"
if opt not in self.help:
self.help[opt] = "The name of the wrapper class to use (string)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 6.682126 | 7.437073 | 0.898489 |
if isinstance(obj, str):
return
if isinstance(obj, unicode):
return
raise Exception("Unsupported class: " + self._input.__class__.__name__) | def check_input(self, obj) | Performs checks on the input object. Raises an exception if unsupported.
:param obj: the object to check
:type obj: object | 6.462538 | 6.383549 | 1.012374 |
cname = str(self.config["wrapper"])
self._output = classes.from_commandline(self._input, classname=cname)
return None | def convert(self) | Performs the actual conversion.
:return: None if successful, otherwise errors message
:rtype: str | 22.888205 | 24.028816 | 0.952532 |
if not plot.matplotlib_available:
logger.error("Matplotlib is not installed, plotting unavailable!")
return
if not isinstance(mat, ResultMatrix):
logger.error("Need to supply a result matrix!")
return
fig, ax = plt.subplots()
if axes_swapped:
ax.set_xlabel(measure)
ax.set_ylabel("Classifiers")
else:
ax.set_xlabel("Classifiers")
ax.set_ylabel(measure)
ax.set_title(title)
fig.canvas.set_window_title(title)
ax.grid(True)
ticksx = []
ticks = []
inc = 1.0 / float(mat.columns)
for i in range(mat.columns):
ticksx.append((i + 0.5) * inc)
ticks.append("[" + str(i+1) + "]")
plt.xticks(ticksx, ticks)
plt.xlim([0.0, 1.0])
for r in range(mat.rows):
x = []
means = []
stdevs = []
for c in range(mat.columns):
mean = mat.get_mean(c, r)
stdev = mat.get_stdev(c, r)
if not math.isnan(mean):
x.append((c + 0.5) * inc)
means.append(mean)
if not math.isnan(stdev):
stdevs.append(stdev)
plot_label = mat.get_row_name(r)
if show_stdev:
ax.errorbar(x, means, yerr=stdevs, fmt='-o', ls="-", label=plot_label)
else:
ax.plot(x, means, "o-", label=plot_label)
plt.draw()
plt.legend(loc=key_loc, shadow=True)
if outfile is not None:
plt.savefig(outfile)
if wait:
plt.show() | def plot_experiment(mat, title="Experiment", axes_swapped=False, measure="Statistic", show_stdev=False,
key_loc="lower right", outfile=None, wait=True) | Plots the results from an experiment.
:param mat: the result matrix to plot
:type mat: ResultMatrix
:param title: the title for the experiment
:type title: str
:param axes_swapped: whether the axes whether swapped ("sets x cls" or "cls x sets")
:type axes_swapped: bool
:param measure: the measure that is being displayed
:type measure: str
:param show_stdev: whether to show the standard deviation as error bar
:type show_stdev: bool
:param key_loc: the location string for the key
:type key_loc: str
:param outfile: the output file, ignored if None
:type outfile: str
:param wait: whether to wait for the user to close the plot
:type wait: bool | 2.154227 | 2.10416 | 1.023794 |
if percent <= 0 or percent >= 100:
return data
data = Instances.copy_instances(data)
data.randomize(Random(seed))
data = Instances.copy_instances(data, 0, int(round(data.num_instances * percent / 100.0)))
return data | def create_subsample(data, percent, seed=1) | Generates a subsample of the dataset.
:param data: the data to create the subsample from
:type data: Instances
:param percent: the percentage (0-100)
:type percent: float
:param seed: the seed value to use
:type seed: int | 3.74644 | 3.325949 | 1.126427 |
if len(preds) == 0:
return None
is_numeric = isinstance(preds[0], NumericPrediction)
# create header
atts = []
if is_numeric:
atts.append(Attribute.create_numeric("index"))
atts.append(Attribute.create_numeric("weight"))
atts.append(Attribute.create_numeric("actual"))
atts.append(Attribute.create_numeric("predicted"))
atts.append(Attribute.create_numeric("error"))
else:
atts.append(Attribute.create_numeric("index"))
atts.append(Attribute.create_numeric("weight"))
atts.append(data.class_attribute.copy(name="actual"))
atts.append(data.class_attribute.copy(name="predicted"))
atts.append(Attribute.create_nominal("error", ["no", "yes"]))
atts.append(Attribute.create_numeric("classification"))
for i in range(data.class_attribute.num_values):
atts.append(Attribute.create_numeric("distribution-" + data.class_attribute.value(i)))
result = Instances.create_instances("Predictions", atts, len(preds))
count = 0
for pred in preds:
count += 1
if is_numeric:
values = array([count, pred.weight, pred.actual, pred.predicted, pred.error])
else:
if pred.actual == pred.predicted:
error = 0.0
else:
error = 1.0
l = [count, pred.weight, pred.actual, pred.predicted, error, max(pred.distribution)]
for i in range(data.class_attribute.num_values):
l.append(pred.distribution[i])
values = array(l)
inst = Instance.create_instance(values)
result.add_instance(inst)
return result | def predictions_to_instances(data, preds) | Turns the predictions turned into an Instances object.
:param data: the original dataset format
:type data: Instances
:param preds: the predictions to convert
:type preds: list
:return: the predictions, None if no predictions present
:rtype: Instances | 2.2226 | 2.286524 | 0.972043 |
if self.is_batchpredictor:
return typeconv.double_matrix_to_ndarray(self.__distributions(data.jobject))
else:
return None | def distributions_for_instances(self, data) | Peforms predictions, returning the class distributions.
:param data: the Instances to get the class distributions for
:type data: Instances
:return: the class distribution matrix, None if not a batch predictor
:rtype: ndarray | 22.877647 | 14.09586 | 1.623005 |
if self.is_batchpredictor:
javabridge.call(self.jobject, "setBatchSize", "(Ljava/lang/String;)V", size) | def batch_size(self, size) | Sets the batch size, in case this classifier is a batch predictor.
:param size: the size of the batch
:type size: str | 6.719282 | 4.295274 | 1.564343 |
if not self.check_type(self.jobject, "weka.classifiers.Sourcable"):
return None
return javabridge.call(self.jobject, "toSource", "(Ljava/lang/String;)Ljava/lang/String;", classname) | def to_source(self, classname) | Returns the model as Java source code if the classifier implements weka.classifiers.Sourcable.
:param classname: the classname for the generated Java code
:type classname: str
:return: the model as source code string
:rtype: str | 4.361536 | 3.517056 | 1.24011 |
if isinstance(evl, str):
evl = self.tags_evaluation.find(evl)
if isinstance(evl, Tag):
evl = SelectedTag(tag_id=evl.ident, tags=self.tags_evaluation)
javabridge.call(self.jobject, "setEvaluation", "(Lweka/core/SelectedTag;)V", evl.jobject) | def evaluation(self, evl) | Sets the statistic to use for evaluation.
:param evl: the statistic
:type evl: SelectedTag, Tag or str | 4.560258 | 3.632719 | 1.255329 |
result = {}
result["property"] = javabridge.call(self.jobject, "getXProperty", "()Ljava/lang/String;")
result["min"] = javabridge.call(self.jobject, "getXMin", "()D")
result["max"] = javabridge.call(self.jobject, "getXMax", "()D")
result["step"] = javabridge.call(self.jobject, "getXStep", "()D")
result["base"] = javabridge.call(self.jobject, "getXBase", "()D")
result["expression"] = javabridge.call(self.jobject, "getXExpression", "()Ljava/lang/String;")
return result | def x(self) | Returns a dictionary with all the current values for the X of the grid.
Keys for the dictionary: property, min, max, step, base, expression
Types: property=str, min=float, max=float, step=float, base=float, expression=str
:return: the dictionary with the parameters
:rtype: dict | 1.849737 | 1.481595 | 1.248477 |
if "property" in d:
javabridge.call(self.jobject, "setXProperty", "(Ljava/lang/String;)V", d["property"])
if "min" in d:
javabridge.call(self.jobject, "setXMin", "(D)V", d["min"])
if "max" in d:
javabridge.call(self.jobject, "setXMax", "(D)V", d["max"])
if "step" in d:
javabridge.call(self.jobject, "setXStep", "(D)V", d["step"])
if "base" in d:
javabridge.call(self.jobject, "setXBase", "(D)V", d["base"])
if "expression" in d:
javabridge.call(self.jobject, "setXExpression", "(Ljava/lang/String;)V", d["expression"]) | def x(self, d) | Allows to configure the X of the grid with one method call.
Keys for the dictionary: property, min, max, step, base, expression
Types: property=str, min=float, max=float, step=float, base=float, expression=str
:param d: the dictionary with the parameters
:type d: dict | 1.56284 | 1.337292 | 1.16866 |
result = {}
result["property"] = javabridge.call(self.jobject, "getYProperty", "()Ljava/lang/String;")
result["min"] = javabridge.call(self.jobject, "getYMin", "()D")
result["max"] = javabridge.call(self.jobject, "getYMax", "()D")
result["step"] = javabridge.call(self.jobject, "getYStep", "()D")
result["base"] = javabridge.call(self.jobject, "getYBase", "()D")
result["expression"] = javabridge.call(self.jobject, "getYExpression", "()Ljava/lang/String;")
return result | def y(self) | Returns a dictionary with all the current values for the Y of the grid.
Keys for the dictionary: property, min, max, step, base, expression
Types: property=str, min=float, max=float, step=float, base=float, expression=str
:return: the dictionary with the parameters
:rtype: dict | 1.849688 | 1.475399 | 1.253686 |
if "property" in d:
javabridge.call(self.jobject, "setYProperty", "(Ljava/lang/String;)V", d["property"])
if "min" in d:
javabridge.call(self.jobject, "setYMin", "(D)V", d["min"])
if "max" in d:
javabridge.call(self.jobject, "setYMax", "(D)V", d["max"])
if "step" in d:
javabridge.call(self.jobject, "setYStep", "(D)V", d["step"])
if "base" in d:
javabridge.call(self.jobject, "setYBase", "(D)V", d["base"])
if "expression" in d:
javabridge.call(self.jobject, "setYExpression", "(Ljava/lang/String;)V", d["expression"]) | def y(self, d) | Allows to configure the Y of the grid with one method call.
Keys for the dictionary: property, min, max, step, base, expression
Types: property=str, min=float, max=float, step=float, base=float, expression=str
:param d: the dictionary with the parameters
:type d: dict | 1.553662 | 1.315687 | 1.180875 |
objects = javabridge.get_env().get_object_array_elements(
javabridge.call(self.jobject, "getClassifiers", "()[Lweka/classifiers/Classifier;"))
result = []
for obj in objects:
result.append(Classifier(jobject=obj))
return result | def classifiers(self) | Returns the list of base classifiers.
:return: the classifier list
:rtype: list | 3.080954 | 3.158396 | 0.97548 |
obj = []
for classifier in classifiers:
obj.append(classifier.jobject)
javabridge.call(self.jobject, "setClassifiers", "([Lweka/classifiers/Classifier;)V", obj) | def classifiers(self, classifiers) | Sets the base classifiers.
:param classifiers: the list of base classifiers to use
:type classifiers: list | 3.670161 | 4.211043 | 0.871556 |
jinst1 = None
if inst1 is not None:
jinst1 = inst1.jobject
return javabridge.call(self.jobject, "eval", "(IILweka/core/Instance;)D", id1, id2, jinst1) | def eval(self, id1, id2, inst1) | Computes the result of the kernel function for two instances. If id1 == -1, eval use inst1 instead of an
instance in the dataset.
:param id1: the index of the first instance in the dataset
:type id1: int
:param id2: the index of the second instance in the dataset
:type id2: int
:param inst1: the instance corresponding to id1 (used if id1 == -1)
:type inst1: Instance | 4.688893 | 4.291958 | 1.092483 |
result = javabridge.static_call(
"weka/classifiers/KernelHelper", "getKernel",
"(Ljava/lang/Object;)Lweka/classifiers/functions/supportVector/Kernel;",
self.jobject)
if result is None:
return None
else:
return Kernel(jobject=result) | def kernel(self) | Returns the current kernel.
:return: the kernel or None if none found
:rtype: Kernel | 3.737587 | 3.448769 | 1.083745 |
result = javabridge.static_call(
"weka/classifiers/KernelHelper", "setKernel",
"(Ljava/lang/Object;Lweka/classifiers/functions/supportVector/Kernel;)Z",
self.jobject, kernel.jobject)
if not result:
raise Exception("Failed to set kernel!") | def kernel(self, kernel) | Sets the kernel.
:param kernel: the kernel to set
:type kernel: Kernel | 3.729146 | 3.807507 | 0.97942 |
return Instances(
javabridge.call(
self.jobject, "applyCostMatrix", "(Lweka/core/Instances;Ljava/util/Random;)Lweka/core/Instances;",
data.jobject, rnd.jobject)) | def apply_cost_matrix(self, data, rnd) | Applies the cost matrix to the data.
:param data: the data to apply to
:type data: Instances
:param rnd: the random number generator
:type rnd: Random | 4.105083 | 4.021314 | 1.020831 |
if inst is None:
costs = javabridge.call(
self.jobject, "expectedCosts", "([D)[D", javabridge.get_env().make_double_array(class_probs))
return javabridge.get_env().get_double_array_elements(costs)
else:
costs = javabridge.call(
self.jobject, "expectedCosts", "([DLweka/core/Instance;)[D",
javabridge.get_env().make_double_array(class_probs), inst.jobject)
return javabridge.get_env().get_double_array_elements(costs) | def expected_costs(self, class_probs, inst=None) | Calculates the expected misclassification cost for each possible class value, given class probability
estimates.
:param class_probs: the class probabilities
:type class_probs: ndarray
:return: the calculated costs
:rtype: ndarray | 2.50518 | 2.483672 | 1.00866 |
return javabridge.call(
self.jobject, "getCell", "(II)Ljava/lang/Object;", row, col) | def get_cell(self, row, col) | Returns the JB_Object at the specified location.
:param row: the 0-based index of the row
:type row: int
:param col: the 0-based index of the column
:type col: int
:return: the object in that cell
:rtype: JB_Object | 6.854106 | 7.215421 | 0.949925 |
if isinstance(obj, JavaObject):
obj = obj.jobject
javabridge.call(
self.jobject, "setCell", "(IILjava/lang/Object;)V", row, col, obj) | def set_cell(self, row, col, obj) | Sets the JB_Object at the specified location. Automatically unwraps JavaObject.
:param row: the 0-based index of the row
:type row: int
:param col: the 0-based index of the column
:type col: int
:param obj: the object for that cell
:type obj: object | 4.242689 | 4.065327 | 1.043628 |
if inst is None:
return javabridge.call(
self.jobject, "getElement", "(II)D", row, col)
else:
return javabridge.call(
self.jobject, "getElement", "(IILweka/core/Instance;)D", row, col, inst.jobject) | def get_element(self, row, col, inst=None) | Returns the value at the specified location.
:param row: the 0-based index of the row
:type row: int
:param col: the 0-based index of the column
:type col: int
:param inst: the Instace
:type inst: Instance
:return: the value in that cell
:rtype: float | 3.133723 | 2.867018 | 1.093025 |
javabridge.call(
self.jobject, "setElement", "(IID)V", row, col, value) | def set_element(self, row, col, value) | Sets the float value at the specified location.
:param row: the 0-based index of the row
:type row: int
:param col: the 0-based index of the column
:type col: int
:param value: the float value for that cell
:type value: float | 8.56471 | 8.109188 | 1.056174 |
if inst is None:
return javabridge.call(
self.jobject, "getMaxCost", "(I)D", class_value)
else:
return javabridge.call(
self.jobject, "getElement", "(ILweka/core/Instance;)D", class_value, inst.jobject) | def get_max_cost(self, class_value, inst=None) | Gets the maximum cost for a particular class value.
:param class_value: the class value to get the maximum cost for
:type class_value: int
:param inst: the Instance
:type inst: Instance
:return: the cost
:rtype: float | 3.550163 | 3.226193 | 1.100419 |
if output is None:
generator = []
else:
generator = [output.jobject]
javabridge.call(
self.jobject, "crossValidateModel",
"(Lweka/classifiers/Classifier;Lweka/core/Instances;ILjava/util/Random;[Ljava/lang/Object;)V",
classifier.jobject, data.jobject, num_folds, rnd.jobject, generator) | def crossvalidate_model(self, classifier, data, num_folds, rnd, output=None) | Crossvalidates the model using the specified data, number of folds and random number generator wrapper.
:param classifier: the classifier to cross-validate
:type classifier: Classifier
:param data: the data to evaluate on
:type data: Instances
:param num_folds: the number of folds
:type num_folds: int
:param rnd: the random number generator to use
:type rnd: Random
:param output: the output generator to use
:type output: PredictionOutput | 2.843779 | 2.779538 | 1.023112 |
if title is None:
return javabridge.call(
self.jobject, "toSummaryString", "()Ljava/lang/String;")
else:
return javabridge.call(
self.jobject, "toSummaryString", "(Ljava/lang/String;Z)Ljava/lang/String;", title, complexity) | def summary(self, title=None, complexity=False) | Generates a summary.
:param title: optional title
:type title: str
:param complexity: whether to print the complexity information as well
:type complexity: bool
:return: the summary
:rtype: str | 2.538503 | 2.559868 | 0.991654 |
if title is None:
return javabridge.call(
self.jobject, "toClassDetailsString", "()Ljava/lang/String;")
else:
return javabridge.call(
self.jobject, "toClassDetailsString", "(Ljava/lang/String;)Ljava/lang/String;", title) | def class_details(self, title=None) | Generates the class details.
:param title: optional title
:type title: str
:return: the details
:rtype: str | 2.634666 | 2.622409 | 1.004674 |
if title is None:
return javabridge.call(self.jobject, "toMatrixString", "()Ljava/lang/String;")
else:
return javabridge.call(self.jobject, "toMatrixString", "(Ljava/lang/String;)Ljava/lang/String;", title) | def matrix(self, title=None) | Generates the confusion matrix.
:param title: optional title
:type title: str
:return: the matrix
:rtype: str | 2.349232 | 2.192837 | 1.071321 |
preds = javabridge.get_collection_wrapper(
javabridge.call(self.jobject, "predictions", "()Ljava/util/ArrayList;"))
if self.discard_predictions:
result = None
else:
result = []
for pred in preds:
if is_instance_of(pred, "weka.classifiers.evaluation.NominalPrediction"):
result.append(NominalPrediction(pred))
elif is_instance_of(pred, "weka.classifiers.evaluation.NumericPrediction"):
result.append(NumericPrediction(pred))
else:
result.append(Prediction(pred))
return result | def predictions(self) | Returns the predictions.
:return: the predictions. None if not available
:rtype: list | 2.76897 | 2.752521 | 1.005976 |
javabridge.call(
self.jobject, "print", "(Lweka/classifiers/Classifier;Lweka/core/Instances;)V",
cls.jobject, data.jobject) | def print_all(self, cls, data) | Prints the header, classifications and footer to the buffer.
:param cls: the classifier
:type cls: Classifier
:param data: the test data
:type data: Instances | 4.667285 | 3.610682 | 1.292633 |
javabridge.call(
self.jobject, "printClassifications", "(Lweka/classifiers/Classifier;Lweka/core/Instances;)V",
cls.jobject, data.jobject) | def print_classifications(self, cls, data) | Prints the classifications to the buffer.
:param cls: the classifier
:type cls: Classifier
:param data: the test data
:type data: Instances | 3.788831 | 3.078274 | 1.23083 |
javabridge.call(
self.jobject, "printClassification", "(Lweka/classifiers/Classifier;Lweka/core/Instance;I)V",
cls.jobject, inst.jobject, index) | def print_classification(self, cls, inst, index) | Prints the classification to the buffer.
:param cls: the classifier
:type cls: Classifier
:param inst: the test instance
:type inst: Instance
:param index: the 0-based index of the test instance
:type index: int | 3.153171 | 2.810025 | 1.122115 |
javabridge.call(self.jobject, "tokenize", "(Ljava/lang/String;)V", s)
return TokenIterator(self) | def tokenize(self, s) | Tokenizes the string.
:param s: the string to tokenize
:type s: str
:return: the iterator
:rtype: TokenIterator | 5.553123 | 5.123833 | 1.083783 |
parser = argparse.ArgumentParser(
description='Executes a data generator from the command-line. Calls JVM start/stop automatically.')
parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories")
parser.add_argument("-X", metavar="heap", dest="heap", help="max heap size for jvm, e.g., 512m")
parser.add_argument("datagenerator", help="data generator classname, e.g., "
+ "weka.datagenerators.classifiers.classification.LED24")
parser.add_argument("option", nargs=argparse.REMAINDER, help="additional data generator options")
parsed = parser.parse_args()
jars = []
if parsed.classpath is not None:
jars = parsed.classpath.split(os.pathsep)
jvm.start(jars, max_heap_size=parsed.heap, packages=True)
logger.debug("Commandline: " + join_options(sys.argv[1:]))
try:
generator = DataGenerator(classname=parsed.datagenerator)
if len(parsed.option) > 0:
generator.options = parsed.option
DataGenerator.make_data(generator, parsed.option)
except Exception as e:
print(e)
finally:
jvm.stop() | def main() | Runs a datagenerator from the command-line. Calls JVM start/stop automatically.
Use -h to see all options. | 3.856717 | 3.25036 | 1.186551 |
data = javabridge.call(self.jobject, "defineDataFormat", "()Lweka/core/Instances;")
if data is None:
return None
else:
return Instances(data) | def define_data_format(self) | Returns the data format.
:return: the data format
:rtype: Instances | 4.287526 | 4.594821 | 0.933121 |
data = javabridge.call(self.jobject, "getDatasetFormat", "()Lweka/core/Instances;")
if data is None:
return None
else:
return Instances(data) | def dataset_format(self) | Returns the dataset format.
:return: the format
:rtype: Instances | 4.017037 | 3.814374 | 1.053131 |
data = javabridge.call(self.jobject, "generateExample", "()Lweka/core/Instance;")
if data is None:
return None
else:
return Instance(data) | def generate_example(self) | Returns a single Instance.
:return: the next example
:rtype: Instance | 4.123404 | 3.782936 | 1.090001 |
data = javabridge.call(self.jobject, "generateExamples", "()Lweka/core/Instances;")
if data is None:
return None
else:
return Instances(data) | def generate_examples(self) | Returns complete dataset.
:return: the generated dataset
:rtype: Instances | 4.425352 | 4.225058 | 1.047406 |
return from_commandline(
to_commandline(generator), classname=classes.get_classname(DataGenerator())) | def make_copy(cls, generator) | Creates a copy of the generator.
:param generator: the generator to copy
:type generator: DataGenerator
:return: the copy of the generator
:rtype: DataGenerator | 35.117493 | 34.649239 | 1.013514 |
options = super(FileSupplier, self).fix_config(options)
opt = "files"
if opt not in options:
options[opt] = []
if opt not in self.help:
self.help[opt] = "The files to output (list of string)."
return options | def fix_config(self, options) | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | 5.024352 | 5.742596 | 0.874927 |
for f in self.resolve_option("files"):
self._output.append(Token(f))
return None | def do_execute(self) | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | 24.938322 | 27.995625 | 0.890794 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.