INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Ensure the span is valid.
def check_span(span, table): """ Ensure the span is valid. A span is a list of [row, column] pairs. These coordinates must form a rectangular shape. For example, this span will cause an error because it is not rectangular in shape.:: span = [[0, 1], [0, 2], [1, 0]] Spans must be ...
Loop through list of cells and piece them together one by one
def merge_all_cells(cells): """ Loop through list of cells and piece them together one by one Parameters ---------- cells : list of dashtable.data2rst.Cell Returns ------- grid_table : str The final grid table """ current = 0 while len(cells) > 1: count = 0...
converts bpp newick format to normal newick
def bpp2newick(bppnewick): "converts bpp newick format to normal newick" regex1 = re.compile(r" #[-+]?[0-9]*\.?[0-9]*[:]") regex2 = re.compile(r" #[-+]?[0-9]*\.?[0-9]*[;]") regex3 = re.compile(r": ") new = regex1.sub(":", bppnewick) new = regex2.sub(";", new) new = regex3.sub(":", new) r...
used to produce balanced trees returns a tip node from the smaller clade
def return_small_clade(treenode): "used to produce balanced trees, returns a tip node from the smaller clade" node = treenode while 1: if node.children: c1, c2 = node.children node = sorted([c1, c2], key=lambda x: len(x.get_leaves()))[0] else: return node
Used in multiple internal functions ( e. g.. root () ) and. drop_tips () ) to select an internal mrca node or multiple tipnames using fuzzy matching so that every name does not need to be written out by hand.
def fuzzy_match_tipnames(ttree, names, wildcard, regex, mrca=True, mono=True): """ Used in multiple internal functions (e.g., .root()) and .drop_tips()) to select an internal mrca node, or multiple tipnames, using fuzzy matching so that every name does not need to be written out by hand. name: verb...
Returns a toytree copy with all nodes scaled so that the root height equals the value entered for treeheight.
def node_scale_root_height(self, treeheight=1): """ Returns a toytree copy with all nodes scaled so that the root height equals the value entered for treeheight. """ # make tree height = 1 * treeheight ctree = self._ttree.copy() _height = ctree.treenode.height ...
Returns a toytree copy with node heights modified while retaining the same topology but not necessarily node branching order. Node heights are moved up or down uniformly between their parent and highest child node heights in levelorder from root to tips. The total tree height is retained at 1. 0 only relative edge leng...
def node_slider(self, seed=None): """ Returns a toytree copy with node heights modified while retaining the same topology but not necessarily node branching order. Node heights are moved up or down uniformly between their parent and highest child node heights in 'levelorder' f...
Returns a toytree copy with all nodes multiplied by a constant sampled uniformly between ( multiplier 1/ multiplier ).
def node_multiplier(self, multiplier=0.5, seed=None): """ Returns a toytree copy with all nodes multiplied by a constant sampled uniformly between (multiplier, 1/multiplier). """ random.seed(seed) ctree = self._ttree.copy() low, high = sorted([multiplier, 1. / mu...
Returns a tree with branch lengths transformed so that the tree is ultrametric. Strategies include ( 1 ) tip - align: extend tips to the length of the fartest tip from the root ; ( 2 ) non - parametric rate - smoothing: minimize ancestor - descendant local rates on branches to align tips ( not yet supported ) ; and ( 3...
def make_ultrametric(self, strategy=1): """ Returns a tree with branch lengths transformed so that the tree is ultrametric. Strategies include (1) tip-align: extend tips to the length of the fartest tip from the root; (2) non-parametric rate-smoothing: minimize ancestor-descend...
Returns a coalescent tree with ntips samples and waiting times between coalescent events drawn from the kingman coalescent: ( 4N )/ ( k * ( k - 1 )) where N is population size and k is sample size. Edge lengths on the tree are in generations.
def coaltree(ntips, ne=None, seed=None): """ Returns a coalescent tree with ntips samples and waiting times between coalescent events drawn from the kingman coalescent: (4N)/(k*(k-1)), where N is population size and k is sample size. Edge lengths on the tree are in generations. ...
Returns a random tree topology w/ N tips and a root height set to 1 or a user - entered treeheight value. Descendant nodes are evenly spaced between the root and time 0.
def unittree(ntips, treeheight=1.0, seed=None): """ Returns a random tree topology w/ N tips and a root height set to 1 or a user-entered treeheight value. Descendant nodes are evenly spaced between the root and time 0. Parameters ----------- ntips (int): ...
Return an imbalanced ( comb - like ) tree topology.
def imbtree(ntips, treeheight=1.0): """ Return an imbalanced (comb-like) tree topology. """ rtree = toytree.tree() rtree.treenode.add_child(name="0") rtree.treenode.add_child(name="1") for i in range(2, ntips): # empty node cherry = toytre...
Returns a balanced tree topology.
def baltree(ntips, treeheight=1.0): """ Returns a balanced tree topology. """ # require even number of tips if ntips % 2: raise ToytreeError("balanced trees must have even number of tips.") # make first cherry rtree = toytree.tree() rtree.tree...
Get the height of a span in the number of newlines it fills.
def get_span_char_height(span, row_heights): """ Get the height of a span in the number of newlines it fills. Parameters ---------- span : list of list of int A list of [row, column] pairs that make up the span row_heights : list of int A list of the number of newlines for each ...
Convert an html table to a data table and spans.
def html2data(html_string): """ Convert an html table to a data table and spans. Parameters ---------- html_string : str The string containing the html table Returns ------- table : list of lists of str spans : list of lists of lists of int A span is a list of [row,...
Returns newick represenation of the tree in its current state.
def newick(self, tree_format=0): "Returns newick represenation of the tree in its current state." # checks one of root's children for features and extra feats. if self.treenode.children: features = {"name", "dist", "support", "height", "idx"} testnode = self.treenode.chil...
Returns edge values in the order they are plotted ( see. get_edges () )
def get_edge_values(self, feature='idx'): """ Returns edge values in the order they are plotted (see .get_edges()) """ elist = [] for cidx in self._coords.edges[:, 1]: node = self.treenode.search_nodes(idx=cidx)[0] elist.append( (node.__get...
Enter a dictionary mapping node idx or tuple of tipnames to values that you want mapped to the stem and descendant edges that node. Edge values are returned in proper plot order to be entered to the edge_colors or edge_widths arguments to draw (). To see node idx values use node_labels = True in draw (). If dictionary ...
def get_edge_values_from_dict(self, node_value_dict=None, include_stem=True): """ Enter a dictionary mapping node 'idx' or tuple of tipnames to values that you want mapped to the stem and descendant edges that node. Edge values are returned in proper plot order to be entered to the ...
Returns the node idx label of the most recent common ancestor node for the clade that includes the selected tips. Arguments can use fuzzy name matching: a list of tip names wildcard selector or regex string.
def get_mrca_idx_from_tip_labels(self, names=None, wildcard=None, regex=None): """ Returns the node idx label of the most recent common ancestor node for the clade that includes the selected tips. Arguments can use fuzzy name matching: a list of tip names, wildcard selector, or regex st...
Returns node values from tree object in node plot order. To modify values you must modify the. treenode object directly by setting new features. For example
def get_node_values( self, feature=None, show_root=False, show_tips=False, ): """ Returns node values from tree object in node plot order. To modify values you must modify the .treenode object directly by setting new 'features'. For example ...
Return node labels as a dictionary mapping { idx: name } where idx is the order of nodes in preorder traversal. Used internally by the func. get_node_values () to return values in proper order.
def get_node_dict(self, return_internal=False, return_nodes=False): """ Return node labels as a dictionary mapping {idx: name} where idx is the order of nodes in 'preorder' traversal. Used internally by the func .get_node_values() to return values in proper order. return_inter...
Returns coordinates of the tip positions for a tree. If no argument for axis then a 2 - d array is returned. The first column is the x coordinates the second column is the y - coordinates. If you enter an argument for axis then a 1 - d array will be returned of just that axis.
def get_tip_coordinates(self, axis=None): """ Returns coordinates of the tip positions for a tree. If no argument for axis then a 2-d array is returned. The first column is the x coordinates the second column is the y-coordinates. If you enter an argument for axis then a 1-d ar...
Returns tip labels in the order they will be plotted on the tree i. e. starting from zero axis and counting up by units of 1 ( bottom to top in right - facing trees ; left to right in down - facing ). If idx is indicated then a list of tip labels descended from that node will be returned instead of all tip labels. This...
def get_tip_labels(self, idx=None): """ Returns tip labels in the order they will be plotted on the tree, i.e., starting from zero axis and counting up by units of 1 (bottom to top in right-facing trees; left to right in down-facing). If 'idx' is indicated then a list of tip la...
Returns False if there is a polytomy in the tree including if the tree is unrooted ( basal polytomy ) unless you use the include_root = False argument.
def is_bifurcating(self, include_root=True): """ Returns False if there is a polytomy in the tree, including if the tree is unrooted (basal polytomy), unless you use the include_root=False argument. """ ctn1 = -1 + (2 * len(self)) ctn2 = -2 + (2 * len(self)) ...
Ladderize tree ( order descendants ) so that top child has fewer descendants than the bottom child in a left to right tree plot. To reverse this pattern use direction = 1.
def ladderize(self, direction=0): """ Ladderize tree (order descendants) so that top child has fewer descendants than the bottom child in a left to right tree plot. To reverse this pattern use direction=1. """ nself = deepcopy(self) nself.treenode.ladderize(dire...
Returns a copy of the tree where internal nodes with dist < = min_dist are deleted resulting in a collapsed tree. e. g.:
def collapse_nodes(self, min_dist=1e-6, min_support=0): """ Returns a copy of the tree where internal nodes with dist <= min_dist are deleted, resulting in a collapsed tree. e.g.: newtre = tre.collapse_nodes(min_dist=0.001) newtre = tre.collapse_nodes(min_support=50) """...
Returns a copy of the tree with the selected tips removed. The entered value can be a name or list of names. To prune on an internal node to create a subtree see the. prune () function instead.
def drop_tips(self, names=None, wildcard=None, regex=None): """ Returns a copy of the tree with the selected tips removed. The entered value can be a name or list of names. To prune on an internal node to create a subtree see the .prune() function instead. Parameters: ti...
Returns a ToyTree with the selected node rotated for plotting. tip colors do not align correct currently if nodes are rotated...
def rotate_node( self, names=None, wildcard=None, regex=None, idx=None, # modify_tree=False, ): """ Returns a ToyTree with the selected node rotated for plotting. tip colors do not align correct currently if nodes are rotated... ...
Returns a copy of the tree with all polytomies randomly resolved. Does not transform tree in - place.
def resolve_polytomy( self, dist=1.0, support=100, recursive=True): """ Returns a copy of the tree with all polytomies randomly resolved. Does not transform tree in-place. """ nself = self.copy() nself.treenode.resolve_polytomy( ...
Returns a copy of the tree unrooted. Does not transform tree in - place.
def unroot(self): """ Returns a copy of the tree unrooted. Does not transform tree in-place. """ nself = self.copy() nself.treenode.unroot() nself.treenode.ladderize() nself._coords.update() return nself
( Re - ) root a tree by creating selecting a existing split in the tree or creating a new node to split an edge in the tree. Rooting location is selected by entering the tips descendant from one child of the root split ( e. g. names = a or names = [ a b ] ). You can alternatively select a list of tip names using a fuzz...
def root(self, names=None, wildcard=None, regex=None): """ (Re-)root a tree by creating selecting a existing split in the tree, or creating a new node to split an edge in the tree. Rooting location is selected by entering the tips descendant from one child of the root split (e.g....
Plot a Toytree tree returns a tuple of Toyplot ( Canvas Axes ) objects.
def draw( self, tree_style=None, height=None, width=None, axes=None, orient=None, tip_labels=None, tip_labels_colors=None, tip_labels_style=None, tip_labels_align=None, node_labels=None, node_labels_style=None, ...
Determine the side of cell1 that can be merged with cell2.
def get_merge_direction(cell1, cell2): """ Determine the side of cell1 that can be merged with cell2. This is based on the location of the two cells in the table as well as the compatability of their height and width. For example these cells can merge:: cell1 cell2 merge "RIGHT" ...
NHX format: [ &&NHX: prop1 = value1: prop2 = value2 ] MB format: (( a [ &Z = 1 Y = 2 ] b [ &Z = 1 Y = 2 ] ): 1. 0 [ &L = 1 W = 0 ]...
def parse_nhx(NHX_string): """ NHX format: [&&NHX:prop1=value1:prop2=value2] MB format: ((a[&Z=1,Y=2], b[&Z=1,Y=2]):1.0[&L=1,W=0], ... """ # store features ndict = {} # parse NHX or MB features if "[&&NHX:" in NHX_string: NHX_string = NHX_string.replace("[&&NHX:", "") ...
Load * data * from a file or string and return as a list of strings. The data contents could be one newick string ; a multiline NEXUS format for one tree ; multiple newick strings on multiple lines ; or multiple newick strings in a multiline NEXUS format. In any case we will read in the data as a list on lines.
def get_data_from_intree(self): """ Load *data* from a file or string and return as a list of strings. The data contents could be one newick string; a multiline NEXUS format for one tree; multiple newick strings on multiple lines; or multiple newick strings in a multiline NEXUS f...
get newick data from NEXUS
def parse_nexus(self): "get newick data from NEXUS" if self.data[0].strip().upper() == "#NEXUS": nex = NexusParser(self.data) self.data = nex.newicks self.tdict = nex.tdict
test format of intree nex/ nwk extra features
def get_treenodes(self): "test format of intree nex/nwk, extra features" if not self.multitree: # get TreeNodes from Newick extractor = Newick2TreeNode(self.data[0].strip(), fmt=self.fmt) # extract one tree self.treenodes.append(extractor.newick_...
Reads a newick string in the New Hampshire format.
def newick_from_string(self): "Reads a newick string in the New Hampshire format." # split on parentheses to traverse hierarchical tree structure for chunk in self.data.split("(")[1:]: # add child to make this node a parent. self.current_parent = ( self.r...
iterate through data file to extract trees
def extract_tree_block(self): "iterate through data file to extract trees" lines = iter(self.data) while 1: try: line = next(lines).strip() except StopIteration: break # enter trees block if line.lower(...
Parse CLI args.
def parse_command_line(): """ Parse CLI args.""" ## create the parser parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" * Example command-line usage: ## push test branch to conda --label=conda-test for travis CI ./versioner.py -p toyt...
Gets git and init versions and commits since the init version
def get_git_status(self): """ Gets git and init versions and commits since the init version """ ## get git branch self._get_git_branch() ## get tag in the init file self._get_init_release_tag() ## get log commits since <tag> try: self...
if no conflicts then write new tag to
def push_git_package(self): """ if no conflicts then write new tag to """ ## check for conflicts, then write to local files self._pull_branch_from_origin() ## log commits to releasenotes if self.deploy: self._write_commits_to_release_notes() ...
Pulls from origin/ master if you have unmerged conflicts it will raise an exception. You will need to resolve these.
def _pull_branch_from_origin(self): """ Pulls from origin/master, if you have unmerged conflicts it will raise an exception. You will need to resolve these. """ try: ## self.repo.git.pull() subprocess.check_call(["git", "pull", "origin", self.branch]) ...
parses init. py to get previous version
def _get_init_release_tag(self): """ parses init.py to get previous version """ self.init_version = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", open(self.init_file, "r").read(), re.M).group(1)
calls git log to complile a change list
def _get_log_commits(self): """ calls git log to complile a change list """ ## check if update is necessary cmd = "git log --pretty=oneline {}..".format(self.init_version) cmdlist = shlex.split(cmd) commits = subprocess.check_output(cmdlist) ## Sp...
writes commits to the releasenotes file by appending to the end
def _write_commits_to_release_notes(self): """ writes commits to the releasenotes file by appending to the end """ with open(self.release_file, 'a') as out: out.write("==========\n{}\n".format(self.tag)) for commit in self.commits: try: ...
Write version to __init__. py by editing in place
def _write_new_tag_to_init(self): """ Write version to __init__.py by editing in place """ for line in fileinput.input(self.init_file, inplace=1): if line.strip().startswith("__version__"): line = "__version__ = \"" + self.tag + "\"" print(line.str...
Write branch and tag to meta. yaml by editing in place
def _write_branch_and_tag_to_meta_yaml(self): """ Write branch and tag to meta.yaml by editing in place """ ## set the branch to pull source from with open(self.meta_yaml.replace("meta", "template"), 'r') as infile: dat = infile.read() newdat = dat.format(...
Write version to __init__. py by editing in place
def _revert_tag_in_init(self): """ Write version to __init__.py by editing in place """ for line in fileinput.input(self.init_file, inplace=1): if line.strip().startswith("__version__"): line = "__version__ = \"" + self.init_version + "\"" print(li...
tags a new release and pushes to origin/ master
def _push_new_tag_to_git(self): """ tags a new release and pushes to origin/master """ print("Pushing new version to git") ## stage the releasefile and initfileb subprocess.call(["git", "add", self.release_file]) subprocess.call(["git", "add", self.in...
Run the Linux build and use converter to build OSX
def build_conda_packages(self): """ Run the Linux build and use converter to build OSX """ ## check if update is necessary #if self.nversion == self.pversion: # raise SystemExit("Exited: new version == existing version") ## tmp dir bldir = "./tmp-bld" ...
Gets the number of rows included in a span
def get_span_row_count(span): """ Gets the number of rows included in a span Parameters ---------- span : list of lists of int The [row, column] pairs that make up the span Returns ------- rows : int The number of rows included in the span Example ------- C...
Convert x into a numpy. ndarray.
def asarray(x, dtype=None): '''Convert ``x`` into a ``numpy.ndarray``.''' iterable = scalarasiter(x) if isinstance(iterable, ndarray): return iterable else: if not hasattr(iterable, '__len__'): iterable = list(iterable) if dtype == object_type: a ...
Convert x into a column - type numpy. ndarray.
def ascolumn(x, dtype = None): '''Convert ``x`` into a ``column``-type ``numpy.ndarray``.''' x = asarray(x, dtype) return x if len(x.shape) >= 2 else x.reshape(len(x),1)
Converts each multiline string in a table to single line.
def multis_2_mono(table): """ Converts each multiline string in a table to single line. Parameters ---------- table : list of list of str A list of rows containing strings Returns ------- table : list of lists of str """ for row in range(len(table)): for column ...
Get the number of rows
def get_html_row_count(spans): """Get the number of rows""" if spans == []: return 0 row_counts = {} for span in spans: span = sorted(span) try: row_counts[str(span[0][1])] += get_span_row_count(span) except KeyError: row_counts[str(span[0][1])] =...
Computes the Levenshtein distance.
def levenshtein_distance(word1, word2): """ Computes the Levenshtein distance. [Reference]: https://en.wikipedia.org/wiki/Levenshtein_distance [Article]: Levenshtein, Vladimir I. (February 1966). "Binary codes capable of correcting deletions, insertions,and reversals". Soviet Physics Doklady 10...
Decorator which check if timeseries has a better implementation of the function.
def better_ts_function(f): '''Decorator which check if timeseries has a better implementation of the function.''' fname = f.__name__ def _(ts, *args, **kwargs): func = getattr(ts, fname, None) if func: return func(*args, **kwargs) else: return f(ts...
Rolling Z - Score statistics. The Z - score is more formally known as standardised residuals. To calculate the standardised residuals of a data set the average value and the standard deviation of the data value have to be estimated... math:: z = \ frac { x - \ mu ( x ) } { \ sigma ( x ) }
def zscore(ts, **kwargs): '''Rolling Z-Score statistics. The Z-score is more formally known as ``standardised residuals``. To calculate the standardised residuals of a data set, the average value and the standard deviation of the data value have to be estimated. .. math:: z = ...
Rolling Percentage range. Value between 0 and 1 indicating the position in the rolling range.
def prange(ts, **kwargs): '''Rolling Percentage range. Value between 0 and 1 indicating the position in the rolling range. ''' mi = ts.rollmin(**kwargs) ma = ts.rollmax(**kwargs) return (ts - mi)/(ma - mi)
data must be numeric list with a len above 20 This function counts the number of data points in a reduced array
def bindata(data, maxbins = 30, reduction = 0.1): ''' data must be numeric list with a len above 20 This function counts the number of data points in a reduced array ''' tole = 0.01 N = len(data) assert N > 20 vmin = min(data) vmax = max(data) DV = vmax - vmin tol = tole*DV vmax += t...
Combines the values from two map objects using the indx values using the op operator. In situations where there is a missing value it will use the callable function handle_missing
def binOp(op, indx, amap, bmap, fill_vec): ''' Combines the values from two map objects using the indx values using the op operator. In situations where there is a missing value it will use the callable function handle_missing ''' def op_or_missing(id): va = amap.get(id, None) ...
takes a single value and creates a vecotor/ matrix with that value filled in it
def _toVec(shape, val): ''' takes a single value and creates a vecotor / matrix with that value filled in it ''' mat = np.empty(shape) mat.fill(val) return mat
Add leading & trailing space to text to center it within an allowed width
def center_line(space, line): """ Add leading & trailing space to text to center it within an allowed width Parameters ---------- space : int The maximum character width allowed for the text. If the length of text is more than this value, no space will be added.\ line : str ...
Register a function in the function registry. The function will be automatically instantiated if not already an instance.
def register(self, function): """Register a function in the function registry. The function will be automatically instantiated if not already an instance. """ function = inspect.isclass(function) and function() or function name = function.name self[name] = ...
Unregister function by name.
def unregister(self, name): """Unregister function by name. """ try: name = name.name except AttributeError: pass return self.pop(name,None)
Determine if there are spans within a row
def row_includes_spans(table, row, spans): """ Determine if there are spans within a row Parameters ---------- table : list of lists of str row : int spans : list of lists of lists of int Returns ------- bool Whether or not a table's row includes spans """ for c...
Create a StateList object from a states Workflow attribute.
def _setup_states(state_definitions, prev=()): """Create a StateList object from a 'states' Workflow attribute.""" states = list(prev) for state_def in state_definitions: if len(state_def) != 2: raise TypeError( "The 'state' attribute of a workflow should be " ...
Create a TransitionList object from a transitions Workflow attribute.
def _setup_transitions(tdef, states, prev=()): """Create a TransitionList object from a 'transitions' Workflow attribute. Args: tdef: list of transition definitions states (StateList): already parsed state definitions. prev (TransitionList): transition definitions from a parent. Re...
Decorator to declare a function as a transition implementation.
def transition(trname='', field='', check=None, before=None, after=None): """Decorator to declare a function as a transition implementation.""" if is_callable(trname): raise ValueError( "The @transition decorator should be called as " "@transition(['transition_name'], **kwargs)")...
Ensure the given function has a xworkflows_hook attribute.
def _make_hook_dict(fun): """Ensure the given function has a xworkflows_hook attribute. That attribute has the following structure: >>> { ... 'before': [('state', <TransitionHook>), ...], ... } """ if not hasattr(fun, 'xworkflows_hook'): fun.xworkflows_hook = { HOOK_...
Checks whether a given State matches self. names.
def _match_state(self, state): """Checks whether a given State matches self.names.""" return (self.names == '*' or state in self.names or state.name in self.names)
Checks whether a given Transition matches self. names.
def _match_transition(self, transition): """Checks whether a given Transition matches self.names.""" return (self.names == '*' or transition in self.names or transition.name in self.names)
Whether this hook applies to the given transition/ state.
def applies_to(self, transition, from_state=None): """Whether this hook applies to the given transition/state. Args: transition (Transition): the transition to check from_state (State or None): the state to check. If absent, the check is 'might this hook apply to...
Run the pre - transition checks.
def _pre_transition_checks(self): """Run the pre-transition checks.""" current_state = getattr(self.instance, self.field_name) if current_state not in self.transition.source: raise InvalidTransitionError( "Transition '%s' isn't available from state '%s'." % ...
Filter a list of hooks keeping only applicable ones.
def _filter_hooks(self, *hook_kinds): """Filter a list of hooks, keeping only applicable ones.""" hooks = sum((self.hooks.get(kind, []) for kind in hook_kinds), []) return sorted(hook for hook in hooks if hook.applies_to(self.transition, self.current_state))
Performs post - transition actions.
def _post_transition(self, result, *args, **kwargs): """Performs post-transition actions.""" for hook in self._filter_hooks(HOOK_AFTER, HOOK_ON_ENTER): hook(self.instance, result, *args, **kwargs)
Import previously defined implementations.
def load_parent_implems(self, parent_implems): """Import previously defined implementations. Args: parent_implems (ImplementationList): List of implementations defined in a parent class. """ for trname, attr, implem in parent_implems.get_custom_implementation...
Add an implementation.
def add_implem(self, transition, attribute, function, **kwargs): """Add an implementation. Args: transition (Transition): the transition for which the implementation is added attribute (str): the name of the attribute where the implementation will...
Decide whether a given value should be collected.
def should_collect(self, value): """Decide whether a given value should be collected.""" return ( # decorated with @transition isinstance(value, TransitionWrapper) # Relates to a compatible transition and value.trname in self.workflow.transitions ...
Collect the implementations from a given attributes dict.
def collect(self, attrs): """Collect the implementations from a given attributes dict.""" for name, value in attrs.items(): if self.should_collect(value): transition = self.workflow.transitions[value.trname] if ( value.trname in self....
Retrieve a list of cutom implementations.
def get_custom_implementations(self): """Retrieve a list of cutom implementations. Yields: (str, str, ImplementationProperty) tuples: The name of the attribute an implementation lives at, the name of the related transition, and the related implementation. ...
Looks at an object method and registers it for relevent transitions.
def register_function_hooks(self, func): """Looks at an object method and registers it for relevent transitions.""" for hook_kind, hooks in func.xworkflows_hook.items(): for field_name, hook in hooks: if field_name and field_name != self.state_field: conti...
Checks whether an ImplementationProperty may override an attribute.
def _may_override(self, implem, other): """Checks whether an ImplementationProperty may override an attribute.""" if isinstance(other, ImplementationProperty): # Overriding another custom implementation for the same transition # and field return (other.transition == i...
Update the attrs dict with generated ImplementationProperty.
def fill_attrs(self, attrs): """Update the 'attrs' dict with generated ImplementationProperty.""" for trname, attrname in self.transitions_at.items(): implem = self.implementations[trname] if attrname in attrs: conflicting = attrs[attrname] if no...
Perform all actions on a given attribute dict.
def transform(self, attrs): """Perform all actions on a given attribute dict.""" self.collect(attrs) self.add_missing_implementations() self.fill_attrs(attrs)
Log a transition.
def log_transition(self, transition, from_state, instance, *args, **kwargs): """Log a transition. Args: transition (Transition): the name of the performed transition from_state (State): the source state instance (object): the modified object Kwargs: ...
Attach a workflow to the attribute list ( create a StateProperty ).
def _add_workflow(mcs, field_name, state_field, attrs): """Attach a workflow to the attribute list (create a StateProperty).""" attrs[field_name] = StateProperty(state_field.workflow, field_name)
Finds all occurrences of a workflow in the attributes definitions.
def _find_workflows(mcs, attrs): """Finds all occurrences of a workflow in the attributes definitions. Returns: dict(str => StateField): maps an attribute name to a StateField describing the related Workflow. """ workflows = {} for attribute, value in...
Collect and enhance transition definitions to a workflow.
def _add_transitions(mcs, field_name, workflow, attrs, implems=None): """Collect and enhance transition definitions to a workflow. Modifies the 'attrs' dict in-place. Args: field_name (str): name of the field transitions should update workflow (Workflow): workflow we're...
Updates cartesian coordinates for drawing tree graph
def update(self): "Updates cartesian coordinates for drawing tree graph" # get new shape and clear for attrs self.edges = np.zeros((self.ttree.nnodes - 1, 2), dtype=int) self.verts = np.zeros((self.ttree.nnodes, 2), dtype=float) self.lines = [] self.coords =...
set root idx highest tip idxs lowest ordered as ladderized
def update_idxs(self): "set root idx highest, tip idxs lowest ordered as ladderized" # internal nodes: root is highest idx idx = self.ttree.nnodes - 1 for node in self.ttree.treenode.traverse("levelorder"): if not node.is_leaf(): node.add_feature("idx", idx) ...
after pruning fixed order needs update to match new nnodes/ ntips.
def update_fixed_order(self): "after pruning fixed order needs update to match new nnodes/ntips." # set tips order if fixing for multi-tree plotting (default None) fixed_order = self.ttree._fixed_order self.ttree_fixed_order = None self.ttree_fixed_idx = list(range(self.ttree.nti...
Sets. edges. verts for node positions. X and Y positions here refer to base assumption that tree is right facing reorient_coordinates () will handle re - translating this.
def assign_vertices(self): """ Sets .edges, .verts for node positions. X and Y positions here refer to base assumption that tree is right facing, reorient_coordinates() will handle re-translating this. """ # shortname uselen = bool(self.ttree.style.use_e...
Returns a modified. verts array with new coordinates for nodes. This does not need to modify. edges. The order of nodes and therefore of verts rows is still the same because it is still based on the tree branching order ( ladderized usually ).
def reorient_coordinates(self): """ Returns a modified .verts array with new coordinates for nodes. This does not need to modify .edges. The order of nodes, and therefore of verts rows is still the same because it is still based on the tree branching order (ladderized usually). ...
An iterator of timeseries as tuples.
def tsiterator(ts, dateconverter=None, desc=None, clean=False, start_value=None, **kwargs): '''An iterator of timeseries as tuples.''' dateconverter = dateconverter or default_converter yield ['Date'] + ts.names() if clean == 'full': for dt, value in full_clean(ts, dateconverter, ...
Modify coords to shift tree position for x y baseline arguments. This is useful for arrangeing trees onto a Canvas with other plots but still sharing a common cartesian axes coordinates.
def set_baselines(self): """ Modify coords to shift tree position for x,y baseline arguments. This is useful for arrangeing trees onto a Canvas with other plots, but still sharing a common cartesian axes coordinates. """ if self.style.xbaseline: if self.styl...
Add text offset from tips of tree with correction for orientation and fixed_order which is usually used in multitree plotting.
def add_tip_labels_to_axes(self): """ Add text offset from tips of tree with correction for orientation, and fixed_order which is usually used in multitree plotting. """ # get tip-coords and replace if using fixed_order xpos = self.ttree.get_tip_coordinates('x') ...
add lines to connect tips to zero axis for tip_labels_align = True
def add_tip_lines_to_axes(self): "add lines to connect tips to zero axis for tip_labels_align=True" # get tip-coords and align-coords from verts xpos, ypos, aedges, averts = self.get_tip_label_coords() if self.style.tip_labels_align: self.axes.graph( aedges,...
Modifies display range to ensure tip labels fit. This is a bit hackish still. The problem is that the extents range of the rendered text is totally correct. So we add a little buffer here. Should add for user to be able to modify this if needed. If not using edge lengths then need to use unit length for treeheight.
def fit_tip_labels(self): """ Modifies display range to ensure tip labels fit. This is a bit hackish still. The problem is that the 'extents' range of the rendered text is totally correct. So we add a little buffer here. Should add for user to be able to modify this if needed. I...