INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Convert profile to sequence and normalize profile across sites.
def prof2seq(profile, gtr, sample_from_prof=False, normalize=True): """ Convert profile to sequence and normalize profile across sites. Parameters ---------- profile : numpy 2D array Profile. Shape of the profile should be (L x a), where L - sequence length, a - alphabet size. ...
return a normalized version of a profile matrix
def normalize_profile(in_profile, log=False, return_offset = True): """return a normalized version of a profile matrix Parameters ---------- in_profile : np.array shape Lxq, will be normalized to one across each row log : bool, optional treat the input as log probabilities retur...
Print log message * msg * to stdout.
def logger(self, msg, level, warn=False): """ Print log message *msg* to stdout. Parameters ----------- msg : str String to print on the screen level : int Log-level. Only the messages with a level higher than the current verbose l...
Set a new GTR object
def gtr(self, value): """ Set a new GTR object Parameters ----------- value : GTR the new GTR object """ if not (isinstance(value, GTR) or isinstance(value, GTR_site_specific)): raise TypeError(" GTR instance expected") self._gtr...
Create new GTR model if needed and set the model as an attribute of the TreeAnc class
def set_gtr(self, in_gtr, **kwargs): """ Create new GTR model if needed, and set the model as an attribute of the TreeAnc class Parameters ----------- in_gtr : str, GTR The gtr model to be assigned. If string is passed, it is taken as the name o...
assigns a tree to the internal self. _tree variable. The tree is either loaded from file ( if in_tree is str ) or assigned ( if in_tree is a Phylo. tree )
def tree(self, in_tree): ''' assigns a tree to the internal self._tree variable. The tree is either loaded from file (if in_tree is str) or assigned (if in_tree is a Phylo.tree) ''' from os.path import isfile if isinstance(in_tree, Phylo.BaseTree.Tree): self....
Reads in the alignment ( from a dict MultipleSeqAlignment or file as necessary ) sets tree - related parameters and attaches sequences to the tree nodes.
def aln(self,in_aln): """ Reads in the alignment (from a dict, MultipleSeqAlignment, or file, as necessary), sets tree-related parameters, and attaches sequences to the tree nodes. Parameters ---------- in_aln : MultipleSeqAlignment, str, dict/defaultdict ...
set the length of the uncompressed sequence. its inverse one_mutation is frequently used as a general length scale. This can t be changed once it is set.
def seq_len(self,L): """set the length of the uncompressed sequence. its inverse 'one_mutation' is frequently used as a general length scale. This can't be changed once it is set. Parameters ---------- L : int length of the sequence alignment """ ...
For each node of the tree check whether there is a sequence available in the alignment and assign this sequence as a character array
def _attach_sequences_to_nodes(self): ''' For each node of the tree, check whether there is a sequence available in the alignment and assign this sequence as a character array ''' failed_leaves= 0 if self.is_vcf: # if alignment is specified as difference from ...
Create the reduced alignment from the full sequences attached to ( some ) tree nodes. The methods collects all sequences from the tree nodes creates the alignment counts the multiplicity for each column of the alignment ( alignment pattern ) and creates the reduced alignment where only the unique patterns are present. ...
def make_reduced_alignment(self): """ Create the reduced alignment from the full sequences attached to (some) tree nodes. The methods collects all sequences from the tree nodes, creates the alignment, counts the multiplicity for each column of the alignment ('alignment pattern'),...
prepare the dictionary specifying differences from a reference sequence to construct the reduced alignment with variable sites only. NOTE: - sites can be constant but different from the reference - sites can be constant plus a ambiguous sites
def process_alignment_dict(self): """ prepare the dictionary specifying differences from a reference sequence to construct the reduced alignment with variable sites only. NOTE: - sites can be constant but different from the reference - sites can be constant plus a ambiguo...
Set link to parent and calculate distance to root for all tree nodes. Should be run once the tree is read and after every rerooting topology change or branch length optimizations.
def prepare_tree(self): """ Set link to parent and calculate distance to root for all tree nodes. Should be run once the tree is read and after every rerooting, topology change or branch length optimizations. """ self.tree.root.branch_length = 0.001 self.tree.root...
Set auxilliary parameters to every node of the tree.
def _prepare_nodes(self): """ Set auxilliary parameters to every node of the tree. """ self.tree.root.up = None self.tree.root.bad_branch=self.tree.root.bad_branch if hasattr(self.tree.root, 'bad_branch') else False internal_node_count = 0 for clade in self.tree.g...
For each node in the tree set its root - to - node distance as dist2root attribute
def _calc_dist2root(self): """ For each node in the tree, set its root-to-node distance as dist2root attribute """ self.tree.root.dist2root = 0.0 for clade in self.tree.get_nonterminals(order='preorder'): # parents first for c in clade.clades: ...
Calculates a GTR model given the multiple sequence alignment and the tree. It performs ancestral sequence inferrence ( joint or marginal ) followed by the branch lengths optimization. Then the numbers of mutations are counted in the optimal tree and related to the time within the mutation happened. From these statistic...
def infer_gtr(self, print_raw=False, marginal=False, normalized_rate=True, fixed_pi=None, pc=5.0, **kwargs): """ Calculates a GTR model given the multiple sequence alignment and the tree. It performs ancestral sequence inferrence (joint or marginal), followed by the bra...
Reconstruct ancestral sequences
def reconstruct_anc(self, method='probabilistic', infer_gtr=False, marginal=False, **kwargs): """Reconstruct ancestral sequences Parameters ---------- method : str Method to use. Supported values are "fitch" and "ml" infer_gtr : bool ...
Recalculates mutations using the original compressed sequence for terminal nodes which will recover ambiguous bases at variable sites. ( See get_mutations )
def recover_var_ambigs(self): """ Recalculates mutations using the original compressed sequence for terminal nodes which will recover ambiguous bases at variable sites. (See 'get_mutations') Once this has been run, infer_gtr and other functions which depend on self.gtr.alphabet ...
Get the mutations on a tree branch. Take compressed sequences from both sides of the branch ( attached to the node ) compute mutations between them and expand these mutations to the positions in the real sequences.
def get_mutations(self, node, keep_var_ambigs=False): """ Get the mutations on a tree branch. Take compressed sequences from both sides of the branch (attached to the node), compute mutations between them, and expand these mutations to the positions in the real sequences. Parame...
uses results from marginal ancestral inference to return a joint distribution of the sequence states at both ends of the branch.
def get_branch_mutation_matrix(self, node, full_sequence=False): """uses results from marginal ancestral inference to return a joint distribution of the sequence states at both ends of the branch. Parameters ---------- node : Phylo.clade node of the tree full...
Expand a nodes compressed sequence into the real sequence
def expanded_sequence(self, node, include_additional_constant_sites=False): """ Expand a nodes compressed sequence into the real sequence Parameters ---------- node : PhyloTree.Clade Tree node Returns ------- seq : np.array Sequence...
For VCF - based TreeAnc objects we do not want to store the entire sequence on every node as they could be large. Instead this returns the dict of variants & their positions for this sequence. This is used in place of: py: meth: treetime. TreeAnc. expanded_sequence for VCF - based objects throughout TreeAnc. However us...
def dict_sequence(self, node, keep_var_ambigs=False): """ For VCF-based TreeAnc objects, we do not want to store the entire sequence on every node, as they could be large. Instead, this returns the dict of variants & their positions for this sequence. This is used in place of :py...
Reconstruct ancestral states using Fitch s algorithm. The method requires sequences to be assigned to leaves. It implements the iteration from leaves to the root constructing the Fitch profiles for each character of the sequence and then by propagating from the root to the leaves reconstructs the sequences of the inter...
def _fitch_anc(self, **kwargs): """ Reconstruct ancestral states using Fitch's algorithm. The method requires sequences to be assigned to leaves. It implements the iteration from leaves to the root constructing the Fitch profiles for each character of the sequence, and then by pr...
Determine the Fitch profile for a single character of the node s sequence. The profile is essentially the intersection between the children s profiles or if the former is empty the union of the profiles.
def _fitch_state(self, node, pos): """ Determine the Fitch profile for a single character of the node's sequence. The profile is essentially the intersection between the children's profiles or, if the former is empty, the union of the profiles. Parameters ---------- ...
Find the intersection of any number of 1D arrays. Return the sorted unique values that are in all of the input arrays. Adapted from numpy. lib. arraysetops. intersect1d
def _fitch_intersect(self, arrays): """ Find the intersection of any number of 1D arrays. Return the sorted, unique values that are in all of the input arrays. Adapted from numpy.lib.arraysetops.intersect1d """ def pairwise_intersect(arr1, arr2): s2 = set(arr2...
return the likelihood of the observed sequences given the tree
def sequence_LH(self, pos=None, full_sequence=False): """return the likelihood of the observed sequences given the tree Parameters ---------- pos : int, optional position in the sequence, if none, the sum over all positions will be returned full_sequence : bool, opti...
Calculate the likelihood of the given realization of the sequences in the tree
def ancestral_likelihood(self): """ Calculate the likelihood of the given realization of the sequences in the tree Returns ------- log_lh : float The tree likelihood given the sequences """ log_lh = np.zeros(self.multiplicity.shape[0]) ...
Set branch lengths to either mutation lengths of given branch lengths. The assigend values are to be used in the following ML analysis.
def _branch_length_to_gtr(self, node): """ Set branch lengths to either mutation lengths of given branch lengths. The assigend values are to be used in the following ML analysis. """ if self.use_mutation_length: return max(ttconf.MIN_BRANCH_LENGTH*self.one_mutation, n...
Perform marginal ML reconstruction of the ancestral states. In contrast to joint reconstructions this needs to access the probabilities rather than only log probabilities and is hence handled by a separate function.
def _ml_anc_marginal(self, store_compressed=False, final=True, sample_from_profile=False, debug=False, **kwargs): """ Perform marginal ML reconstruction of the ancestral states. In contrast to joint reconstructions, this needs to access the probabilities rather than only...
Perform joint ML reconstruction of the ancestral states. In contrast to marginal reconstructions this only needs to compare and multiply LH and can hence operate in log space.
def _ml_anc_joint(self, store_compressed=True, final=True, sample_from_profile=False, debug=False, **kwargs): """ Perform joint ML reconstruction of the ancestral states. In contrast to marginal reconstructions, this only needs to compare and multiply LH and ...
make a compressed representation of a pair of sequences only counting the number of times a particular pair of states ( e. g. ( A T )) is observed the the aligned sequences of parent and child.
def _store_compressed_sequence_to_node(self, node): """ make a compressed representation of a pair of sequences only counting the number of times a particular pair of states (e.g. (A,T)) is observed the the aligned sequences of parent and child. Parameters ----------- ...
Traverse the tree and for each node store the compressed sequence pair. ** Note ** sequence reconstruction should be performed prior to calling this method.
def _store_compressed_sequence_pairs(self): """ Traverse the tree, and for each node store the compressed sequence pair. **Note** sequence reconstruction should be performed prior to calling this method. """ self.logger("TreeAnc._store_compressed_sequence_pairs...",2) ...
Perform optimization for the branch lengths of the entire tree. This method only does a single path and needs to be iterated.
def optimize_branch_length(self, mode='joint', **kwargs): """ Perform optimization for the branch lengths of the entire tree. This method only does a single path and needs to be iterated. **Note** this method assumes that each node stores information about its sequence as numpy....
EXPERIMENTAL GLOBAL OPTIMIZATION
def optimize_branch_length_global(self, **kwargs): """ EXPERIMENTAL GLOBAL OPTIMIZATION """ self.logger("TreeAnc.optimize_branch_length_global: running branch length optimization...",1) def neg_log(s): for si, n in zip(s, self.tree.find_clades(order='preorder')): ...
Calculate optimal branch length given the sequences of node and parent
def optimal_branch_length(self, node): ''' Calculate optimal branch length given the sequences of node and parent Parameters ---------- node : PhyloTree.Clade TreeNode, attached to the branch. Returns ------- new_len : float Optimal...
calculate the marginal distribution of sequence states on both ends of the branch leading to node
def marginal_branch_profile(self, node): ''' calculate the marginal distribution of sequence states on both ends of the branch leading to node, Parameters ---------- node : PhyloTree.Clade TreeNode, attached to the branch. Returns ------- ...
calculate the marginal distribution of sequence states on both ends of the branch leading to node
def optimal_marginal_branch_length(self, node, tol=1e-10): ''' calculate the marginal distribution of sequence states on both ends of the branch leading to node, Parameters ---------- node : PhyloTree.Clade TreeNode, attached to the branch. Returns ...
If the branch length is less than the minimal value remove the branch from the tree. ** Requires ** ancestral sequence reconstruction
def prune_short_branches(self): """ If the branch length is less than the minimal value, remove the branch from the tree. **Requires** ancestral sequence reconstruction """ self.logger("TreeAnc.prune_short_branches: pruning short branches (max prob at zero)...", 1) for no...
Iteratively set branch lengths and reconstruct ancestral sequences until the values of either former or latter do not change. The algorithm assumes knowing only the topology of the tree and requires that sequences are assigned to all leaves of the tree.
def optimize_seq_and_branch_len(self,reuse_branch_len=True, prune_short=True, marginal_sequences=False, branch_length_mode='joint', max_iter=5, infer_gtr=False, **kwargs): """ Iteratively set branch lengths and reconstruct ancestral...
Get the multiple sequence alignment including reconstructed sequences for the internal nodes.
def get_reconstructed_alignment(self): """ Get the multiple sequence alignment, including reconstructed sequences for the internal nodes. Returns ------- new_aln : MultipleSeqAlignment Alignment including sequences of all internal nodes """ fr...
For VCF - based objects returns a nested dict with all the information required to reconstruct sequences for all nodes ( terminal and internal ).
def get_tree_dict(self, keep_var_ambigs=False): """ For VCF-based objects, returns a nested dict with all the information required to reconstruct sequences for all nodes (terminal and internal). Parameters ---------- keep_var_ambigs : boolean If true, generat...
function that return the product of the transition matrix and the equilibrium frequencies to obtain the rate matrix of the GTR model
def Q(self): """function that return the product of the transition matrix and the equilibrium frequencies to obtain the rate matrix of the GTR model """ tmp = np.einsum('ia,ij->ija', self.Pi, self.W) diag_vals = np.sum(tmp, axis=0) for x in range(tmp.shape[-...
Overwrite the GTR model given the provided data
def assign_rates(self, mu=1.0, pi=None, W=None): """ Overwrite the GTR model given the provided data Parameters ---------- mu : float Substitution rate W : nxn matrix Substitution matrix pi : n vector Equilibrium frequenc...
Creates a random GTR model
def random(cls, L=1, avg_mu=1.0, alphabet='nuc', pi_dirichlet_alpha=1, W_dirichlet_alpha=3.0, mu_gamma_alpha=3.0): """ Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (s...
Create a GTR model by specifying the matrix explicitly
def custom(cls, mu=1.0, pi=None, W=None, **kwargs): """ Create a GTR model by specifying the matrix explicitly Parameters ---------- mu : float Substitution rate W : nxn matrix Substitution matrix pi : n vector Equilibriu...
Infer a GTR model by specifying the number of transitions and time spent in each character. The basic equation that is being solved is
def infer(cls, sub_ija, T_ia, root_state, pc=0.01, gap_limit=0.01, Nit=30, dp=1e-5, **kwargs): """ Infer a GTR model by specifying the number of transitions and time spent in each character. The basic equation that is being solved is :math:`n_{ij} = pi_i W_{ij} T_j` ...
Compute the probability to observe seq_ch ( child sequence ) after time t starting from seq_p ( parent sequence ).
def prob_t(self, seq_p, seq_ch, t, pattern_multiplicity = None, return_log=False, ignore_gaps=True): """ Compute the probability to observe seq_ch (child sequence) after time t starting from seq_p (parent sequence). Parameters ---------- seq_p : characte...
Overwrite the GTR model given the provided data
def assign_rates(self, mu=1.0, pi=None, W=None): """ Overwrite the GTR model given the provided data Parameters ---------- mu : float Substitution rate W : nxn matrix Substitution matrix pi : n vector Equilibrium frequenc...
Create standard model of molecular evolution.
def standard(model, **kwargs): """ Create standard model of molecular evolution. Parameters ---------- model : str Model to create. See list of available models below **kwargs: Key word arguments to be passed to the model **Available ...
Creates a random GTR model
def random(cls, mu=1.0, alphabet='nuc'): """ Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (should be standard: 'nuc', 'nuc_gap', 'aa', 'aa_gap') """ alphabet=alph...
Infer a GTR model by specifying the number of transitions and time spent in each character. The basic equation that is being solved is
def infer(cls, nij, Ti, root_state, fixed_pi=None, pc=5.0, gap_limit=0.01, **kwargs): """ Infer a GTR model by specifying the number of transitions and time spent in each character. The basic equation that is being solved is :math:`n_{ij} = pi_i W_{ij} T_j` where :math:`n_{ij}`...
Check the main diagonal of Q and fix it in case it does not corresond the definition of the rate matrix. Should be run every time when creating custom GTR model.
def _check_fix_Q(self, fixed_mu=False): """ Check the main diagonal of Q and fix it in case it does not corresond the definition of the rate matrix. Should be run every time when creating custom GTR model. """ # fix Q self.Pi /= self.Pi.sum() # correct the Pi manu...
Perform eigendecompositon of the rate matrix and stores the left - and right - matrices to convert the sequence profiles to the GTR matrix eigenspace and hence to speed - up the computations.
def _eig(self): """ Perform eigendecompositon of the rate matrix and stores the left- and right- matrices to convert the sequence profiles to the GTR matrix eigenspace and hence to speed-up the computations. """ # eigendecomposition of the rate matrix eigvals, eig...
Perform eigendecompositon of the rate matrix and stores the left - and right - matrices to convert the sequence profiles to the GTR matrix eigenspace and hence to speed - up the computations.
def _eig_sym(self): """ Perform eigendecompositon of the rate matrix and stores the left- and right- matrices to convert the sequence profiles to the GTR matrix eigenspace and hence to speed-up the computations. """ # eigendecomposition of the rate matrix tmpp = n...
Make a compressed representation of a pair of sequences only counting the number of times a particular pair of states ( e. g. ( A T )) is observed in the aligned sequences of parent and child.
def compress_sequence_pair(self, seq_p, seq_ch, pattern_multiplicity=None, ignore_gaps=False): ''' Make a compressed representation of a pair of sequences, only counting the number of times a particular pair of states (e.g. (A,T)) is observed in the aligned...
Calculate the probability of observing a sequence pair at a distance t for compressed sequences
def prob_t_compressed(self, seq_pair, multiplicity, t, return_log=False): ''' Calculate the probability of observing a sequence pair at a distance t, for compressed sequences Parameters ---------- seq_pair : numpy array :code:`np.array([(0,1), (2,2), ()..]...
Compute the probability to observe seq_ch ( child sequence ) after time t starting from seq_p ( parent sequence ).
def prob_t(self, seq_p, seq_ch, t, pattern_multiplicity = None, return_log=False, ignore_gaps=True): """ Compute the probability to observe seq_ch (child sequence) after time t starting from seq_p (parent sequence). Parameters ---------- seq_p : characte...
Find the optimal distance between the two sequences
def optimal_t(self, seq_p, seq_ch, pattern_multiplicity=None, ignore_gaps=False): ''' Find the optimal distance between the two sequences Parameters ---------- seq_p : character array Parent sequence seq_c : character array Child sequence ...
Find the optimal distance between the two sequences for compressed sequences
def optimal_t_compressed(self, seq_pair, multiplicity, profiles=False, tol=1e-10): """ Find the optimal distance between the two sequences, for compressed sequences Parameters ---------- seq_pair : compressed_sequence_pair Compressed representation of sequences alo...
Calculate the probability of observing a node pair at a distance t
def prob_t_profiles(self, profile_pair, multiplicity, t, return_log=False, ignore_gaps=True): ''' Calculate the probability of observing a node pair at a distance t Parameters ---------- profile_pair: numpy arrays Probability distributions ...
Compute the probability of the sequence state of the parent at time ( t + t0 backwards ) given the sequence state of the child ( profile ) at time t0.
def propagate_profile(self, profile, t, return_log=False): """ Compute the probability of the sequence state of the parent at time (t+t0, backwards), given the sequence state of the child (profile) at time t0. Parameters ---------- profile : numpy.array ...
Compute the probability of the sequence state of the child at time t later given the parent profile.
def evolve(self, profile, t, return_log=False): """ Compute the probability of the sequence state of the child at time t later, given the parent profile. Parameters ---------- profile : numpy.array Sequence profile. Shape = (L, a), where L - seq...
Parameters ----------
def _exp_lt(self, t): """ Parameters ---------- t : float time to propagate Returns -------- exp_lt : numpy.array Array of values exp(lambda(i) * t), where (i) - alphabet index (the eigenvalue number). """ r...
Parameters ----------
def expQt(self, t): ''' Parameters ---------- t : float Time to propagate Returns -------- expQt : numpy.array Matrix exponential of exo(Qt) ''' eLambdaT = np.diag(self._exp_lt(t)) # vector length = a Qs = self....
Returns ------- Qtds: Returns 2 V_ { ij } \ lambda_j s e^ { \ lambda_j s ** 2 } V^ { - 1 } _ { jk } This is the derivative of the branch probability with respect to s = \ sqrt ( t )
def expQsds(self, s): ''' Returns ------- Qtds : Returns 2 V_{ij} \lambda_j s e^{\lambda_j s**2 } V^{-1}_{jk} This is the derivative of the branch probability with respect to s=\sqrt(t) ''' lambda_eLambdaT = np.diag(2.0*self._exp_lt(s**2)*self.eigenvals*s...
Returns ------- Qtdtdt: Returns V_ { ij } \ lambda_j^2 e^ { \ lambda_j s ** 2 } V^ { - 1 } _ { jk } This is the second derivative of the branch probability wrt time
def expQsdsds(self, s): ''' Returns ------- Qtdtdt : Returns V_{ij} \lambda_j^2 e^{\lambda_j s**2} V^{-1}_{jk} This is the second derivative of the branch probability wrt time ''' t=s**2 elt = self._exp_lt(t) lambda_eLambdaT = np.diag(elt*...
Returns the log - likelihood of sampling a sequence from equilibrium frequency. Expects a sequence as numpy array
def sequence_logLH(self,seq, pattern_multiplicity=None): """ Returns the log-likelihood of sampling a sequence from equilibrium frequency. Expects a sequence as numpy array Parameters ---------- seq : numpy array Compressed sequence as an array of chars ...
Converts branch length to years and plots the time tree on a time axis.
def plot_vs_years(tt, step = None, ax=None, confidence=None, ticks=True, **kwargs): ''' Converts branch length to years and plots the time tree on a time axis. Parameters ---------- tt : TreeTime object A TreeTime instance after a time tree is inferred step : int Width of sha...
Run TreeTime reconstruction. Based on the input parameters it divides the analysis into semi - independent jobs and conquers them one - by - one gradually optimizing the tree given the temporal constarints and leaf node sequences.
def run(self, root=None, infer_gtr=True, relaxed_clock=None, n_iqd = None, resolve_polytomies=True, max_iter=0, Tc=None, fixed_clock_rate=None, time_marginal=False, sequence_marginal=False, branch_length_mode='auto', vary_rate=False, use_covariation=False, **kwargs): """ ...
if branch_length mode is not explicitly set set according to empirical branch length distribution in input tree
def _set_branch_length_mode(self, branch_length_mode): ''' if branch_length mode is not explicitly set, set according to empirical branch length distribution in input tree Parameters ---------- branch_length_mode : str, 'input', 'joint', 'marginal' if the m...
Labels outlier branches that don t seem to follow a molecular clock and excludes them from subsequent molecular clock estimation and the timetree propagation.
def clock_filter(self, reroot='least-squares', n_iqd=None, plot=False): ''' Labels outlier branches that don't seem to follow a molecular clock and excludes them from subsequent molecular clock estimation and the timetree propagation. Parameters ---------- reroo...
Plot root - to - tip regression
def plot_root_to_tip(self, add_internal=False, label=True, ax=None): """ Plot root-to-tip regression Parameters ---------- add_internal : bool If true, plot inte`rnal node positions label : bool If true, label the plots ax : matplotlib axe...
Find best root and re - root the tree to the new root
def reroot(self, root='least-squares', force_positive=True, covariation=None): """ Find best root and re-root the tree to the new root Parameters ---------- root : str Which method should be used to find the best root. Available methods are: :code:`bes...
Resolve the polytomies on the tree.
def resolve_polytomies(self, merge_compressed=False): """ Resolve the polytomies on the tree. The function scans the tree, resolves polytomies if present, and re-optimizes the tree with new topology. Note that polytomies are only resolved if that would result in higher likelihoo...
Function to resolve polytomies for a given parent node. If the number of the direct decendants is less than three ( not a polytomy ) does nothing. Otherwise for each pair of nodes assess the possible LH increase which could be gained by merging the two nodes. The increase in the LH is basically the tradeoff between the...
def _poly(self, clade, merge_compressed): """ Function to resolve polytomies for a given parent node. If the number of the direct decendants is less than three (not a polytomy), does nothing. Otherwise, for each pair of nodes, assess the possible LH increase which could be gaine...
Print the total likelihood of the tree given the constrained leaves
def print_lh(self, joint=True): """ Print the total likelihood of the tree given the constrained leaves Parameters ---------- joint : bool If true, print joint LH, else print marginal LH """ try: u_lh = self.tree.unconstrained_sequence_...
Add a coalescent model to the tree and optionally optimze
def add_coalescent_model(self, Tc, **kwargs): """Add a coalescent model to the tree and optionally optimze Parameters ---------- Tc : float,str If this is a float, it will be interpreted as the inverse merger rate in molecular clock units, if its is a """...
Allow the mutation rate to vary on the tree ( relaxed molecular clock ). Changes of the mutation rates from one branch to another are penalized. In addition deviation of the mutation rate from the mean rate is penalized.
def relaxed_clock(self, slack=None, coupling=None, **kwargs): """ Allow the mutation rate to vary on the tree (relaxed molecular clock). Changes of the mutation rates from one branch to another are penalized. In addition, deviation of the mutation rate from the mean rate is penal...
Determine the node that when the tree is rooted on this node results in the best regression of temporal constraints and root to tip distances.
def _find_best_root(self, covariation=True, force_positive=True, slope=0, **kwarks): ''' Determine the node that, when the tree is rooted on this node, results in the best regression of temporal constraints and root to tip distances. Parameters ---------- infer_gtr : b...
Function that attempts to load a tree and build it from the alignment if no tree is provided.
def assure_tree(params, tmp_dir='treetime_tmp'): """ Function that attempts to load a tree and build it from the alignment if no tree is provided. """ if params.tree is None: params.tree = os.path.basename(params.aln)+'.nwk' print("No tree given: inferring tree") utils.tree_i...
parse the arguments referring to the GTR model and return a GTR structure
def create_gtr(params): """ parse the arguments referring to the GTR model and return a GTR structure """ model = params.gtr gtr_params = params.gtr_params if model == 'infer': gtr = GTR.standard('jc', alphabet='aa' if params.aa else 'nuc') else: try: kwargs = {} ...
Checks if input is VCF and reads in appropriately if it is
def read_if_vcf(params): """ Checks if input is VCF and reads in appropriately if it is """ ref = None aln = params.aln fixed_pi = None if hasattr(params, 'aln') and params.aln is not None: if any([params.aln.lower().endswith(x) for x in ['.vcf', '.vcf.gz']]): if not para...
the function implementing treetime homoplasies
def scan_homoplasies(params): """ the function implementing treetime homoplasies """ if assure_tree(params, tmp_dir='homoplasy_tmp'): return 1 gtr = create_gtr(params) ########################################################################### ### READ IN VCF ##################...
implementeing treetime tree
def timetree(params): """ implementeing treetime tree """ if params.relax is None: relaxed_clock_params = None elif params.relax==[]: relaxed_clock_params=True elif len(params.relax)==2: relaxed_clock_params={'slack':params.relax[0], 'coupling':params.relax[1]} date...
implementing treetime ancestral
def ancestral_reconstruction(params): """ implementing treetime ancestral """ # set up if assure_tree(params, tmp_dir='ancestral_tmp'): return 1 outdir = get_outdir(params, '_ancestral') basename = get_basename(params, outdir) gtr = create_gtr(params) ####################...
implementing treetime mugration
def mugration(params): """ implementing treetime mugration """ ########################################################################### ### Parse states ########################################################################### if os.path.isfile(params.states): states = pd.read_...
implementing treetime clock
def estimate_clock_model(params): """ implementing treetime clock """ if assure_tree(params, tmp_dir='clock_model_tmp'): return 1 dates = utils.parse_dates(params.dates) if len(dates)==0: return 1 outdir = get_outdir(params, '_clock') ##################################...
Assess the width of the probability distribution. This returns full - width - half - max
def calc_fwhm(distribution, is_neg_log=True): """ Assess the width of the probability distribution. This returns full-width-half-max """ if isinstance(distribution, interp1d): if is_neg_log: ymin = distribution.y.min() log_prob = dist...
Create delta function distribution.
def delta_function(cls, x_pos, weight=1., min_width=MIN_INTEGRATION_PEAK): """ Create delta function distribution. """ distribution = cls(x_pos,0.,is_log=True, min_width=min_width) distribution.weight = weight return distribution
multiplies a list of Distribution objects
def multiply(dists): ''' multiplies a list of Distribution objects ''' if not all([isinstance(k, Distribution) for k in dists]): raise NotImplementedError("Can only multiply Distribution objects") n_delta = np.sum([k.is_delta for k in dists]) min_width = np....
assign dates to nodes
def _assign_dates(self): """assign dates to nodes Returns ------- str success/error code """ if self.tree is None: self.logger("ClockTree._assign_dates: tree is not set, can't assign dates", 0) return ttconf.ERROR bad_branch_c...
function that sets precision to an ( hopfully ) reasonable guess based on the length of the sequence if not explicitly set
def _set_precision(self, precision): ''' function that sets precision to an (hopfully) reasonable guess based on the length of the sequence if not explicitly set ''' # if precision is explicitly specified, use it. if self.one_mutation: self.min_width = 10*sel...
instantiate a TreeRegression object and set its tip_value and branch_value function to defaults that are sensible for treetime instances.
def setup_TreeRegression(self, covariation=True): """instantiate a TreeRegression object and set its tip_value and branch_value function to defaults that are sensible for treetime instances. Parameters ---------- covariation : bool, optional account for phylogenetic ...
Get the conversion coefficients between the dates and the branch lengths as they are used in ML computations. The conversion formula is assumed to be length = k * numdate + b. For convenience these coefficients as well as regression parameters are stored in the dates2dist object.
def init_date_constraints(self, ancestral_inference=False, clock_rate=None, **kwarks): """ Get the conversion coefficients between the dates and the branch lengths as they are used in ML computations. The conversion formula is assumed to be 'length = k*numdate + b'. For convenience, thes...
Use the date constraints to calculate the most likely positions of unconstrained nodes.
def make_time_tree(self, time_marginal=False, clock_rate=None, **kwargs): ''' Use the date constraints to calculate the most likely positions of unconstrained nodes. Parameters ---------- time_marginal : bool If true, use marginal reconstruction for node po...
Compute the joint maximum likelihood assignment of the internal nodes positions by propagating from the tree leaves towards the root. Given the assignment of parent nodes reconstruct the maximum - likelihood positions of the child nodes by propagating from the root to the leaves. The result of this operation is the tim...
def _ml_t_joint(self): """ Compute the joint maximum likelihood assignment of the internal nodes positions by propagating from the tree leaves towards the root. Given the assignment of parent nodes, reconstruct the maximum-likelihood positions of the child nodes by propagating fr...
Return the likelihood of the data given the current branch length in the tree
def timetree_likelihood(self): ''' Return the likelihood of the data given the current branch length in the tree ''' LH = 0 for node in self.tree.find_clades(order='preorder'): # sum the likelihood contributions of all branches if node.up is None: # root node ...
Compute the marginal probability distribution of the internal nodes positions by propagating from the tree leaves towards the root. The result of this operation are the probability distributions of each internal node conditional on the constraints on all leaves of the tree which have sampling dates. The probability dis...
def _ml_t_marginal(self, assign_dates=False): """ Compute the marginal probability distribution of the internal nodes positions by propagating from the tree leaves towards the root. The result of this operation are the probability distributions of each internal node, conditional ...
This function converts the estimated time_before_present properties of all nodes to numerical dates stored in the numdate attribute. This date is further converted into a human readable date string in format %Y - %m - %d assuming the usual calendar.
def convert_dates(self): ''' This function converts the estimated "time_before_present" properties of all nodes to numerical dates stored in the "numdate" attribute. This date is further converted into a human readable date string in format %Y-%m-%d assuming the usual calendar. ...
This function sets branch length to reflect the date differences between parent and child nodes measured in years. Should only be called after: py: meth: timetree. ClockTree. convert_dates has been called.
def branch_length_to_years(self): ''' This function sets branch length to reflect the date differences between parent and child nodes measured in years. Should only be called after :py:meth:`timetree.ClockTree.convert_dates` has been called. Returns ------- None ...
return the time tree estimation of evolutionary rates +/ - one standard deviation form the ML estimate.
def calc_rate_susceptibility(self, rate_std=None, params=None): """return the time tree estimation of evolutionary rates +/- one standard deviation form the ML estimate. Returns ------- TreeTime.return_code : str success or failure """ params = params...