docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Save this corpus at the given path. If the path differs from the current path set, the path gets updated. Parameters: path (str): Path to save the data set to. writer (str, CorpusWriter): The writer or the name of the reader to use.
def save_at(self, path, writer=None): if writer is None: from . import io writer = io.DefaultWriter() elif type(writer) == str: # If a loader is given as string, try to create such a loader. from . import io writer = io.create_writer_...
564,431
Loads the corpus from the given path, using the given reader. If no reader is given the :py:class:`audiomate.corpus.io.DefaultReader` is used. Args: path (str): Path to load the corpus from. reader (str, CorpusReader): The reader or the name of the reader to use. Return...
def load(cls, path, reader=None): if reader is None: from . import io reader = io.DefaultReader() elif type(reader) == str: from . import io reader = io.create_reader_of_type(reader) return reader.load(path)
564,432
Adds a new audio file to the corpus with the given data. Parameters: path (str): Path of the file to add. track_idx (str): The id to associate the file-track with. copy_file (bool): If True the file is copied to the data set folder, otherwise the given ...
def new_file(self, path, track_idx, copy_file=False): new_file_idx = track_idx new_file_path = os.path.abspath(path) # Add index to idx if already existing if new_file_idx in self._tracks.keys(): new_file_idx = naming.index_name_if_in_list(new_file_idx, self._track...
564,433
Add the given tracks/track to the corpus. If any of the given track-ids already exists, a suffix is appended so it is unique. Args: import_tracks (list): Either a list of or a single :py:class:`audiomate.tracks.Track`. Returns: dict: A dictionary containing track-idx ma...
def import_tracks(self, import_tracks): if isinstance(import_tracks, tracks.Track): import_tracks = [import_tracks] idx_mapping = {} for track in import_tracks: idx_mapping[track.idx] = track # Add index to idx if already existing if t...
564,434
Add a new issuer to the dataset with the given data. Parameters: issuer_idx (str): The id to associate the issuer with. If None or already exists, one is generated. info (dict, list): Additional info of the issuer. Returns: Issuer: The ...
def new_issuer(self, issuer_idx, info=None): new_issuer_idx = issuer_idx # Add index to idx if already existing if new_issuer_idx in self._issuers.keys(): new_issuer_idx = naming.index_name_if_in_list(new_issuer_idx, self._issuers.keys()) new_issuer = issuers.Issu...
564,437
Add the given issuers/issuer to the corpus. If any of the given issuer-ids already exists, a suffix is appended so it is unique. Args: issuers (list): Either a list of or a single :py:class:`audiomate.issuers.Issuer`. Returns: dict: A dictionary containing idx mappings ...
def import_issuers(self, new_issuers): if isinstance(new_issuers, issuers.Issuer): new_issuers = [new_issuers] idx_mapping = {} for issuer in new_issuers: idx_mapping[issuer.idx] = issuer # Add index to idx if already existing if issue...
564,438
Add a new feature container with the given data. Parameters: idx (str): An unique identifier within the dataset. path (str): The path to store the feature file. If None a default path is used. Returns: FeatureContainer: The newly added feature-container.
def new_feature_container(self, idx, path=None): new_feature_idx = idx new_feature_path = path # Add index to idx if already existing if new_feature_idx in self._feature_containers.keys(): new_feature_idx = naming.index_name_if_in_list(new_feature_idx, ...
564,439
Add the given subview to the corpus. Args: idx (str): An idx that is unique in the corpus for identifying the subview. If already a subview exists with the given id it will be overridden. subview (Subview): The subview to add.
def import_subview(self, idx, subview): subview.corpus = self self._subviews[idx] = subview
564,440
Merge the given corpus into this corpus. All assets (tracks, utterances, issuers, ...) are copied into this corpus. If any ids (utt-idx, track-idx, issuer-idx, subview-idx, ...) are occurring in both corpora, the ids from the merging corpus are suffixed by a number (starting from 1 until no other is mat...
def merge_corpus(self, corpus): # Create a copy, so objects aren't changed in the original merging corpus merging_corpus = Corpus.from_corpus(corpus) self.import_tracks(corpus.tracks.values()) self.import_issuers(corpus.issuers.values()) utterance_idx_mapping = self.im...
564,441
Create a new modifiable corpus from any other CorpusView. This for example can be used to create a independent modifiable corpus from a subview. Args: corpus (CorpusView): The corpus to create a copy from. Returns: Corpus: A new corpus with the same data as the given on...
def from_corpus(cls, corpus): ds = Corpus() # Tracks tracks = copy.deepcopy(list(corpus.tracks.values())) track_mapping = ds.import_tracks(tracks) # Issuers issuers = copy.deepcopy(list(corpus.issuers.values())) issuer_mapping = ds.import_issuers(issue...
564,444
Merge a list of corpora into one. Args: corpora (Iterable): An iterable of :py:class:`audiomate.corpus.CorpusView`. Returns: Corpus: A corpus with the data from all given corpora merged into one.
def merge_corpora(cls, corpora): ds = Corpus() for merging_corpus in corpora: ds.merge_corpus(merging_corpus) return ds
564,445
Parses an expression that represents an amount of storage/memory and returns the number of bytes it represents. Args: storage_size(str): Size in bytes. The units ``k`` (kibibytes), ``m`` (mebibytes) and ``g`` (gibibytes) are supported, i.e. a ``partition_size`` of ``1g`` equates ...
def parse_storage_size(storage_size): pattern = re.compile(r'^([0-9]+(\.[0-9]+)?)([gmk])?$', re.I) units = { 'k': 1024, 'm': 1024 * 1024, 'g': 1024 * 1024 * 1024 } match = pattern.fullmatch(str(storage_size)) if match is None: raise ValueError('Invalid partiti...
564,455
Calculate the frames containing samples from the given time range in seconds. Args: start (float): Start time in seconds. end (float): End time in seconds. sr (int): The sampling rate to use for time-to-sample conversion. Returns: tuple: A tuple containi...
def time_range_to_frame_range(self, start, end, sr): start_sample = seconds_to_sample(start, sr) end_sample = seconds_to_sample(end, sr) return self.sample_to_frame_range(start_sample)[0], self.sample_to_frame_range(end_sample - 1)[1]
564,461
Merge the read blocks and resample if necessary. Args: buffer (list): A list of blocks of samples. n_channels (int): The number of channels of the input data. Returns: np.array: The samples
def process_buffer(buffer, n_channels): samples = np.concatenate(buffer) if n_channels > 1: samples = samples.reshape((-1, n_channels)).T samples = librosa.to_mono(samples) return samples
564,475
Write to given samples to a wav file. The samples are expected to be floating point numbers in the range of -1.0 to 1.0. Args: path (str): The path to write the wav to. samples (np.array): A float array . sr (int): The sampling rate.
def write_wav(path, samples, sr=16000): max_value = np.abs(np.iinfo(np.int16).min) data = (samples * max_value).astype(np.int16) scipy.io.wavfile.write(path, sr, data)
564,478
Take a list of stats from different sets of data points and merge the stats for getting stats overall data points. Args: list_of_stats (iterable): A list containing stats for different sets of data points. Returns: DataStats: Stats calculated overall sets of data points...
def concatenate(cls, list_of_stats): all_stats = np.stack([stats.values for stats in list_of_stats]) all_counts = all_stats[:, 4] all_counts_relative = all_counts / np.sum(all_counts) min_value = float(np.min(all_stats[:, 2])) max_value = float(np.max(all_stats[:, 3]))...
564,482
Writes the given `label_list` to an audacity label file. Args: path (str): Path to write the file to. label_list (audiomate.annotations.LabelList): Label list
def write_label_list(path, label_list): entries = [] for label in label_list: entries.append([label.start, label.end, label.value]) textfile.write_separated_lines(path, entries, separator='\t')
564,498
Read the labels from an audacity label file. Args: path (str): Path to the label file. Returns: list: List of labels (start [sec], end [sec], label) Example:: >>> read_label_file('/path/to/label/file.txt') [ [0.0, 0.2, 'sie'], [0.2, 2.2, 'hallo'] ...
def read_label_file(path): labels = [] for record in textfile.read_separated_lines_generator(path, separator='\t', max_columns=3): value = '' if len(record) > 2: value = str(record[2]) labels.append([float(_clean_time(record[0])), float(_clean_time(record[1])), value]...
564,499
Reads labels from an Audacity label file and returns them wrapped in a :py:class:`audiomate.annotations.LabelList`. Args: path (str): Path to the Audacity label file Returns: audiomate.annotations.LabelList: Label list containing the labels
def read_label_list(path): ll = annotations.LabelList() for record in read_label_file(path): ll.add(annotations.Label(record[2], start=record[0], end=record[1])) return ll
564,500
Move all files/folder from all subfolders of `folder_path` on top into `folder_path`. Args: folder_path (str): Path of the folder. delete_subfolders (bool): If True the subfolders are deleted after all items are moved out of it. copy (bool): If True copies the files instead of moving. (defa...
def move_all_files_from_subfolders_to_top(folder_path, delete_subfolders=False, copy=False): for item in os.listdir(folder_path): sub_path = os.path.join(folder_path, item) if os.path.isdir(sub_path): for sub_item in os.listdir(sub_path): src = os.path.join(sub_pat...
564,504
Reads a text file where each line represents a record with some separated columns. Parameters: path (str): Path to the file to read. separator (str): Separator that is used to split the columns. max_columns (int): Number of max columns (if the separator occurs within the last column). ...
def read_separated_lines(path, separator=' ', max_columns=-1, keep_empty=False): gen = read_separated_lines_generator(path, separator, max_columns, keep_empty=keep_empty) return list(gen)
564,514
Reads lines of a text file with two columns as key/value dictionary. Parameters: path (str): Path to the file. separator (str): Separator that is used to split key and value. default_value (str): If no value is given this value is used. Returns: dict: A dictionary with first co...
def read_key_value_lines(path, separator=' ', default_value=''): gen = read_separated_lines_generator(path, separator, 2) dic = {} for record in gen: if len(record) > 1: dic[record[0]] = record[1] elif len(record) > 0: dic[record[0]] = default_value return...
564,516
Creates a generator through all lines of a file and returns the splitted line. Parameters: path: Path to the file. separator: Separator that is used to split the columns. max_columns: Number of max columns (if the separator occurs within the last column). ignore_lines_starting_with:...
def read_separated_lines_generator(path, separator=' ', max_columns=-1, ignore_lines_starting_with=[], keep_empty=False): if not os.path.isfile(path): print('File doesnt exist or is no file: {}'.format(path)) return f = open(path, 'r', errors='ignore', en...
564,518
Create a TreeSwift tree from a DendroPy tree Args: ``tree`` (``dendropy.datamodel.treemodel``): A Dendropy ``Tree`` object Returns: ``Tree``: A TreeSwift tree created from ``tree``
def read_tree_dendropy(tree): out = Tree(); d2t = dict() if not hasattr(tree, 'preorder_node_iter') or not hasattr(tree, 'seed_node') or not hasattr(tree, 'is_rooted'): raise TypeError("tree must be a DendroPy Tree object") if tree.is_rooted != True: out.is_rooted = False for node i...
564,898
Read a tree from a Newick string or file Args: ``newick`` (``str``): Either a Newick string or the path to a Newick file (plain-text or gzipped) Returns: ``Tree``: The tree represented by ``newick``. If the Newick file has multiple trees (one per line), a ``list`` of ``Tree`` objects will be r...
def read_tree_newick(newick): if not isinstance(newick, str): try: newick = str(newick) except: raise TypeError("newick must be a str") if newick.lower().endswith('.gz'): # gzipped file f = gopen(expanduser(newick)); ts = f.read().decode().strip(); f.close() ...
564,899
Read a tree from a NeXML string or file Args: ``nexml`` (``str``): Either a NeXML string or the path to a NeXML file (plain-text or gzipped) Returns: ``dict`` of ``Tree``: A dictionary of the trees represented by ``nexml``, where keys are tree names (``str``) and values are ``Tree`` objects
def read_tree_nexml(nexml): if not isinstance(nexml, str): raise TypeError("nexml must be a str") if nexml.lower().endswith('.gz'): # gzipped file f = gopen(expanduser(nexml)) elif isfile(expanduser(nexml)): # plain-text file f = open(expanduser(nexml)) else: f = nex...
564,900
Read a tree from a Nexus string or file Args: ``nexus`` (``str``): Either a Nexus string or the path to a Nexus file (plain-text or gzipped) Returns: ``dict`` of ``Tree``: A dictionary of the trees represented by ``nexus``, where keys are tree names (``str``) and values are ``Tree`` objects
def read_tree_nexus(nexus): if not isinstance(nexus, str): raise TypeError("nexus must be a str") if nexus.lower().endswith('.gz'): # gzipped file f = gopen(expanduser(nexus)) elif isfile(expanduser(nexus)): # plain-text file f = open(expanduser(nexus)) else: f = nex...
564,901
Compute the average length of the selected branches of this ``Tree``. Edges with length ``None`` will be treated as 0-length Args: ``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal branches, otherwi...
def avg_branch_length(self, terminal=True, internal=True): if not isinstance(terminal, bool): raise TypeError("terminal must be a bool") if not isinstance(internal, bool): raise TypeError("internal must be a bool") if not internal and not terminal: ra...
564,904
Generator over the lengths of the selected branches of this ``Tree``. Edges with length ``None`` will be output as 0-length Args: ``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal branches, otherwis...
def branch_lengths(self, terminal=True, internal=True): if not isinstance(terminal, bool): raise TypeError("terminal must be a bool") if not isinstance(internal, bool): raise TypeError("internal must be a bool") for node in self.traverse_preorder(): i...
564,905
Generator over the times of successive coalescence events Args: ``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False``
def coalescence_times(self, backward=True): if not isinstance(backward, bool): raise TypeError("backward must be a bool") for dist in sorted((d for n,d in self.distances_from_root() if len(n.children) > 1), reverse=backward): yield dist
564,907
Generator over the waiting times of successive coalescence events Args: ``backward`` (``bool``): ``True`` to go backward in time (i.e., leaves to root), otherwise ``False``
def coalescence_waiting_times(self, backward=True): if not isinstance(backward, bool): raise TypeError("backward must be a bool") times = list(); lowest_leaf_dist = float('-inf') for n,d in self.distances_from_root(): if len(n.children) > 1: times...
564,908
Collapse internal branches (not terminal branches) with length less than or equal to ``threshold``. A branch length of ``None`` is considered 0 Args: ``threshold`` (``float``): The threshold to use when collapsing branches
def collapse_short_branches(self, threshold): if not isinstance(threshold,float) and not isinstance(threshold,int): raise RuntimeError("threshold must be an integer or a float") elif threshold < 0: raise RuntimeError("threshold cannot be negative") q = deque(); q...
564,909
Contract internal nodes labeled by a number (e.g. branch support) below ``threshold`` Args: ``threshold`` (``float``): The support threshold to use when contracting nodes
def contract_low_support(self, threshold): if not isinstance(threshold, float) and not isinstance(threshold, int): raise TypeError("threshold must be float or int") to_contract = list() for node in self.traverse_preorder(): try: if float(str(node)...
564,912
If the tree has a root edge, drop the edge to be a child of the root node Args: ``label`` (``str``): The desired label of the new child
def deroot(self, label='OLDROOT'): if self.root.edge_length is not None: self.root.add_child(Node(edge_length=self.root.edge_length,label=label)) self.root.edge_length = None
564,913
Return the distance between nodes ``u`` and ``v`` in this ``Tree`` Args: ``u`` (``Node``): Node ``u`` ``v`` (``Node``): Node ``v`` Returns: ``float``: The distance between nodes ``u`` and ``v``
def distance_between(self, u, v): if not isinstance(u, Node): raise TypeError("u must be a Node") if not isinstance(v, Node): raise TypeError("v must be a Node") if u == v: return 0. u_dists = {u:0.}; v_dists = {v:0.} c = u; p = u.pare...
564,915
Return a distance matrix (2D dictionary) of the leaves of this ``Tree`` Args: ``leaf_labels`` (``bool``): ``True`` to have keys be labels of leaf ``Node`` objects, otherwise ``False`` to have keys be ``Node`` objects Returns: ``dict``: Distance matrix (2D dictionary) of the lea...
def distance_matrix(self, leaf_labels=False): M = dict(); leaf_dists = dict() for node in self.traverse_postorder(): if node.is_leaf(): leaf_dists[node] = [[node,0]] else: for c in node.children: if c.edge_length is not...
564,916
Generator over the node-to-parent distances of this ``Tree``; (node,distance) tuples Args: ``terminal`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`` ``unlabeled`` (``bool``): ``...
def distances_from_parent(self, leaves=True, internal=True, unlabeled=False): if not isinstance(leaves, bool): raise TypeError("leaves must be a bool") if not isinstance(internal, bool): raise TypeError("internal must be a bool") if not isinstance(unlabeled, bool...
564,917
Generator over the root-to-node distances of this ``Tree``; (node,distance) tuples Args: ``terminal`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`` ``unlabeled`` (``bool``): ``Tr...
def distances_from_root(self, leaves=True, internal=True, unlabeled=False): if not isinstance(leaves, bool): raise TypeError("leaves must be a bool") if not isinstance(internal, bool): raise TypeError("internal must be a bool") if not isinstance(unlabeled, bool):...
564,918
Compute the sum of all selected edge lengths in this ``Tree`` Args: ``terminal`` (``bool``): ``True`` to include terminal branches, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal branches, otherwise ``False`` Returns: ``float``: Sum of al...
def edge_length_sum(self, terminal=True, internal=True): if not isinstance(terminal, bool): raise TypeError("leaves must be a bool") if not isinstance(internal, bool): raise TypeError("internal must be a bool") return sum(node.edge_length for node in self.travers...
564,919
Return a copy of the subtree rooted at ``node`` Args: ``node`` (``Node``): The root of the desired subtree Returns: ``Tree``: A copy of the subtree rooted at ``node``
def extract_subtree(self, node): if not isinstance(node, Node): raise TypeError("node must be a Node") r = self.root; self.root = node; o = copy(self); self.root = r; return o
564,920
Extract a copy of this ``Tree`` without the leaves labeled by the strings in ``labels`` Args: ``labels`` (``set``): Set of leaf labels to exclude ``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False`` Returns: ``Tree``: Copy ...
def extract_tree_without(self, labels, suppress_unifurcations=True): return self.extract_tree(labels, True, suppress_unifurcations)
564,922
Extract a copy of this ``Tree`` with only the leaves labeled by the strings in ``labels`` Args: ``leaves`` (``set``): Set of leaf labels to include. ``suppress_unifurcations`` (``bool``): ``True`` to suppress unifurcations, otherwise ``False`` Returns: Tree: Copy o...
def extract_tree_with(self, labels, suppress_unifurcations=True): return self.extract_tree(labels, False, suppress_unifurcations)
564,923
Return an indented Newick string, just like ``nw_indent`` in Newick Utilities Args: ``space`` (``int``): The number of spaces a tab should equal Returns: ``str``: An indented Newick string
def indent(self, space=4): if not isinstance(space,int): raise TypeError("space must be an int") if space < 0: raise ValueError("space must be a non-negative integer") space = ' '*space; o = []; l = 0 for c in self.newick(): if c == '(': ...
564,926
Generator over the (non-``None``) ``Node`` labels of this ``Tree`` Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
def labels(self, leaves=True, internal=True): if not isinstance(leaves, bool): raise TypeError("leaves must be a bool") if not isinstance(internal, bool): raise TypeError("internal must be a bool") for node in self.traverse_preorder(): if node.label i...
564,928
Return the Node that is the MRCA of the nodes labeled by a label in ``labels``. If multiple nodes are labeled by a given label, only the last (preorder traversal) will be obtained Args: ``labels`` (``set``): Set of leaf labels Returns: ``Node``: The MRCA of the ``Node`` objects...
def mrca(self, labels): if not isinstance(labels,set): try: labels = set(labels) except: raise TypeError("labels must be iterable") l2n = self.label_to_node(labels) count = dict() for node in l2n.values(): for a...
564,930
Returns the number of lineages of this ``Tree`` that exist ``distance`` away from the root Args: ``distance`` (``float``): The distance away from the root Returns: ``int``: The number of lineages that exist ``distance`` away from the root
def num_lineages_at(self, distance): if not isinstance(distance, float) and not isinstance(distance, int): raise TypeError("distance must be an int or a float") if distance < 0: raise RuntimeError("distance cannot be negative") d = dict(); q = deque(); q.append(s...
564,933
Compute the total number of selected nodes in this ``Tree`` Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`` Returns: ``int``: The total number of selected ...
def num_nodes(self, leaves=True, internal=True): if not isinstance(leaves, bool): raise TypeError("leaves must be a bool") if not isinstance(internal, bool): raise TypeError("internal must be a bool") num = 0 for node in self.traverse_preorder(): ...
564,934
Rename nodes in this ``Tree`` Args: ``renaming_map`` (``dict``): A dictionary mapping old labels (keys) to new labels (values)
def rename_nodes(self, renaming_map): if not isinstance(renaming_map, dict): raise TypeError("renaming_map must be a dict") for node in self.traverse_preorder(): if node.label in renaming_map: node.label = renaming_map[node.label]
564,936
Compute the Sackin balance index of this ``Tree`` Args: ``normalize`` (``str``): How to normalize the Sackin index (if at all) * ``None`` to not normalize * ``"leaves"`` to normalize by the number of leaves * ``"yule"`` to normalize to the Yule model ...
def sackin(self, normalize='leaves'): num_nodes_from_root = dict(); sackin = 0; num_leaves = 0 for node in self.traverse_preorder(): num_nodes_from_root[node] = 1 if not node.is_root(): num_nodes_from_root[node] += num_nodes_from_root[node.parent] ...
564,938
Perform an inorder traversal of the ``Node`` objects in this ``Tree`` Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
def traverse_inorder(self, leaves=True, internal=True): for node in self.root.traverse_inorder(leaves=leaves, internal=internal): yield node
564,941
Perform a postorder traversal of the ``Node`` objects in this ``Tree`` Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
def traverse_postorder(self, leaves=True, internal=True): for node in self.root.traverse_postorder(leaves=leaves, internal=internal): yield node
564,943
Perform a preorder traversal of the ``Node`` objects in this ``Tree`` Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
def traverse_preorder(self, leaves=True, internal=True): for node in self.root.traverse_preorder(leaves=leaves, internal=internal): yield node
564,944
Write this ``Tree`` to a Newick file Args: ``filename`` (``str``): Path to desired output file (plain-text or gzipped)
def write_tree_newick(self, filename, hide_rooted_prefix=False): if not isinstance(filename, str): raise TypeError("filename must be a str") treestr = self.newick() if hide_rooted_prefix: if treestr.startswith('[&R]'): treestr = treestr[4:].strip(...
564,947
``Node`` constructor Args: ``label`` (``str``): Label of this ``Node`` ``edge_length`` (``float``): Length of the edge incident to this ``Node`` Returns: ``Node`` object
def __init__(self, label=None, edge_length=None): self.children = list() # list of child Node objects self.parent = None # parent Node object (None for root) self.label = label # label self.edge_length = edge_length
566,125
Add child to ``Node`` object Args: ``child`` (``Node``): The child ``Node`` to be added
def add_child(self, child): if not isinstance(child, Node): raise TypeError("child must be a Node") self.children.append(child); child.parent = self
566,128
Remove child from ``Node`` object Args: ``child`` (``Node``): The child to remove
def remove_child(self, child): if not isinstance(child, Node): raise TypeError("child must be a Node") try: self.children.remove(child); child.parent = None except: raise RuntimeError("Attempting to remove non-existent child")
566,131
Set the parent of this ``Node`` object. Use this carefully, otherwise you may damage the structure of this ``Tree`` object. Args: ``Node``: The new parent of this ``Node``
def set_parent(self, parent): if not isinstance(parent, Node): raise TypeError("parent must be a Node") self.parent = parent
566,133
Traverse over the ancestors of this ``Node`` Args: ``include_self`` (``bool``): ``True`` to include self in the traversal, otherwise ``False``
def traverse_ancestors(self, include_self=True): if not isinstance(include_self, bool): raise TypeError("include_self must be a bool") if include_self: c = self else: c = self.parent while c is not None: yield c; c = c.parent
566,134
Perform a Breadth-First Search (BFS) starting at this ``Node`` object'. Yields (``Node``, distance) tuples Args: ``include_self`` (``bool``): ``True`` to include self in the traversal, otherwise ``False``
def traverse_bfs(self): if not isinstance(include_self, bool): raise TypeError("include_self must be a bool") q = deque(); dist = dict(); dist[self] = 0; q.append((self,0)) while len(q) != 0: curr = q.popleft(); yield curr for c in curr[0].children: ...
566,135
Perform an inorder traversal starting at this ``Node`` object Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
def traverse_inorder(self, leaves=True, internal=True): c = self; s = deque(); done = False while not done: if c is None: if len(s) == 0: done = True else: c = s.pop() if (leaves and c.is_lea...
566,136
Perform a levelorder traversal starting at this ``Node`` object Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
def traverse_levelorder(self, leaves=True, internal=True): q = deque(); q.append(self) while len(q) != 0: n = q.popleft() if (leaves and n.is_leaf()) or (internal and not n.is_leaf()): yield n q.extend(n.children)
566,137
Perform a postorder traversal starting at this ``Node`` object Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
def traverse_postorder(self, leaves=True, internal=True): s1 = deque(); s2 = deque(); s1.append(self) while len(s1) != 0: n = s1.pop(); s2.append(n); s1.extend(n.children) while len(s2) != 0: n = s2.pop() if (leaves and n.is_leaf()) or (internal and n...
566,138
Perform a preorder traversal starting at this ``Node`` object Args: ``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
def traverse_preorder(self, leaves=True, internal=True): s = deque(); s.append(self) while len(s) != 0: n = s.pop() if (leaves and n.is_leaf()) or (internal and not n.is_leaf()): yield n s.extend(n.children)
566,139
Return uncompressed data for archive entry. For longer files using :meth:`RarFile.open` may be better idea. Parameters: fname filename or RarInfo instance psw password to use for extracting.
def read(self, fname, psw=None): with self.open(fname, 'r', psw) as f: return f.read()
566,736
Extract single file into current directory. Parameters: member filename or :class:`RarInfo` instance path optional destination path pwd optional password to use
def extract(self, member, path=None, pwd=None): if isinstance(member, RarInfo): fname = member.filename else: fname = member self._extract([fname], path, pwd)
566,737
Extract all files into current directory. Parameters: path optional destination path members optional filename or :class:`RarInfo` instance list to extract pwd optional password to use
def extractall(self, path=None, members=None, pwd=None): fnlist = [] if members is not None: for m in members: if isinstance(m, RarInfo): fnlist.append(m.filename) else: fnlist.append(m) self._extract(fn...
566,738
Constructor. Args: channel: A grpc.Channel.
def __init__(self, channel): self._remote_execute = channel.unary_unary( '/OnlineActionHandler/_remote_execute', request_serializer=actions__pb2.OnlineActionRequest.SerializeToString, response_deserializer=actions__pb2.OnlineActionResponse.FromString, ) self._remote_reload =...
567,055
Logic from IPython timeit to handle terminals that cant show mu Args: char (str): character, typically unicode, to try to use fallback (str): ascii character to use if stdout cannot encode char asciimode (bool): if True, always use fallback Example: >>> char = _trychar('µs', 'u...
def _trychar(char, fallback, asciimode=None): # nocover if asciimode is True: # If we request ascii mode simply return it return fallback if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: # pragma: nobranch try: char.encode(sys.stdout.encoding) except...
567,062
Creates a human readable report Args: verbose (int): verbosity level. Either 1, 2, or 3. Returns: str: the report SeeAlso: timerit.Timerit.print Example: >>> import math >>> ti = Timerit(num=1).call(math.factorial, 5) ...
def report(self, verbose=1): lines = [] if verbose >= 2: # use a multi-line format for high verbosity lines.append(self._status_line(tense='past')) if verbose >= 3: unit, mag = _choose_unit(self.total_time, self.unit, ...
567,075
Copy cwl files to a directory where the cwl-runner can find them. Args: from_dir (str): Path to directory where to copy files from (default: the cwl directory of nlppln). to_dir (str): Path to directory where the files should be copied to (e.g., the CWL working directory).
def copy_cwl_files(from_dir=CWL_PATH, to_dir=None): cwl_files = glob.glob('{}{}*.cwl'.format(from_dir, os.sep)) # if no files are found, the output directory should not be created if len(cwl_files) > 0: create_dirs(to_dir) for fi in cwl_files: fo = os.path.join(to_dir, os.path.basen...
567,342
Return path of output file, given a directory, file name and extension. If fname is a path, it is converted to its basename. Args: out_dir (str): path to the directory where output should be written. fname (str): path to the input file. ext (str): file extension of the output file (def...
def out_file_name(out_dir, fname, ext=None): if ext is None: return os.path.join(out_dir, os.path.basename(fname)) fname = remove_ext(fname) return os.path.join(out_dir, '{}.{}'.format(fname, ext))
567,392
Plot normalized fit residuals. The sum of the squares of the residuals equals ``self.chi2``. Individual residuals should be distributed about one, in a Gaussian distribution. Args: plot: :mod:`matplotlib` plotter. If ``None``, uses ``matplotlib.pyplot`. ...
def plot_residuals(self, plot=None): if plot is None: import matplotlib.pyplot as plot x = numpy.arange(1, len(self.residuals) + 1) y = _gvar.mean(self.residuals) yerr = _gvar.sdev(self.residuals) plot.errorbar(x=x, y=y, yerr=yerr, fmt='o', color='b') ...
567,437
Coarse-grain last index of array ``G``. Bin the last index of array ``G`` in bins of width ``ncg``, and replace each bin by its average. Return the binned results. Args: G: Array to be coarse-grained. ncg: Bin width for coarse-graining.
def coarse_grain(G, ncg): if ncg <= 1: return G G = numpy.asarray(G) nbin, remainder = divmod(G.shape[-1], ncg) if remainder != 0: nbin += 1 return numpy.transpose([ numpy.sum(G[..., i:i+ncg], axis=-1) / G[..., i:i+ncg].shape[-1] ...
567,472
Logs, prints, or raises a message. Arguments: message -- message to report severity -- string of one of these values: CRITICAL|ERROR|WARNING|INFO|DEBUG
def log(message, severity="INFO", print_debug=True): print_me = ['WARNING', 'INFO', 'DEBUG'] if severity in print_me: if severity == 'DEBUG': if print_debug: print("{0}: {1}".format(severity, message)) else: print("{0}: {1}".format(severity, message)...
567,651
Uses the stored refresh token to get a new access token. This method assumes that the refresh token exists. Args: None Returns: new access token and expiration time (from now)
def _get_access_from_refresh(self) -> Tuple[str, float]: headers = self._get_authorization_headers() data = { 'grant_type': 'refresh_token', 'refresh_token': self.refresh_token } r = self.session.post(self.TOKEN_URL, headers=headers, data=data) re...
569,263
Constructs and returns the Authorization header for the client app. Args: None Returns: header dict for communicating with the authorization endpoints
def _get_authorization_headers(self) -> dict: auth = base64.encodestring((self.client_id + ':' + self.client_secret).encode('latin-1')).decode('latin-1') auth = auth.replace('\n', '').replace(' ', '') auth = 'Basic {}'.format(auth) headers = {'Authorization': auth} retur...
569,264
Attempts to get a new access token using the refresh token, if needed. If the access token is expired and this instance has a stored refresh token, then the refresh token is in the API call to get a new access token. If successful, this instance is modified in-place with that new access token. ...
def _try_refresh_access_token(self) -> None: if self.refresh_token: if not self.access_token or self._is_access_token_expired(): self.access_token, self.access_expiration = self._get_access_from_refresh() self.access_expiration = time.time() + self.access_exp...
569,265
Authenticates using the code from the EVE SSO. A new Preston object is returned; this object is not modified. The intended usage is: auth = preston.authenticate('some_code_here') Args: code: SSO code Returns: new Preston, authenticated
def authenticate(self, code: str) -> 'Preston': headers = self._get_authorization_headers() data = { 'grant_type': 'authorization_code', 'code': code } r = self.session.post(self.TOKEN_URL, headers=headers, data=data) if not r.status_code == 200: ...
569,266
Fetches the OpenAPI spec from the server. If the spec has already been fetched, the cached version is returned instead. ArgS: None Returns: OpenAPI spec data
def _get_spec(self) -> dict: if self.spec: return self.spec self.spec = requests.get(self.SPEC_URL.format(self.version)).json() return self.spec
569,267
Searches the spec for a path matching the operation id. Args: id: operation id Returns: path to the endpoint, or None if not found
def _get_path_for_op_id(self, id: str) -> Optional[str]: for path_key, path_value in self._get_spec()['paths'].items(): for method in self.METHODS: if method in path_value: if self.OPERATION_ID_KEY in path_value[method]: if path_va...
569,268
Inserts variables into the ESI URL path. Args: path: raw ESI URL path data: data to insert into the URL Returns: path with variables filled
def _insert_vars(self, path: str, data: dict) -> str: data = data.copy() while True: match = re.search(self.VAR_REPLACE_REGEX, path) if not match: return path replace_from = match.group(0) replace_with = str(data.get(match.group(1)...
569,269
Returns the basic information about the authenticated character. Obviously doesn't do anything if this Preston instance is not authenticated, so it returns an empty dict. Args: None Returns: character info if authenticated, otherwise an empty dict
def whoami(self) -> dict: if not self.access_token: return {} self._try_refresh_access_token() return self.session.get(self.WHOAMI_URL).json()
569,270
Queries the ESI by an endpoint URL. This method is not marked "private" as it _can_ be used by consuming code, but it's probably easier to call the `get_op` method instead. Args: path: raw ESI URL path data: data to insert into the URL Returns: ...
def get_path(self, path: str, data: dict) -> Tuple[dict, dict]: path = self._insert_vars(path, data) path = self.BASE_URL + path data = self.cache.check(path) if data: return data self._try_refresh_access_token() r = self.session.get(path) sel...
569,271
Queries the ESI by looking up an operation id. Endpoints are cached, so calls to this method for the same op and args will return the data from the cache instead of making the API call. Args: id: operation id kwargs: data to populate the endpoint's URL variables...
def get_op(self, id: str, **kwargs: str) -> dict: path = self._get_path_for_op_id(id) return self.get_path(path, kwargs)
569,272
Modifies the ESI by an endpoint URL. This method is not marked "private" as it _can_ be used by consuming code, but it's probably easier to call the `get_op` method instead. Args: path: raw ESI URL path path_data: data to format the path with (can be None) ...
def post_path(self, path: str, path_data: Union[dict, None], post_data: Any) -> dict: path = self._insert_vars(path, path_data or {}) path = self.BASE_URL + path self._try_refresh_access_token() return self.session.post(path, json=post_data).json()
569,273
Modifies the ESI by looking up an operation id. Args: path: raw ESI URL path path_data: data to format the path with (can be None) post_data: data to send to ESI Returns: ESI data
def post_op(self, id: str, path_data: Union[dict, None], post_data: Any) -> dict: path = self._get_path_for_op_id(id) return self.post_path(path, path_data, post_data)
569,274
Gets the expiration time of the data from the response headers. Args: headers: dictionary of headers from ESI Returns: value of seconds from now the data expires
def _get_expiration(self, headers: dict) -> int: expiration_str = headers.get('expires') if not expiration_str: return 0 expiration = datetime.strptime(expiration_str, '%a, %d %b %Y %H:%M:%S %Z') delta = (expiration - datetime.utcnow()).total_seconds() return...
569,275
Adds a response to the cache. Args: response: response from ESI Returns: None
def set(self, response: 'requests.Response') -> None: self.data[response.url] = SavedEndpoint( response.json(), self._get_expiration(response.headers) )
569,276
Checks the expiration time for data for a url. If the data has expired, it is deleted from the cache. Args: url: url to check data: page of data for that url Returns: value of either the passed data or None if it expired
def _check_expiration(self, url: str, data: 'SavedEndpoint') -> 'SavedEndpoint': if data.expires_after < time.time(): del self.data[url] data = None return data
569,277
Check if data for a url has expired. Data is not fetched again if it has expired. Args: url: url to check expiration on Returns: value of the data, possibly None
def check(self, url: str) -> Optional[dict]: data = self.data.get(url) if data: data = self._check_expiration(url, data) return data.data if data else None
569,278
SavedEndpoint class. A wrapper around a page from ESI that also includes the expiration time in seconds and the time after which the wrapped data expires. Args: data: page data from ESI expires_in: number of seconds from now that the data expires Returns: ...
def __init__(self, data: dict, expires_in: float) -> None: self.data = data self.expires_in = expires_in self.expires_after = time.time() + expires_in
569,279
Inverse of matrix ``a``. Args: a: Two-dimensional, square matrix/array of numbers and/or :class:`gvar.GVar`\s. Returns: The inverse of matrix ``a``. Raises: ValueError: If matrix is not square and two-dimensional.
def inv(a): amean = gvar.mean(a) if amean.ndim != 2 or amean.shape[0] != amean.shape[1]: raise ValueError('bad matrix shape: ' + str(a.shape)) da = a - amean ainv = numpy.linalg.inv(amean) return ainv - ainv.dot(da.dot(ainv))
569,313
Conversion from latitude, longitude and altitude coordinates to cartesian with respect to an ellipsoid Args: lat (float): Latitude in radians lon (float): Longitude in radians alt (float): Altitude to sea level in meters Return: numpy.array: 3D e...
def _geodetic_to_cartesian(cls, lat, lon, alt): C = Earth.r / np.sqrt(1 - (Earth.e * np.sin(lat)) ** 2) S = Earth.r * (1 - Earth.e ** 2) / np.sqrt(1 - (Earth.e * np.sin(lat)) ** 2) r_d = (C + alt) * np.cos(lat) r_k = (S + alt) * np.sin(lat) norm = np.sqrt(r_d ** 2 + r_k...
570,221
Retrieve a given body orbits and parameters Args: name (str): Object name Return: Body:
def get_body(name): try: body, propag = _bodies[name.lower()] # attach a propagator to the object body.propagate = propag.propagate except KeyError as e: raise UnknownBodyError(e.args[0]) return body
570,223
Retrieve the orbit of a solar system object Args: name (str): The name of the body desired. For exact nomenclature, see :py:func:`available_planets` date (Date): Date at which the state vector will be extracted Return: Orbit: Orbit of the desired object, in the reference fra...
def get_orbit(name, date): # On-demand Propagator and Frame generation if name not in [x.name for x in Bsp().top.list]: raise UnknownBodyError(name) for a, b in Bsp().top.steps(name): if b.name not in _propagator_cache: # Creation of the specific propagator class ...
570,229
Retrieve the Body structure of a JPL .bsp file object Args: name (str) Return: :py:class:`~beyond.constants.Body`
def get_body(name): body = Pck()[name] body.propagate = lambda date: get_orbit(name, date) return body
570,231
Retrieve the position and velocity of a target with respect to a center Args: center (Target): target (Target): date (Date): Return: numpy.array: length-6 array position and velocity (in m and m/s) of the target, with respect to the center
def get(self, center, target, date): if (center.index, target.index) in self.segments: pos, vel = self.segments[center.index, target.index].compute_and_differentiate(date.jd) sign = 1 else: # When we wish to get a segment that is not available in the files (...
570,236
Retrieve a named propagator Args: name (str): Name of the desired propagator Return: Propagator class
def get_propagator(name): from .sgp4 import Sgp4 from .sgp4beta import Sgp4Beta scope = locals().copy() scope.update(globals()) if name not in scope: raise UnknownPropagatorError(name) return scope[name]
570,240
Function for creating listeners for a a list of station Args: stations (iterable): List of TopocentricFrame Return: list of Listener
def stations_listeners(stations): stations = stations if isinstance(stations, (list, tuple)) else [stations] listeners = [] for sta in stations: listeners.append(StationSignalListener(sta)) listeners.append(StationMaxListener(sta)) if sta.mask is not None: listener...
570,241
This method allows to loop over the listeners and trigger the :py:meth:`_bisect` method in case a watched parameter has its state changed. Args: orb (Orbit): The current state of the orbit listeners (iterable): List of Listener objects Return: list of Orbit: ...
def listen(self, orb, listeners): if isinstance(listeners, Listener): listeners = [listeners] orb.event = None results = [] for listener in listeners: if listener.check(orb): results.append(self._bisect(listener.prev, orb, listener)) ...
570,242