code
stringlengths
1
18.2k
def getSkosConcept(self, id=None, uri=None, match=None): """ get the saved skos concept with given ID or via other methods... Note: it tries to guess what is being passed as above """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not uri.startswith("http://"): mat...
def getEntity(self, id=None, uri=None, match=None): """ get a generic entity with given ID or via other methods... """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not uri.startswith("http://"): match = uri uri = None if match: if type(match) != type("string"): r...
x.uri.lower() == uri.lower(): return x for x in self.properties: if id and x.id == id: return x if uri and x.uri.lower() == uri.lower(): return x return None
def getOntology(self, id=None, uri=None, match=None): """ get the saved-ontology with given ID or via other methods... """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not uri.startswith("http://"): match = uri uri = None if match: if type(match) != type("string"...
def nextClass(self, classuri): """Returns the next class in the list of classes. If it's the last one, returns the first one.""" if classuri == self.classes[-1].uri: return self.classes[0] flag = False for x in self.classes: if flag == True: return x if x.uri == classuri: flag = True return None
def nextProperty(self, propuri): """Returns the next property in the list of properties. If it's the last one, returns the first one.""" if propuri == self.properties[-1].uri: return self.properties[0] flag = False for x in self.properties: if flag == True: return x if x.uri == propuri: flag = True return None
def nextConcept(self, concepturi): """Returns the next skos concept in the list of concepts. If it's the last one, returns the first one.""" if concepturi == self.skosConcepts[-1].uri: return self.skosConcepts[0] flag = False for x in self.skosConcepts: if flag == True: return x if x.uri == concepturi: flag = True retu...
def printSkosTree(self, element = None, showids=False, labels=False, showtype=False): """ Print nicely into stdout the SKOS tree of an ontology Note: indentation is made so that ids up to 3 digits fit in, plus a space. [123]1-- [1]123-- [12]12-- """ TYPE_MARGIN = 13 # length for skos:concept if not element: # first tim...
def highlight(code, lexer, **kwargs): """ Returns highlighted code ``div`` tag from ``HtmlFormatter`` Lexer is guessed by ``lexer`` name arguments are passed into the formatter Syntax:: {% highlight [source code] [lexer name] [formatter options] %} Example:: {% highlight 'print "Hello World"' python linenos=true %} """...
def highlight_block(context, nodelist, lexer, **kwargs): """ Code is nodelist ``rendered`` in ``context`` Returns highlighted code ``div`` tag from ``HtmlFormatter`` Lexer is guessed by ``lexer`` name arguments are passed into the formatter Syntax:: {% highlight_block [lexer name] [formatter options] %} ... source code...
def warning(message, code='WARNING'): """Display Warning. Method prints the warning message, message being given as an input. Arguments: message {string} -- The message to be displayed. """ now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') output = now + ' [' + torn.plugins.colors.WARNING + \ code + torn.plugins.color...
def info(message, code='INFO'): """Display Information. Method prints the information message, message being given as an input. Arguments: message {string} -- The message to be displayed. """ now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') output = now + ' [' + torn.plugins.colors.OKBLUE + \ code + torn.plugins.colo...
def error(message, code='ERROR'): """Display Error. Method prints the error message, message being given as an input. Arguments: message {string} -- The message to be displayed. """ now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') output = now + ' [' + torn.plugins.colors.FAIL + \ code + torn.plugins.colors.ENDC + ']...
def render(self, template, **data): """Renders the template using Jinja2 with given data arguments. """ if(type(template) != str): raise TypeError("String expected") env = Environment( loader=FileSystemLoader(os.getcwd() + '/View'), autoescape=select_autoescape() ) template = env.get_template(template) return self.fini...
def match(self, row): """ Returns True if the row matches one or more child conditions. Returns False otherwise. :param dict row: The row. :rtype: bool """ for condition in self._conditions: if condition.match(row): return True return False
def wait_until(time_label): ''' Calculates the number of seconds that the process needs to sleep ''' if time_label == 'next_minute': gevent.sleep(60 - int(time.time()) % 60) elif time_label == 'next_hour': gevent.sleep(3600 - int(time.time()) % 3600) elif time_label == 'tomorrow': gevent.sleep(86400 - int(time.time()) ...
def next(self): ''' Never return StopIteration ''' if self.started is False: self.started = True now_ = datetime.now() if self.hour: # Fixed hour in a day # Next run will be the next day scheduled = now_.replace(hour=self.hour, minute=self.minute, second=self.second, microsecond=0) if scheduled == now_: return timedelt...
def schedule(self, name, timer, func, *args, **kwargs): ''' ts = Scheduler('my_task') ts.schedule(every(seconds=10), handle_message, "Every 10 seconds") ts.schedule(every(seconds=30), fetch_url, url="http://yahoo.com", section="stock_ticker") ts.run_forever() ''' self.tasks.append(Task(name, func, timer, *args, **kwarg...
def unschedule(self, task_name): ''' Removes a task from scheduled jobs but it will not kill running tasks ''' for greenlet in self.waiting[task_name]: try: gevent.kill(greenlet) except BaseException: pass
def stop_task(self, task_name): ''' Stops a running or dead task ''' for greenlet in self.active[task_name]: try: # Do not need to check if greenlet is dead, gevent does it already gevent.kill(greenlet) self.active[task_name] = [] except BaseException: pass
def _remove_dead_greenlet(self, task_name): ''' Removes dead greenlet or done task from active list ''' for greenlet in self.active[task_name]: try: # Allows active greenlet continue to run if greenlet.dead: self.active[task_name].remove(greenlet) except BaseException: pass
def run(self, task): ''' Runs a task and re-schedule it ''' self._remove_dead_greenlet(task.name) if isinstance(task.timer, types.GeneratorType): # Starts the task immediately greenlet_ = gevent.spawn(task.action, *task.args, **task.kwargs) self.active[task.name].append(greenlet_) try: # total_seconds is available in P...
def run_tasks(self): ''' Runs all assigned task in separate green threads. If the task should not be run, schedule it ''' pool = Pool(len(self.tasks)) for task in self.tasks: # Launch a green thread to schedule the task # A task will be managed by 2 green thread: execution thread and scheduling thread pool.spawn(self.r...
def run_forever(self, start_at='once'): """ Starts the scheduling engine @param start_at: 'once' -> start immediately 'next_minute' -> start at the first second of the next minutes 'next_hour' -> start 00:00 (min) next hour 'tomorrow' -> start at 0h tomorrow """ if start_at not in ('once', 'next_minute', 'next_hour', '...
def aba_onto2nx(str_gr_id=10): """ Downloads and parse the Allen Brain Atlas ontologies into a network object More information about Allen Brain Atlas API can be found using following links: http://help.brain-map.org/display/api/Atlas+Drawings+and+Ontologies#AtlasDrawingsandOntologies-StructuresAndOntologies http://hel...
the recursive function root = str_gr_json['msg'][0] root_dct = {key: value for key, value in root.items() if key not in ['children', 'id']} netw.add_node(root['id'], attr_dict=root_dct) add_children(root, netw) return netw
def create_or_append_to_zip(file_handle, zip_path, arc_name=None): """ Append file_handle to given zip_path with name arc_name if given, else file_handle. zip_path will be created. :param file_handle: path to file or file-like object :param zip_path: path to zip archive :param arc_name: optional filename in archive """...
def zipdir(src_path, target_path, wrapdir=''): """ Zips the pat :param path: the path to the directory :param ziph: the zipfile handle :param wrapdir: wrap all contents in an additional dir :return: """ zipf = zipfile.ZipFile(target_path, 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(src_path): for file i...
def compare_version(version1, version2): """ Compares two versions. """ def normalize(v): return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")] return (normalize(version1) > normalize(version2))-(normalize(version1) < normalize(version2))
def encode(self): """ Encodes the value of the field and put it in the element also make the check for nil=true if there is one :return: returns the encoded element :rtype: xml.etree.ElementTree.Element """ element = ElementTree.Element(self.name) element = self._set_nil(element, lambda value: str(value)) return elemen...
def _set_nil(self, element, value_parser): """ Method to set an attribute of the element. If the value of the field is None then set the nil='true' attribute in the element :param element: the element which needs to be modified :type element: xml.etree.ElementTree.Element :param value_parser: the lambda function which ...
def main(input_filename, format): """ Calculate the fingerprint hashses of the referenced audio file and save to disk as a pickle file """ # open the file & convert to wav song_data = AudioSegment.from_file(input_filename, format=format) song_data = song_data.set_channels(1) # convert to mono wav_tmp = song_data.export...
pairs return fingerprints
def read_header(self): """Hardware configuration A505 Head configuration A504 User configuration A500""" with open(self.filepath, 'rb') as instrumentDataFile: while True: sync = instrumentDataFile.read(1) if not sync: break elif sync == '\xa5': id = instrumentDataFile.read(1) if id == '\x05': instrumentDataFile.seek(in...
{}""".format( self[ 'hardwareConfiguration' ].checksum, self[ 'headConfiguration' ].checksum, self[ 'userConfiguration' ].checksum, instrumentDataFile.tell()))
def format(self, template=None): """ Substitutes variables within template with that of fields' """ pattern = r"(?:<([^<]*?)\$(\w+)([^>]*?)>)" s = sub(pattern, self._format_repl, template or self.template) s = self._str_fix_whitespace(s) return s
def begin(request, provider): """ Display authentication form. This is also the first step in registration. The actual login is in social_complete function below. """ # store url to where user will be redirected request.session['next_url'] = request.GET.get("next") or settings.LOGIN_REDIRECT_URL # start the authenticat...
def complete(request, provider): """ After first step of net authentication, we must validate the response. If everything is ok, we must do the following: 1. If user is already authenticated: a. Try to login him again (strange variation but we must take it to account). b. Create new netID record in database. c. Merge a...
extra fields by hand. """ # merge data from POST and GET methods data = request.GET.copy() data.update(request.POST) # In case of skipping begin step. if 'next_url' not in request.session: request.session['next_url'] = request.GET.get("next") or settings.LOGIN_REDIRECT_URL backend = get_backend(provider) response = bac...
def extra(request, provider): """ Handle registration of new user with extra data for profile """ identity = request.session.get('identity', None) if not identity: raise Http404 if request.method == "POST": form = str_to_class(settings.EXTRA_FORM)(request.POST) if form.is_valid(): user = form.save(request, identity, pr...
def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" if inspect.isclass(object): mro = (object,) + inspect.getmro(object) else: mro = () results = [] processed = set() names = dir(object) # :d...
in the __dict__. try: value = getattr(object, key) # handle the duplicate key if key in processed: raise AttributeError except AttributeError: for base in mro: if key in base.__dict__: value = base.__dict__[key] break else: # could be a (currently) missing slot member, or a buggy # __dir__; discard and move on continue...
def _wrap(obj, wrapper=None, methods_to_add=(), name=None, skip=(), wrap_return_values=False, wrap_filenames=(), filename=None, wrapped_name_func=None, wrapped=None): """ Wrap module, class, function or another variable recursively :param Any obj: Object to wrap recursively :param Optional[Callable] wrapper: Wrapper to...
bool wrap_return_values: If try, wrap return values of callables (only types, supported by wrap function \ are supported) :param Collection[str] wrap_filenames: Files to wrap :param Optional[str] filename: Source file of `obj` :param Optional[Callable[Any, str]] wrapped_name_func: Function that accepts `obj` as argumen...
PyUnresolvedReferences original_obj_object = cls._original_obj(*args, **kwargs) # noinspection PyArgumentList result = _wrap(obj=original_obj_object, wrapper=wrapper, methods_to_add=methods_to_add, name=name, skip=skip, wrap_return_values=wrap_return_values, wrap_filenames=wrap_filenames, filename=filename, wrapped_nam...
result = ObjectType.FUNCTION_OR_METHOD elif inspect.iscoroutine(object=obj): result = ObjectType.COROUTINE else: result = ObjectType.OBJECT return result def create_proxy(proxy_type): return { ProxyType.MODULE: ModuleProxy(name=name), ProxyType.CLASS: ClassProxy, ProxyType.OBJECT: ObjectProxy(), }[proxy_type] def add_m...
add_methods() if obj_type == ObjectType.CLASS: for attr_name, attr_value in members: if need_to_wrap(): raises_exception = (isinstance(attr_value, tuple) and len(attr_value) > 0 and attr_value[0] == RAISES_EXCEPTION) if raises_exception and not obj_type == ObjectType.MODULE: def raise_exception(self): _ = self raise at...
def is_magic(obj): return is_magic_name(name=obj.__name__) # noinspection PyShadowingNames def is_coroutine_function(obj, wrapper): return inspect.iscoroutinefunction(object=wrapper(obj)) and not is_magic(obj=obj) # noinspection PyShadowingNames def wrap_call_and_wrap_return_values(obj, wrapper): if is_coroutine_functi...
it. # noinspection PyShadowingNames name = args[1] attr_value = obj_with_original_obj_as_self(*args, **kwargs) if is_magic_name(name=name): return attr_value else: # noinspection PyShadowingNames,PyArgumentList return _wrap(obj=attr_value, wrapper=wrapper, methods_to_add=methods_to_add, name=name, skip=skip, wrap_retur...
hasattr(obj, '__file__') else sys.modules[obj.__module__].__file__ if hasattr(obj, '__module__') else None) except (AttributeError, KeyError): result = None return result result = _get_obj_file(obj=obj) if result is None: result = _get_obj_file(obj=type(obj)) return result def get_obj_library_files(): obj_file = get_ob...
or filename # noinspection PyUnusedLocal members = [] with suppress(ModuleNotFoundError): members = getmembers(object=obj) try: already_wrapped = key in _wrapped_objs except TypeError: already_wrapped = False if filename not in wrap_filenames or is_in_skip(): wrapped = obj elif already_wrapped: wrapped = _wrapped_objs[...
def wrap(obj, wrapper=None, methods_to_add=(), name=None, skip=(), wrap_return_values=False, clear_cache=True): """ Wrap module, class, function or another variable recursively :param Any obj: Object to wrap recursively :param Optional[Callable] wrapper: Wrapper to wrap functions and methods in (accepts function as arg...
try, wrap return values of callables (only types, supported by wrap function \ are supported) :param bool clear_cache: Clear wrapped objects cache after wrapping :return: Wrapped `obj` """ result = _wrap(obj=obj, wrapper=wrapper, methods_to_add=methods_to_add, name=name, skip=skip, wrap_return_values=wrap_return_values...
def docopt(doc, argv=None, help=True, version=None, options_first=False): """Parse `argv` based on command-line interface described in `doc`. `docopt` creates your command-line interface based on its description that you pass as `doc`. Such description can contain --options, <positional-argument>, commands, which could...
Returns ------- args : dict A dictionary, where keys are names of command-line elements such as e.g. "--verbose" and "<path>", and values are the parsed values of those elements. Example ------- >>> from docopt import docopt >>> doc = ''' Usage: my_program tcp <host> <port> [--timeout=<seconds>] my_program serial <port...
= printable_usage(doc) options = parse_defaults(doc) pattern = parse_pattern(formal_usage(DocoptExit.usage), options) # [default] syntax for argument is disabled #for a in pattern.flat(Argument): # same_name = [d for d in arguments if d.name == a.name] # if same_name: # a.value = same_name[0].value argv = parse_argv(To...
def is_scalar(self, typ: Type = _Any) -> bool: """Returns True iff this represents a scalar node. If a type is given, checks that the ScalarNode represents this \ type. Type may be `str`, `int`, `float`, `bool`, or `None`. If no type is given, any ScalarNode will return True. """ if isinstance(self.yaml_node, yaml.Scal...
def get_value(self) -> ScalarType: """Returns the value of a Scalar node. Use is_scalar(type) to check which type the node has. """ if self.yaml_node.tag == 'tag:yaml.org,2002:str': return self.yaml_node.value if self.yaml_node.tag == 'tag:yaml.org,2002:int': return int(self.yaml_node.value) if self.yaml_node.tag == 't...
def set_value(self, value: ScalarType) -> None: """Sets the value of the node to a scalar value. After this, is_scalar(type(value)) will return true. Args: value: The value to set this node to, a str, int, float, \ bool, or None. """ if isinstance(value, bool): value_str = 'true' if value else 'false' else: value_str =...
def make_mapping(self) -> None: """Replaces the node with a new, empty mapping. Note that this will work on the Node object that is passed to \ a yatiml_savorize() or yatiml_sweeten() function, but not on \ any of its attributes or items. If you need to set an attribute \ to a complex value, build a yaml.Node represent...
def has_attribute(self, attribute: str) -> bool: """Whether the node has an attribute with the given name. Use only if is_mapping() returns True. Args: attribute: The name of the attribute to check for. Returns: True iff the attribute is present. """ return any([ key_node.value == attribute for key_node, _ in self.yaml...
def has_attribute_type(self, attribute: str, typ: Type) -> bool: """Whether the given attribute exists and has a compatible type. Returns true iff the attribute exists and is an instance of \ the given type. Matching between types passed as typ and \ yaml node types is as follows: +---------+---------------------------...
matches the type. """ if not self.has_attribute(attribute): return False attr_node = self.get_attribute(attribute).yaml_node if typ in scalar_type_to_tag: tag = scalar_type_to_tag[typ] return attr_node.tag == tag elif typ == list: return isinstance(attr_node, yaml.SequenceNode) elif typ == dict: return isinstance(attr_...
def get_attribute(self, attribute: str) -> 'Node': """Returns the node representing the given attribute's value. Use only if is_mapping() returns true. Args: attribute: The name of the attribute to retrieve. Raises: KeyError: If the attribute does not exist. Returns: A node representing the value. """ matches = [ value...
def set_attribute(self, attribute: str, value: Union[ScalarType, yaml.Node]) -> None: """Sets the attribute to the given value. Use only if is_mapping() returns True. If the attribute does not exist, this adds a new attribute, \ if it does, it will be overwritten. If value is a str, int, float, bool or None, the attrib...
if value else 'false' value_node = yaml.ScalarNode('tag:yaml.org,2002:bool', value_str, start_mark, end_mark) elif isinstance(value, int): value_node = yaml.ScalarNode('tag:yaml.org,2002:int', str(value), start_mark, end_mark) elif isinstance(value, float): value_node = yaml.ScalarNode('tag:yaml.org,2002:float', str(va...
def remove_attribute(self, attribute: str) -> None: """Remove an attribute from the node. Use only if is_mapping() returns True. Args: attribute: The name of the attribute to remove. """ attr_index = self.__attr_index(attribute) if attr_index is not None: self.yaml_node.value.pop(attr_index)
def rename_attribute(self, attribute: str, new_name: str) -> None: """Renames an attribute. Use only if is_mapping() returns true. If the attribute does not exist, this will do nothing. Args: attribute: The (old) name of the attribute to rename. new_name: The new name to rename it to. """ for key_node, _ in self.yaml_n...
def unders_to_dashes_in_keys(self) -> None: """Replaces underscores with dashes in key names. For each attribute in a mapping, this replaces any underscores \ in its keys with dashes. Handy because Python does not \ accept dashes in identifiers, while some YAML-based formats use \ dashes in their keys. """ for key_node...
def dashes_to_unders_in_keys(self) -> None: """Replaces dashes with underscores in key names. For each attribute in a mapping, this replaces any dashes in \ its keys with underscores. Handy because Python does not \ accept dashes in identifiers, while some YAML-based file \ formats use dashes in their keys. """ for key...
def seq_attribute_to_map(self, attribute: str, key_attribute: str, value_attribute: Optional[str] = None, strict: Optional[bool] = True) -> None: """Converts a sequence attribute to a map. This function takes an attribute of this Node that is \ a sequence of mappings and turns it into a mapping of mappings. \ It assume...
description: Basic widget price: 100.0 item2: description: Premium quality widget price: 200.0 which is often more intuitive for people to read and write. If the attribute does not exist, or is not a sequence of \ mappings, this function will silently do nothing. If the keys \ are not unique and strict is False, it wil...
are \ not unique. Raises: SeasoningError: If the keys are not unique and strict is \ True. """ if not self.has_attribute(attribute): return attr_node = self.get_attribute(attribute) if not attr_node.is_sequence(): return start_mark = attr_node.yaml_node.start_mark end_mark = attr_node.yaml_node.end_mark # check that al...
key_node = item.get_attribute(key_attribute).yaml_node item.remove_attribute(key_attribute) if value_attribute is not None: value_node = item.get_attribute(value_attribute).yaml_node if len(item.yaml_node.value) == 1: # no other attributes, use short form mapping_values.append((key_node, value_node)) else: mapping_valu...
def map_attribute_to_seq(self, attribute: str, key_attribute: str, value_attribute: Optional[str] = None) -> None: """Converts a mapping attribute to a sequence. This function takes an attribute of this Node whose value \ is a mapping or a mapping of mappings and turns it into a \ sequence of mappings. Each entry in th...
\ mapping, the conversion is as before, otherwise a new \ submapping is created, and key and value are added using the \ given key and value attribute names. An example probably helps. If you have a Node representing \ this piece of YAML:: items: item1: description: Basic widget price: 100.0 item2: description: Premium...
will result in th equivalent of:: items: - item_id: item1 description: Basic widget - item_id: item2 description: Premium quality widget price: 200.0 If the attribute does not exist, or is not a mapping, this \ function will silently do nothing. With thanks to the makers of the Common Workflow Language for \ the idea. ...
Node(item_value) if not item_value_node.is_mapping(): if value_attribute is None: return ynode = item_value_node.yaml_node item_value_node.make_mapping() item_value_node.set_attribute(value_attribute, ynode) item_value_node.set_attribute(key_attribute, item_key.value) object_list.append(item_value_node.yaml_node) seq_n...
def __attr_index(self, attribute: str) -> Optional[int]: """Finds an attribute's index in the yaml_node.value list.""" attr_index = None for i, (key_node, _) in enumerate(self.yaml_node.value): if key_node.value == attribute: attr_index = i break return attr_index
def require_scalar(self, *args: Type) -> None: """Require the node to be a scalar. If additional arguments are passed, these are taken as a list \ of valid types; if the node matches one of these, then it is \ accepted. Example: # Match either an int or a string node.require_scalar(int, str) Arguments: args: One or mor...
def require_mapping(self) -> None: """Require the node to be a mapping.""" if not isinstance(self.yaml_node, yaml.MappingNode): raise RecognitionError(('{}{}A mapping is required here').format( self.yaml_node.start_mark, os.linesep))
def require_sequence(self) -> None: """Require the node to be a sequence.""" if not isinstance(self.yaml_node, yaml.SequenceNode): raise RecognitionError(('{}{}A sequence is required here').format( self.yaml_node.start_mark, os.linesep))
def require_attribute(self, attribute: str, typ: Type = _Any) -> None: """Require an attribute on the node to exist. If `typ` is given, the attribute must have this type. Args: attribute: The name of the attribute / mapping key. typ: The type the attribute must have. """ attr_nodes = [ value_node for key_node, value_no...
def require_attribute_value( self, attribute: str, value: Union[int, str, float, bool, None]) -> None: """Require an attribute on the node to have a particular value. This requires the attribute to exist, and to have the given value \ and corresponding type. Handy for in your yatiml_recognize() \ function. Args: attrib...
self.yaml_node.start_mark, os.linesep, value, type(value))) if node.get_value() != value: raise RecognitionError( ('{}{}Incorrect attribute value' ' {} where {} was required').format( self.yaml_node.start_mark, os.linesep, value_node.value, value)) if not found: raise RecognitionError( ('{}{}Required attribute {} not f...
def run(self, timeout = 0): """ Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. epoll timeout param is a integer number of miliseconds (seconds/1000). """ ptimeout = int(timeout.microseconds/1000+timeout.seconds*1000 if timeout else (self.m_resolution if timeo...
= act else: sleep(timeout)
def _callback_factory(callback_imp): """Factory for creating a is authenticated callback.""" if callback_imp is None: try: pkg_resources.get_distribution('flask-login') from flask_login import current_user return lambda: current_user.is_authenticated except pkg_resources.DistributionNotFound: return lambda: False elif ...
def init_app(self, app): """Flask application initialization.""" self.init_config(app) self.cache = Cache(app) self.is_authenticated_callback = _callback_factory( app.config['CACHE_IS_AUTHENTICATED_CALLBACK']) app.extensions['invenio-cache'] = self
def difference(arr, n=1, axis=0, **kwargs): ''' Assuming that `arr` is a 2D spectrogram returned by ibmseti.dsp.raw_to_spectrogram(data), this function uses the Numpy.diff function to calculate the nth difference along either time or frequency. If axis = 0 and n=1, then the first difference is taken between subsequent ...
def projection(arr, axis=0, **kwargs): ''' Assuming that `arr` is a 2D spectrogram returned by ibmseti.dsp.raw_to_spectrogram(data), where each row of the `arr` is a power spectrum at a particular time, this function uses the numpy.sum function to project the data onto the time or frequency axis into a 1D array. If axi...
array([ 3, 14, 21, 30]) One interesting kwarg that you may wish to use is `keepdims`. See the documentation on numpy.sum for more information. ''' return np.sum(arr, axis=axis, **kwargs)
def moment(arr, moment=1, axis=0, **kwargs): ''' Uses the scipy.stats.moment to calculate the Nth central moment about the mean. If `arr` is a 2D spectrogram returned by ibmseti.dsp.raw_to_spectrogram(data), where each row of the `arr` is a power spectrum at a particular time, this function, then the Nth moment along e...
1., 3., 6., 10.], //each row is a time sample [ 0., 5., 6., 8.], [ 2., 6., 9., 12.]]) ibmseti.features.mement(x, moment=2, axis=0) //the returned array is of size 4, the number of columns / frequency bins. >>> array([ 0.66666667, 1.55555556, 2., 2.66666667]) ibmseti.features.mement(x, moment=2, axis=1) //the returned a...
def first_order_gradient(arr, axis=0): ''' Returns the gradient of arr along a particular axis using the first order forward-difference. Additionally, the result is padded with 0 so that the returned array is the same shape as in input array. ''' grad_arr = difference(arr, n=1, axis=axis) return np.insert(grad_arr, gra...
def total_variation(arr): ''' If arr is a 2D array (N X M), assumes that arr is a spectrogram with time along axis=0. Calculates the 1D total variation in time for each frequency and returns an array of size M. If arr is a 1D array, calculates total variation and returns a scalar. Sum ( Abs(arr_i+1,j - arr_ij) ) If arr...
def maximum_variation(arr): ''' return np.max(arr, axis=0) - np.min(arr, axis=0) If `arr` is a 1D array, a scalar is returned. If `arr` is a 2D array (N x M), an array of length M is returned. ''' return np.max(arr, axis=0) - np.min(arr, axis=0)
def entropy(p, w): ''' Computes the entropy for a discrete probability distribution function, as represented by a histogram, `p`, with bin sizes `w`, h_p = Sum -1 * p_i * ln(p_i / w_i) Also computes the maximum allowed entropy for a histogram with bin sizes `w`. h_max = ln( Sum w_i ) and returns both as a tuple (h_p , ...
of disorder. (This is easily shown for the case where w_i = 1.) If the `p_i` is zero for all i except j and p_j = 1, then the entropy will be 0, indicating no disorder. One can use this entropy measurement to search for signals in the spectrogram. First we need to build a histogram of the measured power values in the s...
less than 1. The decision that needs to be made is the number of bins and the bin size. And unfortunately, the resulting entropy calculated will depend on the binning. Based on testing and interpretibility, we recommend to use a fixed number of bins that either span the full range of the power values in the spectrogram...