Search is not available for this dataset
text
stringlengths
75
104k
def input_size(self): '''Size of layer input (for layers with one input).''' shape = self.input_shape if shape is None: raise util.ConfigurationError( 'undefined input size for layer "{}"'.format(self.name)) return shape[-1]
def output_size(self): '''Number of "neurons" in this layer's default output.''' shape = self.output_shape if shape is None: raise util.ConfigurationError( 'undefined output size for layer "{}"'.format(self.name)) return shape[-1]
def connect(self, inputs): '''Create Theano variables representing the outputs of this layer. Parameters ---------- inputs : dict of Theano expressions Symbolic inputs to this layer, given as a dictionary mapping string names to Theano expressions. Each string ke...
def bind(self, graph, reset=True, initialize=True): '''Bind this layer into a computation graph. This method is a wrapper for performing common initialization tasks. It calls :func:`resolve`, :func:`setup`, and :func:`log`. Parameters ---------- graph : :class:`Network ...
def resolve_inputs(self, layers): '''Resolve the names of inputs for this layer into shape tuples. Parameters ---------- layers : list of :class:`Layer` A list of the layers that are available for resolving inputs. Raises ------ theanets.util.Configu...
def resolve_outputs(self): '''Resolve the names of outputs for this layer into shape tuples.''' input_shape = None for i, shape in enumerate(self._input_shapes.values()): if i == 0: input_shape = shape if len(input_shape) != len(shape) or any( ...
def log(self): '''Log some information about this layer.''' inputs = ', '.join('"{0}" {1}'.format(*ns) for ns in self._input_shapes.items()) util.log('layer {0.__class__.__name__} "{0.name}" {0.output_shape} {1} from {2}', self, getattr(self.activate, 'name', self.activate), inp...
def log_params(self): '''Log information about this layer's parameters.''' total = 0 for p in self.params: shape = p.get_value().shape util.log('parameter "{}" {}', p.name, shape) total += np.prod(shape) return total
def _fmt(self, string): '''Helper method to format our name into a string.''' if '{' not in string: string = '{}.' + string return string.format(self.name)
def _resolve_shape(self, name, layers): '''Given a list of layers, find the layer output with the given name. Parameters ---------- name : str Name of a layer to resolve. layers : list of :class:`theanets.layers.base.Layer` A list of layers to search in. ...
def find(self, key): '''Get a shared variable for a parameter by name. Parameters ---------- key : str or int The name of the parameter to look up, or the index of the parameter in our parameter list. These are both dependent on the implementation of ...
def add_weights(self, name, nin, nout, mean=0, std=0, sparsity=0, diagonal=0): '''Helper method to create a new weight matrix. Parameters ---------- name : str Name of the parameter to add. nin : int Size of "input" for this weight matrix. nout : ...
def add_bias(self, name, size, mean=0, std=1): '''Helper method to create a new bias vector. Parameters ---------- name : str Name of the parameter to add. size : int Size of the bias vector. mean : float, optional Mean value for rando...
def to_spec(self): '''Create a specification dictionary for this layer. Returns ------- spec : dict A dictionary specifying the configuration of this layer. ''' spec = dict(**self.kwargs) spec.update( form=self.__class__.__name__.lower(), ...
def argmax(self, C): """ Returns the ArgMax from C by returning the (x_pos, y_pos, theta, scale) tuple >>> C = np.random.randn(10, 10, 5, 4) >>> x_pos, y_pos, theta, scale = mp.argmax(C) >>> C[x_pos][y_pos][theta][scale] = C.max() """ ind = np.absolute(...
def golden_pyramid(self, z, mask=False, spiral=True, fig_width=13): """ The Golden Laplacian Pyramid. To represent the edges of the image at different levels, we may use a simple recursive approach constructing progressively a set of images of decreasing sizes, from a base to the summit of a pyr...
def band(self, sf_0, B_sf, force=False): """ Returns the radial frequency envelope: Selects a preferred spatial frequency ``sf_0`` and a bandwidth ``B_sf``. """ if sf_0 == 0.: return 1. elif self.pe.use_cache and not force: tag = str(sf_0) + '_' ...
def orientation(self, theta, B_theta, force=False): """ Returns the orientation envelope: We use a von-Mises distribution on the orientation: - mean orientation is ``theta`` (in radians), - ``B_theta`` is the bandwidth (in radians). It is equal to the standard deviation of the Ga...
def loggabor(self, x_pos, y_pos, sf_0, B_sf, theta, B_theta, preprocess=True): """ Returns the envelope of a LogGabor Note that the convention for coordinates follows that of matrices: the origin is at the top left of the image, and coordinates are first the rows (vertical axis,...
def loggabor_image(self, x_pos, y_pos, theta, sf_0, phase, B_sf, B_theta): """ Returns the image of a LogGabor Note that the convention for coordinates follows that of matrices: the origin is at the top left of the image, and coordinates are first the rows (vertical axis, going ...
def from_file(self, ifile, codec='ascii'): """Read textgrid from stream. :param file ifile: Stream to read from. :param str codec: Text encoding for the input. Note that this will be ignored for binary TextGrids. """ if ifile.read(12) == b'ooBinaryFile': ...
def sort_tiers(self, key=lambda x: x.name): """Sort the tiers given the key. Example key functions: Sort according to the tiername in a list: ``lambda x: ['name1', 'name2' ... 'namen'].index(x.name)``. Sort according to the number of annotations: ``lambda x: len(list(x.get_in...
def add_tier(self, name, tier_type='IntervalTier', number=None): """Add an IntervalTier or a TextTier on the specified location. :param str name: Name of the tier, duplicate names is allowed. :param str tier_type: Type of the tier. :param int number: Place to insert the tier, when ``Non...
def remove_tier(self, name_num): """Remove a tier, when multiple tiers exist with that name only the first is removed. :param name_num: Name or number of the tier to remove. :type name_num: int or str :raises IndexError: If there is no tier with that number. """ ...
def get_tier(self, name_num): """Gives a tier, when multiple tiers exist with that name only the first is returned. :param name_num: Name or number of the tier to return. :type name_num: int or str :returns: The tier. :raises IndexError: If the tier doesn't exist. ...
def to_file(self, filepath, codec='utf-8', mode='normal'): """Write the object to a file. :param str filepath: Path of the fil. :param str codec: Text encoding. :param string mode: Flag to for write mode, possible modes: 'n'/'normal', 's'/'short' and 'b'/'binary' """...
def to_eaf(self, skipempty=True, pointlength=0.1): """Convert the object to an pympi.Elan.Eaf object :param int pointlength: Length of respective interval from points in seconds :param bool skipempty: Skip the empty annotations :returns: :class:`pympi.Ela...
def add_point(self, point, value, check=True): """Add a point to the TextTier :param int point: Time of the point. :param str value: Text of the point. :param bool check: Flag to check for overlap. :raises Exception: If overlap or wrong tiertype. """ if self.tier...
def add_interval(self, begin, end, value, check=True): """Add an interval to the IntervalTier. :param float begin: Start time of the interval. :param float end: End time of the interval. :param str value: Text of the interval. :param bool check: Flag to check for overlap. ...
def remove_interval(self, time): """Remove an interval, if no interval is found nothing happens. :param int time: Time of the interval. :raises TierTypeException: If the tier is not a IntervalTier. """ if self.tier_type != 'IntervalTier': raise Exception('Tiertype mu...
def remove_point(self, time): """Remove a point, if no point is found nothing happens. :param int time: Time of the point. :raises TierTypeException: If the tier is not a TextTier. """ if self.tier_type != 'TextTier': raise Exception('Tiertype must be TextTier.') ...
def get_intervals(self, sort=False): """Give all the intervals or points. :param bool sort: Flag for yielding the intervals or points sorted. :yields: All the intervals """ for i in sorted(self.intervals) if sort else self.intervals: yield i
def get_all_intervals(self): """Returns the true list of intervals including the empty intervals.""" ints = sorted(self.get_intervals(True)) if self.tier_type == 'IntervalTier': if not ints: ints.append((self.xmin, self.xmax, '')) else: if ...
def eaf_from_chat(file_path, codec='ascii', extension='wav'): """Reads a .cha file and converts it to an elan object. The functions tries to mimic the CHAT2ELAN program that comes with the CLAN package as close as possible. This function however converts to the latest ELAN file format since the library ...
def parse_eaf(file_path, eaf_obj): """Parse an EAF file :param str file_path: Path to read from, - for stdin. :param pympi.Elan.Eaf eaf_obj: Existing EAF object to put the data in. :returns: EAF object. """ if file_path == '-': file_path = sys.stdin # Annotation document try: ...
def indent(el, level=0): """Function to pretty print the xml, meaning adding tabs and newlines. :param ElementTree.Element el: Current element. :param int level: Current level. """ i = '\n' + level * '\t' if len(el): if not el.text or not el.text.strip(): el.text = i+'\t' ...
def to_eaf(file_path, eaf_obj, pretty=True): """Write an Eaf object to file. :param str file_path: Filepath to write to, - for stdout. :param pympi.Elan.Eaf eaf_obj: Object to write. :param bool pretty: Flag to set pretty printing. """ def rm_none(x): try: # Ugly hack to test if s is a...
def add_annotation(self, id_tier, start, end, value='', svg_ref=None): """Add an annotation. :param str id_tier: Name of the tier. :param int start: Start time of the annotation. :param int end: End time of the annotation. :param str value: Value of the annotation. :para...
def add_cv_entry(self, cv_id, cve_id, values, ext_ref=None): """Add an entry to a controlled vocabulary. :param str cv_id: Name of the controlled vocabulary to add an entry. :param str cve_id: Name of the entry. :param list values: List of values of the form: ``(value, lang_...
def add_cv_description(self, cv_id, lang_ref, description=None): """Add a description to a controlled vocabulary. :param str cv_id: Name of the controlled vocabulary to add the description. :param str lang_ref: Language reference. :param str description: Description, this ca...
def add_external_ref(self, eid, etype, value): """Add an external reference. :param str eid: Name of the external reference. :param str etype: Type of the external reference, has to be in ``['iso12620', 'ecv', 'cve_id', 'lexen_id', 'resource_url']``. :param str value: Value ...
def add_language(self, lang_id, lang_def=None, lang_label=None): """Add a language. :param str lang_id: ID of the language. :param str lang_def: Definition of the language(preferably ISO-639-3). :param str lang_label: Label of the language. """ self.languages[lang_id] = ...
def add_lexicon_ref(self, lrid, name, lrtype, url, lexicon_id, lexicon_name, datcat_id=None, datcat_name=None): """Add lexicon reference. :param str lrid: Lexicon reference internal ID. :param str name: Lexicon reference display name. :param str lrtype: Lexicon r...
def add_linguistic_type(self, lingtype, constraints=None, timealignable=True, graphicreferences=False, extref=None, param_dict=None): """Add a linguistic type. :param str lingtype: Name of the linguistic type. :param str constraints: Const...
def add_linked_file(self, file_path, relpath=None, mimetype=None, time_origin=None, ex_from=None): """Add a linked file. :param str file_path: Path of the file. :param str relpath: Relative path of the file. :param str mimetype: Mimetype of the file, if ``None`` ...
def add_locale(self, language_code, country_code=None, variant=None): """Add a locale. :param str language_code: The language code of the locale. :param str country_code: The country code of the locale. :param str variant: The variant of the locale. """ self.locales[lang...
def add_ref_annotation(self, id_tier, tier2, time, value='', prev=None, svg=None): """Add a reference annotation. .. note:: When a timepoint matches two annotations the new reference annotation will reference to the first annotation. To circumvent this it's alw...
def add_secondary_linked_file(self, file_path, relpath=None, mimetype=None, time_origin=None, assoc_with=None): """Add a secondary linked file. :param str file_path: Path of the file. :param str relpath: Relative path of the file. :param str mimetype: M...
def add_tier(self, tier_id, ling='default-lt', parent=None, locale=None, part=None, ann=None, language=None, tier_dict=None): """Add a tier. When no linguistic type is given and the default linguistic type is unavailable then the assigned linguistic type will be the first in the...
def clean_time_slots(self): """Clean up all unused timeslots. .. warning:: This can and will take time for larger tiers. When you want to do a lot of operations on a lot of tiers please unset the flags for cleaning in the functions so that the cleaning is only performed afterwa...
def copy_tier(self, eaf_obj, tier_name): """Copies a tier to another :class:`pympi.Elan.Eaf` object. :param pympi.Elan.Eaf eaf_obj: Target Eaf object. :param str tier_name: Name of the tier. :raises KeyError: If the tier doesn't exist. """ if tier_name in eaf_obj.get_tie...
def create_gaps_and_overlaps_tier(self, tier1, tier2, tier_name=None, maxlen=-1, fast=False): """Create a tier with the gaps and overlaps of the annotations. For types see :func:`get_gaps_and_overlaps` :param str tier1: Name of the first tier. :para...
def extract(self, start, end): """Extracts the selected time frame as a new object. :param int start: Start time. :param int end: End time. :returns: class:`pympi.Elan.Eaf` object containing the extracted frame. """ from copy import deepcopy eaf_out = deepcopy(se...
def filter_annotations(self, tier, tier_name=None, filtin=None, filtex=None, regex=False, safe=False): """Filter annotations in a tier using an exclusive and/or inclusive filter. :param str tier: Name of the tier. :param str tier_name: Name of the output tier,...
def generate_annotation_id(self): """Generate the next annotation id, this function is mainly used internally. """ if not self.maxaid: valid_anns = [int(''.join(filter(str.isdigit, a))) for a in self.timeslots] self.maxaid = max(valid_ann...
def generate_ts_id(self, time=None): """Generate the next timeslot id, this function is mainly used internally :param int time: Initial time to assign to the timeslot. :raises ValueError: If the time is negative. """ if time and time < 0: raise ValueError('Ti...
def get_annotation_data_at_time(self, id_tier, time): """Give the annotations at the given time. When the tier contains reference annotations this will be returned, check :func:`get_ref_annotation_data_at_time` for the format. :param str id_tier: Name of the tier. :param int tim...
def get_annotation_data_after_time(self, id_tier, time): """Give the annotation before a given time. When the tier contains reference annotations this will be returned, check :func:`get_ref_annotation_data_before_time` for the format. If an annotation overlaps with ``time`` that annotati...
def get_annotation_data_before_time(self, id_tier, time): """Give the annotation before a given time. When the tier contains reference annotations this will be returned, check :func:`get_ref_annotation_data_before_time` for the format. If an annotation overlaps with ``time`` that annotat...
def get_annotation_data_between_times(self, id_tier, start, end): """Gives the annotations within the times. When the tier contains reference annotations this will be returned, check :func:`get_ref_annotation_data_between_times` for the format. :param str id_tier: Name of the tier. ...
def get_annotation_data_for_tier(self, id_tier): """Gives a list of annotations of the form: ``(begin, end, value)`` When the tier contains reference annotations this will be returned, check :func:`get_ref_annotation_data_for_tier` for the format. :param str id_tier: Name of the tier. ...
def get_child_tiers_for(self, id_tier): """Give all child tiers for a tier. :param str id_tier: Name of the tier. :returns: List of all children :raises KeyError: If the tier is non existent. """ self.tiers[id_tier] return [m for m in self.tiers if 'PARENT_REF' i...
def get_full_time_interval(self): """Give the full time interval of the file. Note that the real interval can be longer because the sound file attached can be longer. :returns: Tuple of the form: ``(min_time, max_time)``. """ return (0, 0) if not self.timeslots else\ ...
def get_gaps_and_overlaps(self, tier1, tier2, maxlen=-1): """Give gaps and overlaps. The return types are shown in the table below. The string will be of the format: ``id_tiername_tiername``. .. note:: There is also a faster method: :func:`get_gaps_and_overlaps2` For example when a gap...
def get_gaps_and_overlaps2(self, tier1, tier2, maxlen=-1): """Faster variant of :func:`get_gaps_and_overlaps`. Faster in this case means almost 100 times faster... :param str tier1: Name of the first tier. :param str tier2: Name of the second tier. :param int maxlen: Maximum len...
def get_ref_annotation_at_time(self, tier, time): """Give the ref annotations at the given time of the form ``[(start, end, value, refvalue)]`` :param str tier: Name of the tier. :param int time: Time of the annotation of the parent. :returns: List of annotations at that time. ...
def get_ref_annotation_data_after_time(self, id_tier, time): """Give the ref annotation after a time. If an annotation overlaps with `ktime`` that annotation will be returned. :param str id_tier: Name of the tier. :param int time: Time to get the annotation after. :returns: Anno...
def get_ref_annotation_data_before_time(self, id_tier, time): """Give the ref annotation before a time. If an annotation overlaps with ``time`` that annotation will be returned. :param str id_tier: Name of the tier. :param int time: Time to get the annotation before. :returns: A...
def get_ref_annotation_data_between_times(self, id_tier, start, end): """Give the ref annotations between times of the form ``[(start, end, value, refvalue)]`` :param str tier: Name of the tier. :param int start: End time of the annotation of the parent. :param int end: Start ti...
def get_ref_annotation_data_for_tier(self, id_tier): """"Give a list of all reference annotations of the form: ``[(start, end, value, refvalue)]`` :param str id_tier: Name of the tier. :raises KeyError: If the tier is non existent. :returns: Reference annotations within that tie...
def get_parent_aligned_annotation(self, ref_id): """" Give the aligment annotation that a reference annotation belongs to directly, or indirectly through other reference annotations. :param str ref_id: Id of a reference annotation. :raises KeyError: If no annotation exists with the id or...
def get_tier_ids_for_linguistic_type(self, ling_type, parent=None): """Give a list of all tiers matching a linguistic type. :param str ling_type: Name of the linguistic type. :param str parent: Only match tiers from this parent, when ``None`` this option will be ignor...
def insert_annotation(self, id_tier, start, end, value='', svg_ref=None): """.. deprecated:: 1.2 Use :func:`add_annotation` instead. """ return self.add_annotation(id_tier, start, end, value, svg_ref)
def insert_ref_annotation(self, id_tier, tier2, time, value='', prev=None, svg=None): """.. deprecated:: 1.2 Use :func:`add_ref_annotation` instead. """ return self.add_ref_annotation(id_tier, tier2, time, value, prev, svg)
def merge_tiers(self, tiers, tiernew=None, gapt=0, sep='_', safe=False): """Merge tiers into a new tier and when the gap is lower then the threshhold glue the annotations together. :param list tiers: List of tier names. :param str tiernew: Name for the new tier, if ``None`` the name wil...
def remove_all_annotations_from_tier(self, id_tier, clean=True): """remove all annotations from a tier :param str id_tier: Name of the tier. :raises KeyError: If the tier is non existent. """ for aid in self.tiers[id_tier][0]: del(self.annotations[aid]) for a...
def remove_annotation(self, id_tier, time, clean=True): """Remove an annotation in a tier, if you need speed the best thing is to clean the timeslots after the last removal. When the tier contains reference annotations :func:`remove_ref_annotation` will be executed instead. :par...
def remove_cv_description(self, cv_id, lang_ref): """Remove a controlled vocabulary description. :param str cv_id: Name of the controlled vocabulary. :paarm str cve_id: Name of the entry. :throws KeyError: If there is no controlled vocabulary with that name. """ for i, (...
def remove_license(self, name=None, url=None): """Remove all licenses matching both key and value. :param str name: Name of the license. :param str url: URL of the license. """ for k, v in self.licenses[:]: if (name is None or name == k) and (url is None or url == v)...
def remove_linked_files(self, file_path=None, relpath=None, mimetype=None, time_origin=None, ex_from=None): """Remove all linked files that match all the criteria, criterias that are ``None`` are ignored. :param str file_path: Path of the file. :param str rel...
def remove_property(self, key=None, value=None): """Remove all properties matching both key and value. :param str key: Key of the property. :param str value: Value of the property. """ for k, v in self.properties[:]: if (key is None or key == k) and (value is None or...
def remove_ref_annotation(self, id_tier, time): """Remove a reference annotation. :param str id_tier: Name of tier. :param int time: Time of the referenced annotation :raises KeyError: If the tier is non existent. :returns: Number of removed annotations. """ remo...
def remove_secondary_linked_files(self, file_path=None, relpath=None, mimetype=None, time_origin=None, assoc_with=None): """Remove all secondary linked files that match all the criteria, criterias that are ``None`` are ignored. ...
def remove_tier(self, id_tier, clean=True): """Remove a tier. :param str id_tier: Name of the tier. :param bool clean: Flag to also clean the timeslots. :raises KeyError: If tier is non existent. """ del(self.tiers[id_tier]) if clean: self.clean_time_...
def remove_tiers(self, tiers): """Remove multiple tiers, note that this is a lot faster then removing them individually because of the delayed cleaning of timeslots. :param list tiers: Names of the tier to remove. :raises KeyError: If a tier is non existent. """ for a in...
def rename_tier(self, id_from, id_to): """Rename a tier. Note that this renames also the child tiers that have the tier as a parent. :param str id_from: Original name of the tier. :param str id_to: Target name of the tier. :throws KeyError: If the tier doesnt' exist. """...
def shift_annotations(self, time): """Shift all annotations in time. Annotations that are in the beginning and a left shift is applied can be squashed or discarded. :param int time: Time shift width, negative numbers make a left shift. :returns: Tuple of a list of squashed annotations a...
def to_textgrid(self, filtin=[], filtex=[], regex=False): """Convert the object to a :class:`pympi.Praat.TextGrid` object. :param list filtin: Include only tiers in this list, if empty all tiers are included. :param list filtex: Exclude all tiers in this list. :param bool re...
def main(): """Will be used to create the console script""" import optparse import sys import codecs import locale import six from .algorithm import get_display parser = optparse.OptionParser() parser.add_option('-e', '--encoding', dest='encoding', ...
def debug_storage(storage, base_info=False, chars=True, runs=False): "Display debug information for the storage" import codecs import locale import sys if six.PY2: stderr = codecs.getwriter(locale.getpreferredencoding())(sys.stderr) else: stderr = sys.stderr caller = inspe...
def get_base_level(text, upper_is_rtl=False): """Get the paragraph base embedding level. Returns 0 for LTR, 1 for RTL. `text` a unicode object. Set `upper_is_rtl` to True to treat upper case chars as strong 'R' for debugging (default: False). """ base_level = None prev_surrogate = F...
def get_embedding_levels(text, storage, upper_is_rtl=False, debug=False): """Get the paragraph base embedding level and direction, set the storage to the array of chars""" prev_surrogate = False base_level = storage['base_level'] # preset the storage's chars for _ch in text: if _IS_UCS...
def explicit_embed_and_overrides(storage, debug=False): """Apply X1 to X9 rules of the unicode algorithm. See http://unicode.org/reports/tr9/#Explicit_Levels_and_Directions """ overflow_counter = almost_overflow_counter = 0 directional_override = 'N' levels = deque() # X1 embedding_le...
def calc_level_runs(storage): """Split the storage to run of char types at the same level. Applies X10. See http://unicode.org/reports/tr9/#X10 """ # run level depends on the higher of the two levels on either side of # the boundary If the higher level is odd, the type is R; otherwise, # it is ...
def resolve_weak_types(storage, debug=False): """Reslove weak type rules W1 - W3. See: http://unicode.org/reports/tr9/#Resolving_Weak_Types """ for run in storage['runs']: prev_strong = prev_type = run['sor'] start, length = run['start'], run['length'] chars = storage['chars']...
def resolve_neutral_types(storage, debug): """Resolving neutral types. Implements N1 and N2 See: http://unicode.org/reports/tr9/#Resolving_Neutral_Types """ for run in storage['runs']: start, length = run['start'], run['length'] # use sor and eor chars = [{'type': run['sor']}]...
def resolve_implicit_levels(storage, debug): """Resolving implicit levels (I1, I2) See: http://unicode.org/reports/tr9/#Resolving_Implicit_Levels """ for run in storage['runs']: start, length = run['start'], run['length'] chars = storage['chars'][start:start+length] for _ch in...
def reverse_contiguous_sequence(chars, line_start, line_end, highest_level, lowest_odd_level): """L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence...
def reorder_resolved_levels(storage, debug): """L1 and L2 rules""" # Applies L1. should_reset = True chars = storage['chars'] for _ch in chars[::-1]: # L1. On each line, reset the embedding level of the following # characters to the paragraph embedding level: if _ch['orig'...
def apply_mirroring(storage, debug): """Applies L4: mirroring See: http://unicode.org/reports/tr9/#L4 """ # L4. A character is depicted by a mirrored glyph if and only if (a) the # resolved directionality of that character is R, and (b) the # Bidi_Mirrored property value of that character is t...