partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
prof2seq
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. gtr : gtr.GTR Instance of the GTR class to supply the sequence alphabet collapse_prof : bool Whether to convert the profile to the delta-function Returns ------- seq : numpy.array Sequence as numpy array of length L prof_values : numpy.array Values of the profile for the chosen sequence characters (length L) idx : numpy.array Indices chosen from profile as array of length L
treetime/seq_utils.py
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. gtr : gtr.GTR Instance of the GTR class to supply the sequence alphabet collapse_prof : bool Whether to convert the profile to the delta-function Returns ------- seq : numpy.array Sequence as numpy array of length L prof_values : numpy.array Values of the profile for the chosen sequence characters (length L) idx : numpy.array Indices chosen from profile as array of length L """ # normalize profile such that probabilities at each site sum to one if normalize: tmp_profile, pre=normalize_profile(profile, return_offset=False) else: tmp_profile = profile # sample sequence according to the probabilities in the profile # (sampling from cumulative distribution over the different states) if sample_from_prof: cumdis = tmp_profile.cumsum(axis=1).T randnum = np.random.random(size=cumdis.shape[1]) idx = np.argmax(cumdis>=randnum, axis=0) else: idx = tmp_profile.argmax(axis=1) seq = gtr.alphabet[idx] # max LH over the alphabet prof_values = tmp_profile[np.arange(tmp_profile.shape[0]), idx] return seq, prof_values, idx
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. gtr : gtr.GTR Instance of the GTR class to supply the sequence alphabet collapse_prof : bool Whether to convert the profile to the delta-function Returns ------- seq : numpy.array Sequence as numpy array of length L prof_values : numpy.array Values of the profile for the chosen sequence characters (length L) idx : numpy.array Indices chosen from profile as array of length L """ # normalize profile such that probabilities at each site sum to one if normalize: tmp_profile, pre=normalize_profile(profile, return_offset=False) else: tmp_profile = profile # sample sequence according to the probabilities in the profile # (sampling from cumulative distribution over the different states) if sample_from_prof: cumdis = tmp_profile.cumsum(axis=1).T randnum = np.random.random(size=cumdis.shape[1]) idx = np.argmax(cumdis>=randnum, axis=0) else: idx = tmp_profile.argmax(axis=1) seq = gtr.alphabet[idx] # max LH over the alphabet prof_values = tmp_profile[np.arange(tmp_profile.shape[0]), idx] return seq, prof_values, idx
[ "Convert", "profile", "to", "sequence", "and", "normalize", "profile", "across", "sites", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/seq_utils.py#L177-L224
[ "def", "prof2seq", "(", "profile", ",", "gtr", ",", "sample_from_prof", "=", "False", ",", "normalize", "=", "True", ")", ":", "# normalize profile such that probabilities at each site sum to one", "if", "normalize", ":", "tmp_profile", ",", "pre", "=", "normalize_profile", "(", "profile", ",", "return_offset", "=", "False", ")", "else", ":", "tmp_profile", "=", "profile", "# sample sequence according to the probabilities in the profile", "# (sampling from cumulative distribution over the different states)", "if", "sample_from_prof", ":", "cumdis", "=", "tmp_profile", ".", "cumsum", "(", "axis", "=", "1", ")", ".", "T", "randnum", "=", "np", ".", "random", ".", "random", "(", "size", "=", "cumdis", ".", "shape", "[", "1", "]", ")", "idx", "=", "np", ".", "argmax", "(", "cumdis", ">=", "randnum", ",", "axis", "=", "0", ")", "else", ":", "idx", "=", "tmp_profile", ".", "argmax", "(", "axis", "=", "1", ")", "seq", "=", "gtr", ".", "alphabet", "[", "idx", "]", "# max LH over the alphabet", "prof_values", "=", "tmp_profile", "[", "np", ".", "arange", "(", "tmp_profile", ".", "shape", "[", "0", "]", ")", ",", "idx", "]", "return", "seq", ",", "prof_values", ",", "idx" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
normalize_profile
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 return_offset : bool, optional return the log of the scale factor for each row Returns ------- tuple normalized profile (fresh np object) and offset (if return_offset==True)
treetime/seq_utils.py
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 return_offset : bool, optional return the log of the scale factor for each row Returns ------- tuple normalized profile (fresh np object) and offset (if return_offset==True) """ if log: tmp_prefactor = in_profile.max(axis=1) tmp_prof = np.exp(in_profile.T - tmp_prefactor).T else: tmp_prefactor = 0.0 tmp_prof = in_profile norm_vector = tmp_prof.sum(axis=1) return (np.copy(np.einsum('ai,a->ai',tmp_prof,1.0/norm_vector)), (np.log(norm_vector) + tmp_prefactor) if return_offset else None)
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 return_offset : bool, optional return the log of the scale factor for each row Returns ------- tuple normalized profile (fresh np object) and offset (if return_offset==True) """ if log: tmp_prefactor = in_profile.max(axis=1) tmp_prof = np.exp(in_profile.T - tmp_prefactor).T else: tmp_prefactor = 0.0 tmp_prof = in_profile norm_vector = tmp_prof.sum(axis=1) return (np.copy(np.einsum('ai,a->ai',tmp_prof,1.0/norm_vector)), (np.log(norm_vector) + tmp_prefactor) if return_offset else None)
[ "return", "a", "normalized", "version", "of", "a", "profile", "matrix" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/seq_utils.py#L227-L253
[ "def", "normalize_profile", "(", "in_profile", ",", "log", "=", "False", ",", "return_offset", "=", "True", ")", ":", "if", "log", ":", "tmp_prefactor", "=", "in_profile", ".", "max", "(", "axis", "=", "1", ")", "tmp_prof", "=", "np", ".", "exp", "(", "in_profile", ".", "T", "-", "tmp_prefactor", ")", ".", "T", "else", ":", "tmp_prefactor", "=", "0.0", "tmp_prof", "=", "in_profile", "norm_vector", "=", "tmp_prof", ".", "sum", "(", "axis", "=", "1", ")", "return", "(", "np", ".", "copy", "(", "np", ".", "einsum", "(", "'ai,a->ai'", ",", "tmp_prof", ",", "1.0", "/", "norm_vector", ")", ")", ",", "(", "np", ".", "log", "(", "norm_vector", ")", "+", "tmp_prefactor", ")", "if", "return_offset", "else", "None", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.logger
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 level will be shown. warn : bool Warning flag. If True, the message will be displayed regardless of its log-level.
treetime/treeanc.py
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 level will be shown. warn : bool Warning flag. If True, the message will be displayed regardless of its log-level. """ if level<self.verbose or (warn and level<=self.verbose): dt = time.time() - self.t_start outstr = '\n' if level<2 else '' outstr += format(dt, '4.2f')+'\t' outstr += level*'-' outstr += msg print(outstr, file=sys.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 level will be shown. warn : bool Warning flag. If True, the message will be displayed regardless of its log-level. """ if level<self.verbose or (warn and level<=self.verbose): dt = time.time() - self.t_start outstr = '\n' if level<2 else '' outstr += format(dt, '4.2f')+'\t' outstr += level*'-' outstr += msg print(outstr, file=sys.stdout)
[ "Print", "log", "message", "*", "msg", "*", "to", "stdout", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L130-L155
[ "def", "logger", "(", "self", ",", "msg", ",", "level", ",", "warn", "=", "False", ")", ":", "if", "level", "<", "self", ".", "verbose", "or", "(", "warn", "and", "level", "<=", "self", ".", "verbose", ")", ":", "dt", "=", "time", ".", "time", "(", ")", "-", "self", ".", "t_start", "outstr", "=", "'\\n'", "if", "level", "<", "2", "else", "''", "outstr", "+=", "format", "(", "dt", ",", "'4.2f'", ")", "+", "'\\t'", "outstr", "+=", "level", "*", "'-'", "outstr", "+=", "msg", "print", "(", "outstr", ",", "file", "=", "sys", ".", "stdout", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.gtr
Set a new GTR object Parameters ----------- value : GTR the new GTR object
treetime/treeanc.py
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 = value
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 = value
[ "Set", "a", "new", "GTR", "object" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L181-L193
[ "def", "gtr", "(", "self", ",", "value", ")", ":", "if", "not", "(", "isinstance", "(", "value", ",", "GTR", ")", "or", "isinstance", "(", "value", ",", "GTR_site_specific", ")", ")", ":", "raise", "TypeError", "(", "\" GTR instance expected\"", ")", "self", ".", "_gtr", "=", "value" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.set_gtr
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 of a standard GTR model, and is attempted to be created through :code:`GTR.standard()` interface. If a GTR instance is passed, it is set directly . **kwargs Keyword arguments to construct the GTR model. If none are passed, defaults are assumed.
treetime/treeanc.py
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 of a standard GTR model, and is attempted to be created through :code:`GTR.standard()` interface. If a GTR instance is passed, it is set directly . **kwargs Keyword arguments to construct the GTR model. If none are passed, defaults are assumed. """ if isinstance(in_gtr, str): self._gtr = GTR.standard(model=in_gtr, **kwargs) self._gtr.logger = self.logger elif isinstance(in_gtr, GTR) or isinstance(in_gtr, GTR_site_specific): self._gtr = in_gtr self._gtr.logger=self.logger else: self.logger("TreeAnc.gtr_setter: can't interpret GTR model", 1, warn=True) raise TypeError("Cannot set GTR model in TreeAnc class: GTR or " "string expected") if self._gtr.ambiguous is None: self.fill_overhangs=False
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 of a standard GTR model, and is attempted to be created through :code:`GTR.standard()` interface. If a GTR instance is passed, it is set directly . **kwargs Keyword arguments to construct the GTR model. If none are passed, defaults are assumed. """ if isinstance(in_gtr, str): self._gtr = GTR.standard(model=in_gtr, **kwargs) self._gtr.logger = self.logger elif isinstance(in_gtr, GTR) or isinstance(in_gtr, GTR_site_specific): self._gtr = in_gtr self._gtr.logger=self.logger else: self.logger("TreeAnc.gtr_setter: can't interpret GTR model", 1, warn=True) raise TypeError("Cannot set GTR model in TreeAnc class: GTR or " "string expected") if self._gtr.ambiguous is None: self.fill_overhangs=False
[ "Create", "new", "GTR", "model", "if", "needed", "and", "set", "the", "model", "as", "an", "attribute", "of", "the", "TreeAnc", "class" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L196-L228
[ "def", "set_gtr", "(", "self", ",", "in_gtr", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "in_gtr", ",", "str", ")", ":", "self", ".", "_gtr", "=", "GTR", ".", "standard", "(", "model", "=", "in_gtr", ",", "*", "*", "kwargs", ")", "self", ".", "_gtr", ".", "logger", "=", "self", ".", "logger", "elif", "isinstance", "(", "in_gtr", ",", "GTR", ")", "or", "isinstance", "(", "in_gtr", ",", "GTR_site_specific", ")", ":", "self", ".", "_gtr", "=", "in_gtr", "self", ".", "_gtr", ".", "logger", "=", "self", ".", "logger", "else", ":", "self", ".", "logger", "(", "\"TreeAnc.gtr_setter: can't interpret GTR model\"", ",", "1", ",", "warn", "=", "True", ")", "raise", "TypeError", "(", "\"Cannot set GTR model in TreeAnc class: GTR or \"", "\"string expected\"", ")", "if", "self", ".", "_gtr", ".", "ambiguous", "is", "None", ":", "self", ".", "fill_overhangs", "=", "False" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.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)
treetime/treeanc.py
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._tree = in_tree elif type(in_tree) in string_types and isfile(in_tree): try: self._tree=Phylo.read(in_tree, 'newick') except: fmt = in_tree.split('.')[-1] if fmt in ['nexus', 'nex']: self._tree=Phylo.read(in_tree, 'nexus') else: self.logger('TreeAnc: could not load tree, format needs to be nexus or newick! input was '+str(in_tree),1) self._tree = None return ttconf.ERROR else: self.logger('TreeAnc: could not load tree! input was '+str(in_tree),0) self._tree = None return ttconf.ERROR # remove all existing sequence attributes for node in self._tree.find_clades(): if hasattr(node, "sequence"): node.__delattr__("sequence") node.original_length = node.branch_length node.mutation_length = node.branch_length self.prepare_tree() return ttconf.SUCCESS
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._tree = in_tree elif type(in_tree) in string_types and isfile(in_tree): try: self._tree=Phylo.read(in_tree, 'newick') except: fmt = in_tree.split('.')[-1] if fmt in ['nexus', 'nex']: self._tree=Phylo.read(in_tree, 'nexus') else: self.logger('TreeAnc: could not load tree, format needs to be nexus or newick! input was '+str(in_tree),1) self._tree = None return ttconf.ERROR else: self.logger('TreeAnc: could not load tree! input was '+str(in_tree),0) self._tree = None return ttconf.ERROR # remove all existing sequence attributes for node in self._tree.find_clades(): if hasattr(node, "sequence"): node.__delattr__("sequence") node.original_length = node.branch_length node.mutation_length = node.branch_length self.prepare_tree() return ttconf.SUCCESS
[ "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", ")" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L244-L276
[ "def", "tree", "(", "self", ",", "in_tree", ")", ":", "from", "os", ".", "path", "import", "isfile", "if", "isinstance", "(", "in_tree", ",", "Phylo", ".", "BaseTree", ".", "Tree", ")", ":", "self", ".", "_tree", "=", "in_tree", "elif", "type", "(", "in_tree", ")", "in", "string_types", "and", "isfile", "(", "in_tree", ")", ":", "try", ":", "self", ".", "_tree", "=", "Phylo", ".", "read", "(", "in_tree", ",", "'newick'", ")", "except", ":", "fmt", "=", "in_tree", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", "if", "fmt", "in", "[", "'nexus'", ",", "'nex'", "]", ":", "self", ".", "_tree", "=", "Phylo", ".", "read", "(", "in_tree", ",", "'nexus'", ")", "else", ":", "self", ".", "logger", "(", "'TreeAnc: could not load tree, format needs to be nexus or newick! input was '", "+", "str", "(", "in_tree", ")", ",", "1", ")", "self", ".", "_tree", "=", "None", "return", "ttconf", ".", "ERROR", "else", ":", "self", ".", "logger", "(", "'TreeAnc: could not load tree! input was '", "+", "str", "(", "in_tree", ")", ",", "0", ")", "self", ".", "_tree", "=", "None", "return", "ttconf", ".", "ERROR", "# remove all existing sequence attributes", "for", "node", "in", "self", ".", "_tree", ".", "find_clades", "(", ")", ":", "if", "hasattr", "(", "node", ",", "\"sequence\"", ")", ":", "node", ".", "__delattr__", "(", "\"sequence\"", ")", "node", ".", "original_length", "=", "node", ".", "branch_length", "node", ".", "mutation_length", "=", "node", ".", "branch_length", "self", ".", "prepare_tree", "(", ")", "return", "ttconf", ".", "SUCCESS" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.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 The alignment to be read in
treetime/treeanc.py
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 The alignment to be read in """ # load alignment from file if necessary from os.path import isfile from Bio.Align import MultipleSeqAlignment self._aln = None if in_aln is None: return elif isinstance(in_aln, MultipleSeqAlignment): self._aln = in_aln elif type(in_aln) in string_types and isfile(in_aln): for fmt in ['fasta', 'phylip-relaxed', 'nexus']: try: self._aln=AlignIO.read(in_aln, fmt) break except: continue elif type(in_aln) in [defaultdict, dict]: #if is read in from VCF file self._aln = in_aln self.is_vcf = True if self._aln is None: self.logger("TreeAnc: loading alignment failed... ",1, warn=True) return ttconf.ERROR #Convert to uppercase here, rather than in _attach_sequences_to_nodes #(which used to do it through seq2array in seq_utils.py) #so that it is controlled by param convert_upper. This way for #mugration (ancestral reconstruction of non-sequences), you can #use upper- and lower case characters for discrete states! if (not self.is_vcf) and self.convert_upper: self._aln = MultipleSeqAlignment([seq.upper() for seq in self._aln]) if self.seq_len: if self.is_vcf and self.seq_len!=len(self.ref): self.logger("TreeAnc.aln: specified sequence length doesn't match reference length, ignoring sequence length.", 1, warn=True) self._seq_len = len(self.ref) else: self.logger("TreeAnc.aln: specified sequence length doesn't match alignment length. Treating difference as constant sites.", 2, warn=True) self.additional_constant_sites = max(0, self.seq_len - self.aln.get_alignment_length()) else: if self.is_vcf: self.seq_len = len(self.ref) else: self.seq_len = self.aln.get_alignment_length() # check whether the alignment is consistent with a nucleotide alignment. likely_alphabet = self._guess_alphabet() from .seq_utils import alphabets # if likely alignment is not nucleotide but the gtr alignment is, WARN if likely_alphabet=='aa' and self.gtr.n_states==len(alphabets['nuc']) and np.all(self.gtr.alphabet==alphabets['nuc']): self.logger('WARNING: small fraction of ACGT-N in alignment. Really a nucleotide alignment? if not, rerun with --aa', 1, warn=True) # conversely, warn if alignment is consistent with nucleotide but gtr has a long alphabet if likely_alphabet=='nuc' and self.gtr.n_states>10: self.logger('WARNING: almost exclusively ACGT-N in alignment. Really a protein alignment?', 1, warn=True) if hasattr(self, '_tree') and (self.tree is not None): self._attach_sequences_to_nodes() else: self.logger("TreeAnc.aln: sequences not yet attached to tree", 3, warn=True)
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 The alignment to be read in """ # load alignment from file if necessary from os.path import isfile from Bio.Align import MultipleSeqAlignment self._aln = None if in_aln is None: return elif isinstance(in_aln, MultipleSeqAlignment): self._aln = in_aln elif type(in_aln) in string_types and isfile(in_aln): for fmt in ['fasta', 'phylip-relaxed', 'nexus']: try: self._aln=AlignIO.read(in_aln, fmt) break except: continue elif type(in_aln) in [defaultdict, dict]: #if is read in from VCF file self._aln = in_aln self.is_vcf = True if self._aln is None: self.logger("TreeAnc: loading alignment failed... ",1, warn=True) return ttconf.ERROR #Convert to uppercase here, rather than in _attach_sequences_to_nodes #(which used to do it through seq2array in seq_utils.py) #so that it is controlled by param convert_upper. This way for #mugration (ancestral reconstruction of non-sequences), you can #use upper- and lower case characters for discrete states! if (not self.is_vcf) and self.convert_upper: self._aln = MultipleSeqAlignment([seq.upper() for seq in self._aln]) if self.seq_len: if self.is_vcf and self.seq_len!=len(self.ref): self.logger("TreeAnc.aln: specified sequence length doesn't match reference length, ignoring sequence length.", 1, warn=True) self._seq_len = len(self.ref) else: self.logger("TreeAnc.aln: specified sequence length doesn't match alignment length. Treating difference as constant sites.", 2, warn=True) self.additional_constant_sites = max(0, self.seq_len - self.aln.get_alignment_length()) else: if self.is_vcf: self.seq_len = len(self.ref) else: self.seq_len = self.aln.get_alignment_length() # check whether the alignment is consistent with a nucleotide alignment. likely_alphabet = self._guess_alphabet() from .seq_utils import alphabets # if likely alignment is not nucleotide but the gtr alignment is, WARN if likely_alphabet=='aa' and self.gtr.n_states==len(alphabets['nuc']) and np.all(self.gtr.alphabet==alphabets['nuc']): self.logger('WARNING: small fraction of ACGT-N in alignment. Really a nucleotide alignment? if not, rerun with --aa', 1, warn=True) # conversely, warn if alignment is consistent with nucleotide but gtr has a long alphabet if likely_alphabet=='nuc' and self.gtr.n_states>10: self.logger('WARNING: almost exclusively ACGT-N in alignment. Really a protein alignment?', 1, warn=True) if hasattr(self, '_tree') and (self.tree is not None): self._attach_sequences_to_nodes() else: self.logger("TreeAnc.aln: sequences not yet attached to tree", 3, warn=True)
[ "Reads", "in", "the", "alignment", "(", "from", "a", "dict", "MultipleSeqAlignment", "or", "file", "as", "necessary", ")", "sets", "tree", "-", "related", "parameters", "and", "attaches", "sequences", "to", "the", "tree", "nodes", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L292-L361
[ "def", "aln", "(", "self", ",", "in_aln", ")", ":", "# load alignment from file if necessary", "from", "os", ".", "path", "import", "isfile", "from", "Bio", ".", "Align", "import", "MultipleSeqAlignment", "self", ".", "_aln", "=", "None", "if", "in_aln", "is", "None", ":", "return", "elif", "isinstance", "(", "in_aln", ",", "MultipleSeqAlignment", ")", ":", "self", ".", "_aln", "=", "in_aln", "elif", "type", "(", "in_aln", ")", "in", "string_types", "and", "isfile", "(", "in_aln", ")", ":", "for", "fmt", "in", "[", "'fasta'", ",", "'phylip-relaxed'", ",", "'nexus'", "]", ":", "try", ":", "self", ".", "_aln", "=", "AlignIO", ".", "read", "(", "in_aln", ",", "fmt", ")", "break", "except", ":", "continue", "elif", "type", "(", "in_aln", ")", "in", "[", "defaultdict", ",", "dict", "]", ":", "#if is read in from VCF file", "self", ".", "_aln", "=", "in_aln", "self", ".", "is_vcf", "=", "True", "if", "self", ".", "_aln", "is", "None", ":", "self", ".", "logger", "(", "\"TreeAnc: loading alignment failed... \"", ",", "1", ",", "warn", "=", "True", ")", "return", "ttconf", ".", "ERROR", "#Convert to uppercase here, rather than in _attach_sequences_to_nodes", "#(which used to do it through seq2array in seq_utils.py)", "#so that it is controlled by param convert_upper. This way for", "#mugration (ancestral reconstruction of non-sequences), you can", "#use upper- and lower case characters for discrete states!", "if", "(", "not", "self", ".", "is_vcf", ")", "and", "self", ".", "convert_upper", ":", "self", ".", "_aln", "=", "MultipleSeqAlignment", "(", "[", "seq", ".", "upper", "(", ")", "for", "seq", "in", "self", ".", "_aln", "]", ")", "if", "self", ".", "seq_len", ":", "if", "self", ".", "is_vcf", "and", "self", ".", "seq_len", "!=", "len", "(", "self", ".", "ref", ")", ":", "self", ".", "logger", "(", "\"TreeAnc.aln: specified sequence length doesn't match reference length, ignoring sequence length.\"", ",", "1", ",", "warn", "=", "True", ")", "self", ".", "_seq_len", "=", "len", "(", "self", ".", "ref", ")", "else", ":", "self", ".", "logger", "(", "\"TreeAnc.aln: specified sequence length doesn't match alignment length. Treating difference as constant sites.\"", ",", "2", ",", "warn", "=", "True", ")", "self", ".", "additional_constant_sites", "=", "max", "(", "0", ",", "self", ".", "seq_len", "-", "self", ".", "aln", ".", "get_alignment_length", "(", ")", ")", "else", ":", "if", "self", ".", "is_vcf", ":", "self", ".", "seq_len", "=", "len", "(", "self", ".", "ref", ")", "else", ":", "self", ".", "seq_len", "=", "self", ".", "aln", ".", "get_alignment_length", "(", ")", "# check whether the alignment is consistent with a nucleotide alignment.", "likely_alphabet", "=", "self", ".", "_guess_alphabet", "(", ")", "from", ".", "seq_utils", "import", "alphabets", "# if likely alignment is not nucleotide but the gtr alignment is, WARN", "if", "likely_alphabet", "==", "'aa'", "and", "self", ".", "gtr", ".", "n_states", "==", "len", "(", "alphabets", "[", "'nuc'", "]", ")", "and", "np", ".", "all", "(", "self", ".", "gtr", ".", "alphabet", "==", "alphabets", "[", "'nuc'", "]", ")", ":", "self", ".", "logger", "(", "'WARNING: small fraction of ACGT-N in alignment. Really a nucleotide alignment? if not, rerun with --aa'", ",", "1", ",", "warn", "=", "True", ")", "# conversely, warn if alignment is consistent with nucleotide but gtr has a long alphabet", "if", "likely_alphabet", "==", "'nuc'", "and", "self", ".", "gtr", ".", "n_states", ">", "10", ":", "self", ".", "logger", "(", "'WARNING: almost exclusively ACGT-N in alignment. Really a protein alignment?'", ",", "1", ",", "warn", "=", "True", ")", "if", "hasattr", "(", "self", ",", "'_tree'", ")", "and", "(", "self", ".", "tree", "is", "not", "None", ")", ":", "self", ".", "_attach_sequences_to_nodes", "(", ")", "else", ":", "self", ".", "logger", "(", "\"TreeAnc.aln: sequences not yet attached to tree\"", ",", "3", ",", "warn", "=", "True", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.seq_len
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
treetime/treeanc.py
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 """ if (not hasattr(self, '_seq_len')) or self._seq_len is None: if L: self._seq_len = int(L) else: self.logger("TreeAnc: one_mutation and sequence length can't be reset",1)
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 """ if (not hasattr(self, '_seq_len')) or self._seq_len is None: if L: self._seq_len = int(L) else: self.logger("TreeAnc: one_mutation and sequence length can't be reset",1)
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L371-L385
[ "def", "seq_len", "(", "self", ",", "L", ")", ":", "if", "(", "not", "hasattr", "(", "self", ",", "'_seq_len'", ")", ")", "or", "self", ".", "_seq_len", "is", "None", ":", "if", "L", ":", "self", ".", "_seq_len", "=", "int", "(", "L", ")", "else", ":", "self", ".", "logger", "(", "\"TreeAnc: one_mutation and sequence length can't be reset\"", ",", "1", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._attach_sequences_to_nodes
For each node of the tree, check whether there is a sequence available in the alignment and assign this sequence as a character array
treetime/treeanc.py
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 ref dic_aln = self.aln else: # if full alignment is specified dic_aln = {k.name: seq2array(k.seq, fill_overhangs=self.fill_overhangs, ambiguous_character=self.gtr.ambiguous) for k in self.aln} # # loop over leaves and assign multiplicities of leaves (e.g. number of identical reads) for l in self.tree.get_terminals(): if l.name in self.seq_multiplicity: l.count = self.seq_multiplicity[l.name] else: l.count = 1.0 # loop over tree, and assign sequences for l in self.tree.find_clades(): if l.name in dic_aln: l.sequence= dic_aln[l.name] elif l.is_terminal(): self.logger("***WARNING: TreeAnc._attach_sequences_to_nodes: NO SEQUENCE FOR LEAF: %s" % l.name, 0, warn=True) failed_leaves += 1 l.sequence = seq2array(self.gtr.ambiguous*self.seq_len, fill_overhangs=self.fill_overhangs, ambiguous_character=self.gtr.ambiguous) if failed_leaves > self.tree.count_terminals()/3: self.logger("ERROR: At least 30\\% terminal nodes cannot be assigned with a sequence!\n", 0, warn=True) self.logger("Are you sure the alignment belongs to the tree?", 2, warn=True) break else: # could not assign sequence for internal node - is OK pass if failed_leaves: self.logger("***WARNING: TreeAnc: %d nodes don't have a matching sequence in the alignment." " POSSIBLE ERROR."%failed_leaves, 0, warn=True) # extend profile to contain additional unknown characters self.extend_profile() return self.make_reduced_alignment()
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 ref dic_aln = self.aln else: # if full alignment is specified dic_aln = {k.name: seq2array(k.seq, fill_overhangs=self.fill_overhangs, ambiguous_character=self.gtr.ambiguous) for k in self.aln} # # loop over leaves and assign multiplicities of leaves (e.g. number of identical reads) for l in self.tree.get_terminals(): if l.name in self.seq_multiplicity: l.count = self.seq_multiplicity[l.name] else: l.count = 1.0 # loop over tree, and assign sequences for l in self.tree.find_clades(): if l.name in dic_aln: l.sequence= dic_aln[l.name] elif l.is_terminal(): self.logger("***WARNING: TreeAnc._attach_sequences_to_nodes: NO SEQUENCE FOR LEAF: %s" % l.name, 0, warn=True) failed_leaves += 1 l.sequence = seq2array(self.gtr.ambiguous*self.seq_len, fill_overhangs=self.fill_overhangs, ambiguous_character=self.gtr.ambiguous) if failed_leaves > self.tree.count_terminals()/3: self.logger("ERROR: At least 30\\% terminal nodes cannot be assigned with a sequence!\n", 0, warn=True) self.logger("Are you sure the alignment belongs to the tree?", 2, warn=True) break else: # could not assign sequence for internal node - is OK pass if failed_leaves: self.logger("***WARNING: TreeAnc: %d nodes don't have a matching sequence in the alignment." " POSSIBLE ERROR."%failed_leaves, 0, warn=True) # extend profile to contain additional unknown characters self.extend_profile() return self.make_reduced_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" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L463-L508
[ "def", "_attach_sequences_to_nodes", "(", "self", ")", ":", "failed_leaves", "=", "0", "if", "self", ".", "is_vcf", ":", "# if alignment is specified as difference from ref", "dic_aln", "=", "self", ".", "aln", "else", ":", "# if full alignment is specified", "dic_aln", "=", "{", "k", ".", "name", ":", "seq2array", "(", "k", ".", "seq", ",", "fill_overhangs", "=", "self", ".", "fill_overhangs", ",", "ambiguous_character", "=", "self", ".", "gtr", ".", "ambiguous", ")", "for", "k", "in", "self", ".", "aln", "}", "#", "# loop over leaves and assign multiplicities of leaves (e.g. number of identical reads)", "for", "l", "in", "self", ".", "tree", ".", "get_terminals", "(", ")", ":", "if", "l", ".", "name", "in", "self", ".", "seq_multiplicity", ":", "l", ".", "count", "=", "self", ".", "seq_multiplicity", "[", "l", ".", "name", "]", "else", ":", "l", ".", "count", "=", "1.0", "# loop over tree, and assign sequences", "for", "l", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "l", ".", "name", "in", "dic_aln", ":", "l", ".", "sequence", "=", "dic_aln", "[", "l", ".", "name", "]", "elif", "l", ".", "is_terminal", "(", ")", ":", "self", ".", "logger", "(", "\"***WARNING: TreeAnc._attach_sequences_to_nodes: NO SEQUENCE FOR LEAF: %s\"", "%", "l", ".", "name", ",", "0", ",", "warn", "=", "True", ")", "failed_leaves", "+=", "1", "l", ".", "sequence", "=", "seq2array", "(", "self", ".", "gtr", ".", "ambiguous", "*", "self", ".", "seq_len", ",", "fill_overhangs", "=", "self", ".", "fill_overhangs", ",", "ambiguous_character", "=", "self", ".", "gtr", ".", "ambiguous", ")", "if", "failed_leaves", ">", "self", ".", "tree", ".", "count_terminals", "(", ")", "/", "3", ":", "self", ".", "logger", "(", "\"ERROR: At least 30\\\\% terminal nodes cannot be assigned with a sequence!\\n\"", ",", "0", ",", "warn", "=", "True", ")", "self", ".", "logger", "(", "\"Are you sure the alignment belongs to the tree?\"", ",", "2", ",", "warn", "=", "True", ")", "break", "else", ":", "# could not assign sequence for internal node - is OK", "pass", "if", "failed_leaves", ":", "self", ".", "logger", "(", "\"***WARNING: TreeAnc: %d nodes don't have a matching sequence in the alignment.\"", "\" POSSIBLE ERROR.\"", "%", "failed_leaves", ",", "0", ",", "warn", "=", "True", ")", "# extend profile to contain additional unknown characters", "self", ".", "extend_profile", "(", ")", "return", "self", ".", "make_reduced_alignment", "(", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.make_reduced_alignment
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. The reduced alignment and the pattern multiplicity are sufficient for the GTR calculations and allow to save memory on profile instantiation. The maps from full sequence to reduced sequence and back are also stored to allow compressing and expanding the sequences. Notes ----- full_to_reduced_sequence_map : (array) Map to reduce a sequence reduced_to_full_sequence_map : (dict) Map to restore sequence from reduced alignment multiplicity : (array) Numpy array, which stores the pattern multiplicity for each position of the reduced alignment. reduced_alignment : (2D numpy array) The reduced alignment. Shape is (N x L'), where N is number of sequences, L' - number of unique alignment patterns cseq : (array) The compressed sequence (corresponding row of the reduced alignment) attached to each node
treetime/treeanc.py
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'), and creates the reduced alignment, where only the unique patterns are present. The reduced alignment and the pattern multiplicity are sufficient for the GTR calculations and allow to save memory on profile instantiation. The maps from full sequence to reduced sequence and back are also stored to allow compressing and expanding the sequences. Notes ----- full_to_reduced_sequence_map : (array) Map to reduce a sequence reduced_to_full_sequence_map : (dict) Map to restore sequence from reduced alignment multiplicity : (array) Numpy array, which stores the pattern multiplicity for each position of the reduced alignment. reduced_alignment : (2D numpy array) The reduced alignment. Shape is (N x L'), where N is number of sequences, L' - number of unique alignment patterns cseq : (array) The compressed sequence (corresponding row of the reduced alignment) attached to each node """ self.logger("TreeAnc: making reduced alignment...", 1) # bind positions in real sequence to that of the reduced (compressed) sequence self.full_to_reduced_sequence_map = np.zeros(self.seq_len, dtype=int) # bind position in reduced sequence to the array of positions in real (expanded) sequence self.reduced_to_full_sequence_map = {} #if is a dict, want to be efficient and not iterate over a bunch of const_sites #so pre-load alignment_patterns with the location of const sites! #and get the sites that we want to iterate over only! if self.is_vcf: tmp_reduced_aln, alignment_patterns, positions = self.process_alignment_dict() seqNames = self.aln.keys() #store seqName order to put back on tree elif self.reduce_alignment: # transpose real alignment, for ease of iteration alignment_patterns = {} tmp_reduced_aln = [] # NOTE the order of tree traversal must be the same as below # for assigning the cseq attributes to the nodes. seqs = [n.sequence for n in self.tree.find_clades() if hasattr(n, 'sequence')] if len(np.unique([len(x) for x in seqs]))>1: self.logger("TreeAnc: Sequences differ in in length! ABORTING",0, warn=True) aln_transpose = None return else: aln_transpose = np.array(seqs).T positions = range(aln_transpose.shape[0]) else: self.multiplicity = np.ones(self.seq_len, dtype=float) self.full_to_reduced_sequence_map = np.arange(self.seq_len) self.reduced_to_full_sequence_map = {p:np.array([p]) for p in np.arange(self.seq_len)} for n in self.tree.find_clades(): if hasattr(n, 'sequence'): n.original_cseq = np.copy(n.sequence) n.cseq = np.copy(n.sequence) return ttconf.SUCCESS for pi in positions: if self.is_vcf: pattern = [ self.aln[k][pi] if pi in self.aln[k].keys() else self.ref[pi] for k,v in self.aln.items() ] else: pattern = aln_transpose[pi] str_pat = "".join(pattern) # if the column contains only one state and ambiguous nucleotides, replace # those with the state in other strains right away unique_letters = list(np.unique(pattern)) if hasattr(self.gtr, "ambiguous"): if len(unique_letters)==2 and self.gtr.ambiguous in unique_letters: other = [c for c in unique_letters if c!=self.gtr.ambiguous][0] str_pat = str_pat.replace(self.gtr.ambiguous, other) unique_letters = [other] # if there is a mutation in this column, give it its private pattern # this is required when sampling mutations from reconstructed profiles. # otherwise, all mutations corresponding to the same pattern will be coupled. if len(unique_letters)>1: str_pat += '_%d'%pi # if the pattern is not yet seen, if str_pat not in alignment_patterns: # bind the index in the reduced aln, index in sequence to the pattern string alignment_patterns[str_pat] = (len(tmp_reduced_aln), [pi]) # append this pattern to the reduced alignment tmp_reduced_aln.append(pattern) else: # if the pattern is already seen, append the position in the real # sequence to the reduced aln<->sequence_pos_indexes map alignment_patterns[str_pat][1].append(pi) # add constant alignment column not in the alignment. We don't know where they # are, so just add them to the end. First, determine sequence composition. if self.additional_constant_sites: character_counts = {c:np.sum(aln_transpose==c) for c in self.gtr.alphabet if c not in [self.gtr.ambiguous, '-']} total = np.sum(list(character_counts.values())) additional_columns = [(c,int(np.round(self.additional_constant_sites*n/total))) for c, n in character_counts.items()] columns_left = self.additional_constant_sites pi = len(positions) for c,n in additional_columns: if c==additional_columns[-1][0]: # make sure all additions add up to the correct number to avoid rounding n = columns_left str_pat = c*len(self.aln) pos_list = list(range(pi, pi+n)) if str_pat in alignment_patterns: alignment_patterns[str_pat][1].extend(pos_list) else: alignment_patterns[str_pat] = (len(tmp_reduced_aln), pos_list) tmp_reduced_aln.append(np.array(list(str_pat))) pi += n columns_left -= n # count how many times each column is repeated in the real alignment self.multiplicity = np.zeros(len(alignment_patterns)) for p, pos in alignment_patterns.values(): self.multiplicity[p]=len(pos) # create the reduced alignment as np array self.reduced_alignment = np.array(tmp_reduced_aln).T # create map to compress a sequence for p, pos in alignment_patterns.values(): self.full_to_reduced_sequence_map[np.array(pos)]=p # create a map to reconstruct full sequence from the reduced (compressed) sequence for p, val in alignment_patterns.items(): self.reduced_to_full_sequence_map[val[0]]=np.array(val[1], dtype=int) # assign compressed sequences to all nodes of the tree, which have sequence assigned # for dict we cannot assume this is in the same order, as it does below! # so do it explicitly # # sequences are overwritten during reconstruction and # ambiguous sites change. Keep orgininals for reference if self.is_vcf: seq_reduce_align = {n:self.reduced_alignment[i] for i, n in enumerate(seqNames)} for n in self.tree.find_clades(): if hasattr(n, 'sequence'): n.original_cseq = seq_reduce_align[n.name] n.cseq = np.copy(n.original_cseq) else: # NOTE the order of tree traversal must be the same as above to catch the # index in the reduced alignment correctly seq_count = 0 for n in self.tree.find_clades(): if hasattr(n, 'sequence'): n.original_cseq = self.reduced_alignment[seq_count] n.cseq = np.copy(n.original_cseq) seq_count+=1 self.logger("TreeAnc: constructed reduced alignment...", 1) return ttconf.SUCCESS
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'), and creates the reduced alignment, where only the unique patterns are present. The reduced alignment and the pattern multiplicity are sufficient for the GTR calculations and allow to save memory on profile instantiation. The maps from full sequence to reduced sequence and back are also stored to allow compressing and expanding the sequences. Notes ----- full_to_reduced_sequence_map : (array) Map to reduce a sequence reduced_to_full_sequence_map : (dict) Map to restore sequence from reduced alignment multiplicity : (array) Numpy array, which stores the pattern multiplicity for each position of the reduced alignment. reduced_alignment : (2D numpy array) The reduced alignment. Shape is (N x L'), where N is number of sequences, L' - number of unique alignment patterns cseq : (array) The compressed sequence (corresponding row of the reduced alignment) attached to each node """ self.logger("TreeAnc: making reduced alignment...", 1) # bind positions in real sequence to that of the reduced (compressed) sequence self.full_to_reduced_sequence_map = np.zeros(self.seq_len, dtype=int) # bind position in reduced sequence to the array of positions in real (expanded) sequence self.reduced_to_full_sequence_map = {} #if is a dict, want to be efficient and not iterate over a bunch of const_sites #so pre-load alignment_patterns with the location of const sites! #and get the sites that we want to iterate over only! if self.is_vcf: tmp_reduced_aln, alignment_patterns, positions = self.process_alignment_dict() seqNames = self.aln.keys() #store seqName order to put back on tree elif self.reduce_alignment: # transpose real alignment, for ease of iteration alignment_patterns = {} tmp_reduced_aln = [] # NOTE the order of tree traversal must be the same as below # for assigning the cseq attributes to the nodes. seqs = [n.sequence for n in self.tree.find_clades() if hasattr(n, 'sequence')] if len(np.unique([len(x) for x in seqs]))>1: self.logger("TreeAnc: Sequences differ in in length! ABORTING",0, warn=True) aln_transpose = None return else: aln_transpose = np.array(seqs).T positions = range(aln_transpose.shape[0]) else: self.multiplicity = np.ones(self.seq_len, dtype=float) self.full_to_reduced_sequence_map = np.arange(self.seq_len) self.reduced_to_full_sequence_map = {p:np.array([p]) for p in np.arange(self.seq_len)} for n in self.tree.find_clades(): if hasattr(n, 'sequence'): n.original_cseq = np.copy(n.sequence) n.cseq = np.copy(n.sequence) return ttconf.SUCCESS for pi in positions: if self.is_vcf: pattern = [ self.aln[k][pi] if pi in self.aln[k].keys() else self.ref[pi] for k,v in self.aln.items() ] else: pattern = aln_transpose[pi] str_pat = "".join(pattern) # if the column contains only one state and ambiguous nucleotides, replace # those with the state in other strains right away unique_letters = list(np.unique(pattern)) if hasattr(self.gtr, "ambiguous"): if len(unique_letters)==2 and self.gtr.ambiguous in unique_letters: other = [c for c in unique_letters if c!=self.gtr.ambiguous][0] str_pat = str_pat.replace(self.gtr.ambiguous, other) unique_letters = [other] # if there is a mutation in this column, give it its private pattern # this is required when sampling mutations from reconstructed profiles. # otherwise, all mutations corresponding to the same pattern will be coupled. if len(unique_letters)>1: str_pat += '_%d'%pi # if the pattern is not yet seen, if str_pat not in alignment_patterns: # bind the index in the reduced aln, index in sequence to the pattern string alignment_patterns[str_pat] = (len(tmp_reduced_aln), [pi]) # append this pattern to the reduced alignment tmp_reduced_aln.append(pattern) else: # if the pattern is already seen, append the position in the real # sequence to the reduced aln<->sequence_pos_indexes map alignment_patterns[str_pat][1].append(pi) # add constant alignment column not in the alignment. We don't know where they # are, so just add them to the end. First, determine sequence composition. if self.additional_constant_sites: character_counts = {c:np.sum(aln_transpose==c) for c in self.gtr.alphabet if c not in [self.gtr.ambiguous, '-']} total = np.sum(list(character_counts.values())) additional_columns = [(c,int(np.round(self.additional_constant_sites*n/total))) for c, n in character_counts.items()] columns_left = self.additional_constant_sites pi = len(positions) for c,n in additional_columns: if c==additional_columns[-1][0]: # make sure all additions add up to the correct number to avoid rounding n = columns_left str_pat = c*len(self.aln) pos_list = list(range(pi, pi+n)) if str_pat in alignment_patterns: alignment_patterns[str_pat][1].extend(pos_list) else: alignment_patterns[str_pat] = (len(tmp_reduced_aln), pos_list) tmp_reduced_aln.append(np.array(list(str_pat))) pi += n columns_left -= n # count how many times each column is repeated in the real alignment self.multiplicity = np.zeros(len(alignment_patterns)) for p, pos in alignment_patterns.values(): self.multiplicity[p]=len(pos) # create the reduced alignment as np array self.reduced_alignment = np.array(tmp_reduced_aln).T # create map to compress a sequence for p, pos in alignment_patterns.values(): self.full_to_reduced_sequence_map[np.array(pos)]=p # create a map to reconstruct full sequence from the reduced (compressed) sequence for p, val in alignment_patterns.items(): self.reduced_to_full_sequence_map[val[0]]=np.array(val[1], dtype=int) # assign compressed sequences to all nodes of the tree, which have sequence assigned # for dict we cannot assume this is in the same order, as it does below! # so do it explicitly # # sequences are overwritten during reconstruction and # ambiguous sites change. Keep orgininals for reference if self.is_vcf: seq_reduce_align = {n:self.reduced_alignment[i] for i, n in enumerate(seqNames)} for n in self.tree.find_clades(): if hasattr(n, 'sequence'): n.original_cseq = seq_reduce_align[n.name] n.cseq = np.copy(n.original_cseq) else: # NOTE the order of tree traversal must be the same as above to catch the # index in the reduced alignment correctly seq_count = 0 for n in self.tree.find_clades(): if hasattr(n, 'sequence'): n.original_cseq = self.reduced_alignment[seq_count] n.cseq = np.copy(n.original_cseq) seq_count+=1 self.logger("TreeAnc: constructed reduced alignment...", 1) return ttconf.SUCCESS
[ "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", ".", "The", "reduced", "alignment", "and", "the", "pattern", "multiplicity", "are", "sufficient", "for", "the", "GTR", "calculations", "and", "allow", "to", "save", "memory", "on", "profile", "instantiation", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L511-L681
[ "def", "make_reduced_alignment", "(", "self", ")", ":", "self", ".", "logger", "(", "\"TreeAnc: making reduced alignment...\"", ",", "1", ")", "# bind positions in real sequence to that of the reduced (compressed) sequence", "self", ".", "full_to_reduced_sequence_map", "=", "np", ".", "zeros", "(", "self", ".", "seq_len", ",", "dtype", "=", "int", ")", "# bind position in reduced sequence to the array of positions in real (expanded) sequence", "self", ".", "reduced_to_full_sequence_map", "=", "{", "}", "#if is a dict, want to be efficient and not iterate over a bunch of const_sites", "#so pre-load alignment_patterns with the location of const sites!", "#and get the sites that we want to iterate over only!", "if", "self", ".", "is_vcf", ":", "tmp_reduced_aln", ",", "alignment_patterns", ",", "positions", "=", "self", ".", "process_alignment_dict", "(", ")", "seqNames", "=", "self", ".", "aln", ".", "keys", "(", ")", "#store seqName order to put back on tree", "elif", "self", ".", "reduce_alignment", ":", "# transpose real alignment, for ease of iteration", "alignment_patterns", "=", "{", "}", "tmp_reduced_aln", "=", "[", "]", "# NOTE the order of tree traversal must be the same as below", "# for assigning the cseq attributes to the nodes.", "seqs", "=", "[", "n", ".", "sequence", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", "if", "hasattr", "(", "n", ",", "'sequence'", ")", "]", "if", "len", "(", "np", ".", "unique", "(", "[", "len", "(", "x", ")", "for", "x", "in", "seqs", "]", ")", ")", ">", "1", ":", "self", ".", "logger", "(", "\"TreeAnc: Sequences differ in in length! ABORTING\"", ",", "0", ",", "warn", "=", "True", ")", "aln_transpose", "=", "None", "return", "else", ":", "aln_transpose", "=", "np", ".", "array", "(", "seqs", ")", ".", "T", "positions", "=", "range", "(", "aln_transpose", ".", "shape", "[", "0", "]", ")", "else", ":", "self", ".", "multiplicity", "=", "np", ".", "ones", "(", "self", ".", "seq_len", ",", "dtype", "=", "float", ")", "self", ".", "full_to_reduced_sequence_map", "=", "np", ".", "arange", "(", "self", ".", "seq_len", ")", "self", ".", "reduced_to_full_sequence_map", "=", "{", "p", ":", "np", ".", "array", "(", "[", "p", "]", ")", "for", "p", "in", "np", ".", "arange", "(", "self", ".", "seq_len", ")", "}", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "hasattr", "(", "n", ",", "'sequence'", ")", ":", "n", ".", "original_cseq", "=", "np", ".", "copy", "(", "n", ".", "sequence", ")", "n", ".", "cseq", "=", "np", ".", "copy", "(", "n", ".", "sequence", ")", "return", "ttconf", ".", "SUCCESS", "for", "pi", "in", "positions", ":", "if", "self", ".", "is_vcf", ":", "pattern", "=", "[", "self", ".", "aln", "[", "k", "]", "[", "pi", "]", "if", "pi", "in", "self", ".", "aln", "[", "k", "]", ".", "keys", "(", ")", "else", "self", ".", "ref", "[", "pi", "]", "for", "k", ",", "v", "in", "self", ".", "aln", ".", "items", "(", ")", "]", "else", ":", "pattern", "=", "aln_transpose", "[", "pi", "]", "str_pat", "=", "\"\"", ".", "join", "(", "pattern", ")", "# if the column contains only one state and ambiguous nucleotides, replace", "# those with the state in other strains right away", "unique_letters", "=", "list", "(", "np", ".", "unique", "(", "pattern", ")", ")", "if", "hasattr", "(", "self", ".", "gtr", ",", "\"ambiguous\"", ")", ":", "if", "len", "(", "unique_letters", ")", "==", "2", "and", "self", ".", "gtr", ".", "ambiguous", "in", "unique_letters", ":", "other", "=", "[", "c", "for", "c", "in", "unique_letters", "if", "c", "!=", "self", ".", "gtr", ".", "ambiguous", "]", "[", "0", "]", "str_pat", "=", "str_pat", ".", "replace", "(", "self", ".", "gtr", ".", "ambiguous", ",", "other", ")", "unique_letters", "=", "[", "other", "]", "# if there is a mutation in this column, give it its private pattern", "# this is required when sampling mutations from reconstructed profiles.", "# otherwise, all mutations corresponding to the same pattern will be coupled.", "if", "len", "(", "unique_letters", ")", ">", "1", ":", "str_pat", "+=", "'_%d'", "%", "pi", "# if the pattern is not yet seen,", "if", "str_pat", "not", "in", "alignment_patterns", ":", "# bind the index in the reduced aln, index in sequence to the pattern string", "alignment_patterns", "[", "str_pat", "]", "=", "(", "len", "(", "tmp_reduced_aln", ")", ",", "[", "pi", "]", ")", "# append this pattern to the reduced alignment", "tmp_reduced_aln", ".", "append", "(", "pattern", ")", "else", ":", "# if the pattern is already seen, append the position in the real", "# sequence to the reduced aln<->sequence_pos_indexes map", "alignment_patterns", "[", "str_pat", "]", "[", "1", "]", ".", "append", "(", "pi", ")", "# add constant alignment column not in the alignment. We don't know where they", "# are, so just add them to the end. First, determine sequence composition.", "if", "self", ".", "additional_constant_sites", ":", "character_counts", "=", "{", "c", ":", "np", ".", "sum", "(", "aln_transpose", "==", "c", ")", "for", "c", "in", "self", ".", "gtr", ".", "alphabet", "if", "c", "not", "in", "[", "self", ".", "gtr", ".", "ambiguous", ",", "'-'", "]", "}", "total", "=", "np", ".", "sum", "(", "list", "(", "character_counts", ".", "values", "(", ")", ")", ")", "additional_columns", "=", "[", "(", "c", ",", "int", "(", "np", ".", "round", "(", "self", ".", "additional_constant_sites", "*", "n", "/", "total", ")", ")", ")", "for", "c", ",", "n", "in", "character_counts", ".", "items", "(", ")", "]", "columns_left", "=", "self", ".", "additional_constant_sites", "pi", "=", "len", "(", "positions", ")", "for", "c", ",", "n", "in", "additional_columns", ":", "if", "c", "==", "additional_columns", "[", "-", "1", "]", "[", "0", "]", ":", "# make sure all additions add up to the correct number to avoid rounding", "n", "=", "columns_left", "str_pat", "=", "c", "*", "len", "(", "self", ".", "aln", ")", "pos_list", "=", "list", "(", "range", "(", "pi", ",", "pi", "+", "n", ")", ")", "if", "str_pat", "in", "alignment_patterns", ":", "alignment_patterns", "[", "str_pat", "]", "[", "1", "]", ".", "extend", "(", "pos_list", ")", "else", ":", "alignment_patterns", "[", "str_pat", "]", "=", "(", "len", "(", "tmp_reduced_aln", ")", ",", "pos_list", ")", "tmp_reduced_aln", ".", "append", "(", "np", ".", "array", "(", "list", "(", "str_pat", ")", ")", ")", "pi", "+=", "n", "columns_left", "-=", "n", "# count how many times each column is repeated in the real alignment", "self", ".", "multiplicity", "=", "np", ".", "zeros", "(", "len", "(", "alignment_patterns", ")", ")", "for", "p", ",", "pos", "in", "alignment_patterns", ".", "values", "(", ")", ":", "self", ".", "multiplicity", "[", "p", "]", "=", "len", "(", "pos", ")", "# create the reduced alignment as np array", "self", ".", "reduced_alignment", "=", "np", ".", "array", "(", "tmp_reduced_aln", ")", ".", "T", "# create map to compress a sequence", "for", "p", ",", "pos", "in", "alignment_patterns", ".", "values", "(", ")", ":", "self", ".", "full_to_reduced_sequence_map", "[", "np", ".", "array", "(", "pos", ")", "]", "=", "p", "# create a map to reconstruct full sequence from the reduced (compressed) sequence", "for", "p", ",", "val", "in", "alignment_patterns", ".", "items", "(", ")", ":", "self", ".", "reduced_to_full_sequence_map", "[", "val", "[", "0", "]", "]", "=", "np", ".", "array", "(", "val", "[", "1", "]", ",", "dtype", "=", "int", ")", "# assign compressed sequences to all nodes of the tree, which have sequence assigned", "# for dict we cannot assume this is in the same order, as it does below!", "# so do it explicitly", "#", "# sequences are overwritten during reconstruction and", "# ambiguous sites change. Keep orgininals for reference", "if", "self", ".", "is_vcf", ":", "seq_reduce_align", "=", "{", "n", ":", "self", ".", "reduced_alignment", "[", "i", "]", "for", "i", ",", "n", "in", "enumerate", "(", "seqNames", ")", "}", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "hasattr", "(", "n", ",", "'sequence'", ")", ":", "n", ".", "original_cseq", "=", "seq_reduce_align", "[", "n", ".", "name", "]", "n", ".", "cseq", "=", "np", ".", "copy", "(", "n", ".", "original_cseq", ")", "else", ":", "# NOTE the order of tree traversal must be the same as above to catch the", "# index in the reduced alignment correctly", "seq_count", "=", "0", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "hasattr", "(", "n", ",", "'sequence'", ")", ":", "n", ".", "original_cseq", "=", "self", ".", "reduced_alignment", "[", "seq_count", "]", "n", ".", "cseq", "=", "np", ".", "copy", "(", "n", ".", "original_cseq", ")", "seq_count", "+=", "1", "self", ".", "logger", "(", "\"TreeAnc: constructed reduced alignment...\"", ",", "1", ")", "return", "ttconf", ".", "SUCCESS" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.process_alignment_dict
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 assigns ------- - self.nonref_positions: at least one sequence is different from ref Returns ------- reduced_alignment_const reduced alignment accounting for non-variable postitions alignment_patterns_const dict pattern -> (pos in reduced alignment, list of pos in full alignment) ariable_positions list of variable positions needed to construct remaining
treetime/treeanc.py
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 ambiguous sites assigns ------- - self.nonref_positions: at least one sequence is different from ref Returns ------- reduced_alignment_const reduced alignment accounting for non-variable postitions alignment_patterns_const dict pattern -> (pos in reduced alignment, list of pos in full alignment) ariable_positions list of variable positions needed to construct remaining """ # number of sequences in alignment nseq = len(self.aln) inv_map = defaultdict(list) for k,v in self.aln.items(): for pos, bs in v.items(): inv_map[pos].append(bs) self.nonref_positions = np.sort(list(inv_map.keys())) self.inferred_const_sites = [] ambiguous_char = self.gtr.ambiguous nonref_const = [] nonref_alleles = [] ambiguous_const = [] variable_pos = [] for pos, bs in inv_map.items(): #loop over positions and patterns bases = "".join(np.unique(bs)) if len(bs) == nseq: if (len(bases)<=2 and ambiguous_char in bases) or len(bases)==1: # all sequences different from reference, but only one state # (other than ambiguous_char) in column nonref_const.append(pos) nonref_alleles.append(bases.replace(ambiguous_char, '')) if ambiguous_char in bases: #keep track of sites 'made constant' self.inferred_const_sites.append(pos) else: # at least two non-reference alleles variable_pos.append(pos) else: # not every sequence different from reference if bases==ambiguous_char: ambiguous_const.append(pos) self.inferred_const_sites.append(pos) #keep track of sites 'made constant' else: # at least one non ambiguous non-reference allele not in # every sequence variable_pos.append(pos) refMod = np.array(list(self.ref)) # place constant non reference positions by their respective allele refMod[nonref_const] = nonref_alleles # mask variable positions states = self.gtr.alphabet # maybe states = np.unique(refMod) refMod[variable_pos] = '.' # for each base in the gtr, make constant alignment pattern and # assign it to all const positions in the modified reference sequence reduced_alignment_const = [] alignment_patterns_const = {} for base in states: p = base*nseq pos = list(np.where(refMod==base)[0]) #if the alignment doesn't have a const site of this base, don't add! (ex: no '----' site!) if len(pos): alignment_patterns_const[p] = [len(reduced_alignment_const), pos] reduced_alignment_const.append(list(p)) return reduced_alignment_const, alignment_patterns_const, variable_pos
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 ambiguous sites assigns ------- - self.nonref_positions: at least one sequence is different from ref Returns ------- reduced_alignment_const reduced alignment accounting for non-variable postitions alignment_patterns_const dict pattern -> (pos in reduced alignment, list of pos in full alignment) ariable_positions list of variable positions needed to construct remaining """ # number of sequences in alignment nseq = len(self.aln) inv_map = defaultdict(list) for k,v in self.aln.items(): for pos, bs in v.items(): inv_map[pos].append(bs) self.nonref_positions = np.sort(list(inv_map.keys())) self.inferred_const_sites = [] ambiguous_char = self.gtr.ambiguous nonref_const = [] nonref_alleles = [] ambiguous_const = [] variable_pos = [] for pos, bs in inv_map.items(): #loop over positions and patterns bases = "".join(np.unique(bs)) if len(bs) == nseq: if (len(bases)<=2 and ambiguous_char in bases) or len(bases)==1: # all sequences different from reference, but only one state # (other than ambiguous_char) in column nonref_const.append(pos) nonref_alleles.append(bases.replace(ambiguous_char, '')) if ambiguous_char in bases: #keep track of sites 'made constant' self.inferred_const_sites.append(pos) else: # at least two non-reference alleles variable_pos.append(pos) else: # not every sequence different from reference if bases==ambiguous_char: ambiguous_const.append(pos) self.inferred_const_sites.append(pos) #keep track of sites 'made constant' else: # at least one non ambiguous non-reference allele not in # every sequence variable_pos.append(pos) refMod = np.array(list(self.ref)) # place constant non reference positions by their respective allele refMod[nonref_const] = nonref_alleles # mask variable positions states = self.gtr.alphabet # maybe states = np.unique(refMod) refMod[variable_pos] = '.' # for each base in the gtr, make constant alignment pattern and # assign it to all const positions in the modified reference sequence reduced_alignment_const = [] alignment_patterns_const = {} for base in states: p = base*nseq pos = list(np.where(refMod==base)[0]) #if the alignment doesn't have a const site of this base, don't add! (ex: no '----' site!) if len(pos): alignment_patterns_const[p] = [len(reduced_alignment_const), pos] reduced_alignment_const.append(list(p)) return reduced_alignment_const, alignment_patterns_const, variable_pos
[ "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" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L684-L768
[ "def", "process_alignment_dict", "(", "self", ")", ":", "# number of sequences in alignment", "nseq", "=", "len", "(", "self", ".", "aln", ")", "inv_map", "=", "defaultdict", "(", "list", ")", "for", "k", ",", "v", "in", "self", ".", "aln", ".", "items", "(", ")", ":", "for", "pos", ",", "bs", "in", "v", ".", "items", "(", ")", ":", "inv_map", "[", "pos", "]", ".", "append", "(", "bs", ")", "self", ".", "nonref_positions", "=", "np", ".", "sort", "(", "list", "(", "inv_map", ".", "keys", "(", ")", ")", ")", "self", ".", "inferred_const_sites", "=", "[", "]", "ambiguous_char", "=", "self", ".", "gtr", ".", "ambiguous", "nonref_const", "=", "[", "]", "nonref_alleles", "=", "[", "]", "ambiguous_const", "=", "[", "]", "variable_pos", "=", "[", "]", "for", "pos", ",", "bs", "in", "inv_map", ".", "items", "(", ")", ":", "#loop over positions and patterns", "bases", "=", "\"\"", ".", "join", "(", "np", ".", "unique", "(", "bs", ")", ")", "if", "len", "(", "bs", ")", "==", "nseq", ":", "if", "(", "len", "(", "bases", ")", "<=", "2", "and", "ambiguous_char", "in", "bases", ")", "or", "len", "(", "bases", ")", "==", "1", ":", "# all sequences different from reference, but only one state", "# (other than ambiguous_char) in column", "nonref_const", ".", "append", "(", "pos", ")", "nonref_alleles", ".", "append", "(", "bases", ".", "replace", "(", "ambiguous_char", ",", "''", ")", ")", "if", "ambiguous_char", "in", "bases", ":", "#keep track of sites 'made constant'", "self", ".", "inferred_const_sites", ".", "append", "(", "pos", ")", "else", ":", "# at least two non-reference alleles", "variable_pos", ".", "append", "(", "pos", ")", "else", ":", "# not every sequence different from reference", "if", "bases", "==", "ambiguous_char", ":", "ambiguous_const", ".", "append", "(", "pos", ")", "self", ".", "inferred_const_sites", ".", "append", "(", "pos", ")", "#keep track of sites 'made constant'", "else", ":", "# at least one non ambiguous non-reference allele not in", "# every sequence", "variable_pos", ".", "append", "(", "pos", ")", "refMod", "=", "np", ".", "array", "(", "list", "(", "self", ".", "ref", ")", ")", "# place constant non reference positions by their respective allele", "refMod", "[", "nonref_const", "]", "=", "nonref_alleles", "# mask variable positions", "states", "=", "self", ".", "gtr", ".", "alphabet", "# maybe states = np.unique(refMod)", "refMod", "[", "variable_pos", "]", "=", "'.'", "# for each base in the gtr, make constant alignment pattern and", "# assign it to all const positions in the modified reference sequence", "reduced_alignment_const", "=", "[", "]", "alignment_patterns_const", "=", "{", "}", "for", "base", "in", "states", ":", "p", "=", "base", "*", "nseq", "pos", "=", "list", "(", "np", ".", "where", "(", "refMod", "==", "base", ")", "[", "0", "]", ")", "#if the alignment doesn't have a const site of this base, don't add! (ex: no '----' site!)", "if", "len", "(", "pos", ")", ":", "alignment_patterns_const", "[", "p", "]", "=", "[", "len", "(", "reduced_alignment_const", ")", ",", "pos", "]", "reduced_alignment_const", ".", "append", "(", "list", "(", "p", ")", ")", "return", "reduced_alignment_const", ",", "alignment_patterns_const", ",", "variable_pos" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.prepare_tree
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.
treetime/treeanc.py
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.mutation_length = self.tree.root.branch_length self.tree.root.mutations = [] self.tree.ladderize() self._prepare_nodes() self._leaves_lookup = {node.name:node for node in self.tree.get_terminals()}
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.mutation_length = self.tree.root.branch_length self.tree.root.mutations = [] self.tree.ladderize() self._prepare_nodes() self._leaves_lookup = {node.name:node for node in self.tree.get_terminals()}
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L771-L782
[ "def", "prepare_tree", "(", "self", ")", ":", "self", ".", "tree", ".", "root", ".", "branch_length", "=", "0.001", "self", ".", "tree", ".", "root", ".", "mutation_length", "=", "self", ".", "tree", ".", "root", ".", "branch_length", "self", ".", "tree", ".", "root", ".", "mutations", "=", "[", "]", "self", ".", "tree", ".", "ladderize", "(", ")", "self", ".", "_prepare_nodes", "(", ")", "self", ".", "_leaves_lookup", "=", "{", "node", ".", "name", ":", "node", "for", "node", "in", "self", ".", "tree", ".", "get_terminals", "(", ")", "}" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._prepare_nodes
Set auxilliary parameters to every node of the tree.
treetime/treeanc.py
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.get_nonterminals(order='preorder'): # parents first internal_node_count+=1 if clade.name is None: clade.name = "NODE_" + format(self._internal_node_count, '07d') self._internal_node_count += 1 for c in clade.clades: if c.is_terminal(): c.bad_branch = c.bad_branch if hasattr(c, 'bad_branch') else False c.up = clade for clade in self.tree.get_nonterminals(order='postorder'): # parents first clade.bad_branch = all([c.bad_branch for c in clade]) self._calc_dist2root() self._internal_node_count = max(internal_node_count, self._internal_node_count)
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.get_nonterminals(order='preorder'): # parents first internal_node_count+=1 if clade.name is None: clade.name = "NODE_" + format(self._internal_node_count, '07d') self._internal_node_count += 1 for c in clade.clades: if c.is_terminal(): c.bad_branch = c.bad_branch if hasattr(c, 'bad_branch') else False c.up = clade for clade in self.tree.get_nonterminals(order='postorder'): # parents first clade.bad_branch = all([c.bad_branch for c in clade]) self._calc_dist2root() self._internal_node_count = max(internal_node_count, self._internal_node_count)
[ "Set", "auxilliary", "parameters", "to", "every", "node", "of", "the", "tree", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L785-L806
[ "def", "_prepare_nodes", "(", "self", ")", ":", "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", ".", "get_nonterminals", "(", "order", "=", "'preorder'", ")", ":", "# parents first", "internal_node_count", "+=", "1", "if", "clade", ".", "name", "is", "None", ":", "clade", ".", "name", "=", "\"NODE_\"", "+", "format", "(", "self", ".", "_internal_node_count", ",", "'07d'", ")", "self", ".", "_internal_node_count", "+=", "1", "for", "c", "in", "clade", ".", "clades", ":", "if", "c", ".", "is_terminal", "(", ")", ":", "c", ".", "bad_branch", "=", "c", ".", "bad_branch", "if", "hasattr", "(", "c", ",", "'bad_branch'", ")", "else", "False", "c", ".", "up", "=", "clade", "for", "clade", "in", "self", ".", "tree", ".", "get_nonterminals", "(", "order", "=", "'postorder'", ")", ":", "# parents first", "clade", ".", "bad_branch", "=", "all", "(", "[", "c", ".", "bad_branch", "for", "c", "in", "clade", "]", ")", "self", ".", "_calc_dist2root", "(", ")", "self", ".", "_internal_node_count", "=", "max", "(", "internal_node_count", ",", "self", ".", "_internal_node_count", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._calc_dist2root
For each node in the tree, set its root-to-node distance as dist2root attribute
treetime/treeanc.py
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: if not hasattr(c, 'mutation_length'): c.mutation_length=c.branch_length c.dist2root = c.up.dist2root + c.mutation_length
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: if not hasattr(c, 'mutation_length'): c.mutation_length=c.branch_length c.dist2root = c.up.dist2root + c.mutation_length
[ "For", "each", "node", "in", "the", "tree", "set", "its", "root", "-", "to", "-", "node", "distance", "as", "dist2root", "attribute" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L809-L819
[ "def", "_calc_dist2root", "(", "self", ")", ":", "self", ".", "tree", ".", "root", ".", "dist2root", "=", "0.0", "for", "clade", "in", "self", ".", "tree", ".", "get_nonterminals", "(", "order", "=", "'preorder'", ")", ":", "# parents first", "for", "c", "in", "clade", ".", "clades", ":", "if", "not", "hasattr", "(", "c", ",", "'mutation_length'", ")", ":", "c", ".", "mutation_length", "=", "c", ".", "branch_length", "c", ".", "dist2root", "=", "c", ".", "up", ".", "dist2root", "+", "c", ".", "mutation_length" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.infer_gtr
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 statistics, the relative state transition probabilities are inferred, and the transition matrix is computed. The result is used to construct the new GTR model of type 'custom'. The model is assigned to the TreeAnc and is used in subsequent analysis. Parameters ----------- print_raw : bool If True, print the inferred GTR model marginal : bool If True, use marginal sequence reconstruction normalized_rate : bool If True, sets the mutation rate prefactor to 1.0. fixed_pi : np.array Provide the equilibrium character concentrations. If None is passed, the concentrations will be inferred from the alignment. pc: float Number of pseudo counts to use in gtr inference Returns ------- gtr : GTR The inferred GTR model
treetime/treeanc.py
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 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 statistics, the relative state transition probabilities are inferred, and the transition matrix is computed. The result is used to construct the new GTR model of type 'custom'. The model is assigned to the TreeAnc and is used in subsequent analysis. Parameters ----------- print_raw : bool If True, print the inferred GTR model marginal : bool If True, use marginal sequence reconstruction normalized_rate : bool If True, sets the mutation rate prefactor to 1.0. fixed_pi : np.array Provide the equilibrium character concentrations. If None is passed, the concentrations will be inferred from the alignment. pc: float Number of pseudo counts to use in gtr inference Returns ------- gtr : GTR The inferred GTR model """ # decide which type of the Maximum-likelihood reconstruction use # (marginal) or (joint) if marginal: _ml_anc = self._ml_anc_marginal else: _ml_anc = self._ml_anc_joint self.logger("TreeAnc.infer_gtr: inferring the GTR model from the tree...", 1) if (self.tree is None) or (self.aln is None): self.logger("TreeAnc.infer_gtr: ERROR, alignment or tree are missing", 0) return ttconf.ERROR _ml_anc(final=True, **kwargs) # call one of the reconstruction types alpha = list(self.gtr.alphabet) n=len(alpha) # matrix of mutations n_{ij}: i = derived state, j=ancestral state nij = np.zeros((n,n)) Ti = np.zeros(n) self.logger("TreeAnc.infer_gtr: counting mutations...", 2) for node in self.tree.find_clades(): if hasattr(node,'mutations'): for a,pos, d in node.mutations: i,j = alpha.index(d), alpha.index(a) nij[i,j]+=1 Ti[j] += 0.5*self._branch_length_to_gtr(node) Ti[i] -= 0.5*self._branch_length_to_gtr(node) for ni,nuc in enumerate(node.cseq): i = alpha.index(nuc) Ti[i] += self._branch_length_to_gtr(node)*self.multiplicity[ni] self.logger("TreeAnc.infer_gtr: counting mutations...done", 3) if print_raw: print('alphabet:',alpha) print('n_ij:', nij, nij.sum()) print('T_i:', Ti, Ti.sum()) root_state = np.array([np.sum((self.tree.root.cseq==nuc)*self.multiplicity) for nuc in alpha]) self._gtr = GTR.infer(nij, Ti, root_state, fixed_pi=fixed_pi, pc=pc, alphabet=self.gtr.alphabet, logger=self.logger, prof_map = self.gtr.profile_map) if normalized_rate: self.logger("TreeAnc.infer_gtr: setting overall rate to 1.0...", 2) self._gtr.mu=1.0 return self._gtr
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 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 statistics, the relative state transition probabilities are inferred, and the transition matrix is computed. The result is used to construct the new GTR model of type 'custom'. The model is assigned to the TreeAnc and is used in subsequent analysis. Parameters ----------- print_raw : bool If True, print the inferred GTR model marginal : bool If True, use marginal sequence reconstruction normalized_rate : bool If True, sets the mutation rate prefactor to 1.0. fixed_pi : np.array Provide the equilibrium character concentrations. If None is passed, the concentrations will be inferred from the alignment. pc: float Number of pseudo counts to use in gtr inference Returns ------- gtr : GTR The inferred GTR model """ # decide which type of the Maximum-likelihood reconstruction use # (marginal) or (joint) if marginal: _ml_anc = self._ml_anc_marginal else: _ml_anc = self._ml_anc_joint self.logger("TreeAnc.infer_gtr: inferring the GTR model from the tree...", 1) if (self.tree is None) or (self.aln is None): self.logger("TreeAnc.infer_gtr: ERROR, alignment or tree are missing", 0) return ttconf.ERROR _ml_anc(final=True, **kwargs) # call one of the reconstruction types alpha = list(self.gtr.alphabet) n=len(alpha) # matrix of mutations n_{ij}: i = derived state, j=ancestral state nij = np.zeros((n,n)) Ti = np.zeros(n) self.logger("TreeAnc.infer_gtr: counting mutations...", 2) for node in self.tree.find_clades(): if hasattr(node,'mutations'): for a,pos, d in node.mutations: i,j = alpha.index(d), alpha.index(a) nij[i,j]+=1 Ti[j] += 0.5*self._branch_length_to_gtr(node) Ti[i] -= 0.5*self._branch_length_to_gtr(node) for ni,nuc in enumerate(node.cseq): i = alpha.index(nuc) Ti[i] += self._branch_length_to_gtr(node)*self.multiplicity[ni] self.logger("TreeAnc.infer_gtr: counting mutations...done", 3) if print_raw: print('alphabet:',alpha) print('n_ij:', nij, nij.sum()) print('T_i:', Ti, Ti.sum()) root_state = np.array([np.sum((self.tree.root.cseq==nuc)*self.multiplicity) for nuc in alpha]) self._gtr = GTR.infer(nij, Ti, root_state, fixed_pi=fixed_pi, pc=pc, alphabet=self.gtr.alphabet, logger=self.logger, prof_map = self.gtr.profile_map) if normalized_rate: self.logger("TreeAnc.infer_gtr: setting overall rate to 1.0...", 2) self._gtr.mu=1.0 return self._gtr
[ "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", "statistics", "the", "relative", "state", "transition", "probabilities", "are", "inferred", "and", "the", "transition", "matrix", "is", "computed", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L827-L910
[ "def", "infer_gtr", "(", "self", ",", "print_raw", "=", "False", ",", "marginal", "=", "False", ",", "normalized_rate", "=", "True", ",", "fixed_pi", "=", "None", ",", "pc", "=", "5.0", ",", "*", "*", "kwargs", ")", ":", "# decide which type of the Maximum-likelihood reconstruction use", "# (marginal) or (joint)", "if", "marginal", ":", "_ml_anc", "=", "self", ".", "_ml_anc_marginal", "else", ":", "_ml_anc", "=", "self", ".", "_ml_anc_joint", "self", ".", "logger", "(", "\"TreeAnc.infer_gtr: inferring the GTR model from the tree...\"", ",", "1", ")", "if", "(", "self", ".", "tree", "is", "None", ")", "or", "(", "self", ".", "aln", "is", "None", ")", ":", "self", ".", "logger", "(", "\"TreeAnc.infer_gtr: ERROR, alignment or tree are missing\"", ",", "0", ")", "return", "ttconf", ".", "ERROR", "_ml_anc", "(", "final", "=", "True", ",", "*", "*", "kwargs", ")", "# call one of the reconstruction types", "alpha", "=", "list", "(", "self", ".", "gtr", ".", "alphabet", ")", "n", "=", "len", "(", "alpha", ")", "# matrix of mutations n_{ij}: i = derived state, j=ancestral state", "nij", "=", "np", ".", "zeros", "(", "(", "n", ",", "n", ")", ")", "Ti", "=", "np", ".", "zeros", "(", "n", ")", "self", ".", "logger", "(", "\"TreeAnc.infer_gtr: counting mutations...\"", ",", "2", ")", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "hasattr", "(", "node", ",", "'mutations'", ")", ":", "for", "a", ",", "pos", ",", "d", "in", "node", ".", "mutations", ":", "i", ",", "j", "=", "alpha", ".", "index", "(", "d", ")", ",", "alpha", ".", "index", "(", "a", ")", "nij", "[", "i", ",", "j", "]", "+=", "1", "Ti", "[", "j", "]", "+=", "0.5", "*", "self", ".", "_branch_length_to_gtr", "(", "node", ")", "Ti", "[", "i", "]", "-=", "0.5", "*", "self", ".", "_branch_length_to_gtr", "(", "node", ")", "for", "ni", ",", "nuc", "in", "enumerate", "(", "node", ".", "cseq", ")", ":", "i", "=", "alpha", ".", "index", "(", "nuc", ")", "Ti", "[", "i", "]", "+=", "self", ".", "_branch_length_to_gtr", "(", "node", ")", "*", "self", ".", "multiplicity", "[", "ni", "]", "self", ".", "logger", "(", "\"TreeAnc.infer_gtr: counting mutations...done\"", ",", "3", ")", "if", "print_raw", ":", "print", "(", "'alphabet:'", ",", "alpha", ")", "print", "(", "'n_ij:'", ",", "nij", ",", "nij", ".", "sum", "(", ")", ")", "print", "(", "'T_i:'", ",", "Ti", ",", "Ti", ".", "sum", "(", ")", ")", "root_state", "=", "np", ".", "array", "(", "[", "np", ".", "sum", "(", "(", "self", ".", "tree", ".", "root", ".", "cseq", "==", "nuc", ")", "*", "self", ".", "multiplicity", ")", "for", "nuc", "in", "alpha", "]", ")", "self", ".", "_gtr", "=", "GTR", ".", "infer", "(", "nij", ",", "Ti", ",", "root_state", ",", "fixed_pi", "=", "fixed_pi", ",", "pc", "=", "pc", ",", "alphabet", "=", "self", ".", "gtr", ".", "alphabet", ",", "logger", "=", "self", ".", "logger", ",", "prof_map", "=", "self", ".", "gtr", ".", "profile_map", ")", "if", "normalized_rate", ":", "self", ".", "logger", "(", "\"TreeAnc.infer_gtr: setting overall rate to 1.0...\"", ",", "2", ")", "self", ".", "_gtr", ".", "mu", "=", "1.0", "return", "self", ".", "_gtr" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.reconstruct_anc
Reconstruct ancestral sequences Parameters ---------- method : str Method to use. Supported values are "fitch" and "ml" infer_gtr : bool Infer a GTR model before reconstructing the sequences marginal : bool Assign sequences that are most likely after averaging over all other nodes instead of the jointly most likely sequences. **kwargs additional keyword arguments that are passed down to :py:meth:`TreeAnc.infer_gtr` and :py:meth:`TreeAnc._ml_anc` Returns ------- N_diff : int Number of nucleotides different from the previous reconstruction. If there were no pre-set sequences, returns N*L
treetime/treeanc.py
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 Infer a GTR model before reconstructing the sequences marginal : bool Assign sequences that are most likely after averaging over all other nodes instead of the jointly most likely sequences. **kwargs additional keyword arguments that are passed down to :py:meth:`TreeAnc.infer_gtr` and :py:meth:`TreeAnc._ml_anc` Returns ------- N_diff : int Number of nucleotides different from the previous reconstruction. If there were no pre-set sequences, returns N*L """ self.logger("TreeAnc.infer_ancestral_sequences with method: %s, %s"%(method, 'marginal' if marginal else 'joint'), 1) if (self.tree is None) or (self.aln is None): self.logger("TreeAnc.infer_ancestral_sequences: ERROR, alignment or tree are missing", 0) return ttconf.ERROR if method in ['ml', 'probabilistic']: if marginal: _ml_anc = self._ml_anc_marginal else: _ml_anc = self._ml_anc_joint else: _ml_anc = self._fitch_anc if infer_gtr: tmp = self.infer_gtr(marginal=marginal, **kwargs) if tmp==ttconf.ERROR: return tmp N_diff = _ml_anc(**kwargs) else: N_diff = _ml_anc(**kwargs) return N_diff
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 Infer a GTR model before reconstructing the sequences marginal : bool Assign sequences that are most likely after averaging over all other nodes instead of the jointly most likely sequences. **kwargs additional keyword arguments that are passed down to :py:meth:`TreeAnc.infer_gtr` and :py:meth:`TreeAnc._ml_anc` Returns ------- N_diff : int Number of nucleotides different from the previous reconstruction. If there were no pre-set sequences, returns N*L """ self.logger("TreeAnc.infer_ancestral_sequences with method: %s, %s"%(method, 'marginal' if marginal else 'joint'), 1) if (self.tree is None) or (self.aln is None): self.logger("TreeAnc.infer_ancestral_sequences: ERROR, alignment or tree are missing", 0) return ttconf.ERROR if method in ['ml', 'probabilistic']: if marginal: _ml_anc = self._ml_anc_marginal else: _ml_anc = self._ml_anc_joint else: _ml_anc = self._fitch_anc if infer_gtr: tmp = self.infer_gtr(marginal=marginal, **kwargs) if tmp==ttconf.ERROR: return tmp N_diff = _ml_anc(**kwargs) else: N_diff = _ml_anc(**kwargs) return N_diff
[ "Reconstruct", "ancestral", "sequences" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L922-L968
[ "def", "reconstruct_anc", "(", "self", ",", "method", "=", "'probabilistic'", ",", "infer_gtr", "=", "False", ",", "marginal", "=", "False", ",", "*", "*", "kwargs", ")", ":", "self", ".", "logger", "(", "\"TreeAnc.infer_ancestral_sequences with method: %s, %s\"", "%", "(", "method", ",", "'marginal'", "if", "marginal", "else", "'joint'", ")", ",", "1", ")", "if", "(", "self", ".", "tree", "is", "None", ")", "or", "(", "self", ".", "aln", "is", "None", ")", ":", "self", ".", "logger", "(", "\"TreeAnc.infer_ancestral_sequences: ERROR, alignment or tree are missing\"", ",", "0", ")", "return", "ttconf", ".", "ERROR", "if", "method", "in", "[", "'ml'", ",", "'probabilistic'", "]", ":", "if", "marginal", ":", "_ml_anc", "=", "self", ".", "_ml_anc_marginal", "else", ":", "_ml_anc", "=", "self", ".", "_ml_anc_joint", "else", ":", "_ml_anc", "=", "self", ".", "_fitch_anc", "if", "infer_gtr", ":", "tmp", "=", "self", ".", "infer_gtr", "(", "marginal", "=", "marginal", ",", "*", "*", "kwargs", ")", "if", "tmp", "==", "ttconf", ".", "ERROR", ":", "return", "tmp", "N_diff", "=", "_ml_anc", "(", "*", "*", "kwargs", ")", "else", ":", "N_diff", "=", "_ml_anc", "(", "*", "*", "kwargs", ")", "return", "N_diff" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.recover_var_ambigs
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 will not work, as ambiguous bases are not part of that alphabet (only A, C, G, T, -). This is why it's left for the user to choose when to run
treetime/treeanc.py
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 will not work, as ambiguous bases are not part of that alphabet (only A, C, G, T, -). This is why it's left for the user to choose when to run """ for node in self.tree.get_terminals(): node.mutations = self.get_mutations(node, keep_var_ambigs=True)
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 will not work, as ambiguous bases are not part of that alphabet (only A, C, G, T, -). This is why it's left for the user to choose when to run """ for node in self.tree.get_terminals(): node.mutations = self.get_mutations(node, keep_var_ambigs=True)
[ "Recalculates", "mutations", "using", "the", "original", "compressed", "sequence", "for", "terminal", "nodes", "which", "will", "recover", "ambiguous", "bases", "at", "variable", "sites", ".", "(", "See", "get_mutations", ")" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L971-L981
[ "def", "recover_var_ambigs", "(", "self", ")", ":", "for", "node", "in", "self", ".", "tree", ".", "get_terminals", "(", ")", ":", "node", ".", "mutations", "=", "self", ".", "get_mutations", "(", "node", ",", "keep_var_ambigs", "=", "True", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.get_mutations
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. Parameters ---------- node : PhyloTree.Clade Tree node, which is the child node attached to the branch. keep_var_ambigs : boolean If true, generates mutations based on the *original* compressed sequence, which may include ambiguities. Note sites that only have 1 unambiguous base and ambiguous bases ("AAAAANN") are stripped of ambiguous bases *before* compression, so ambiguous bases will **not** be preserved. Returns ------- muts : list List of mutations. Each mutation is represented as tuple of :code:`(parent_state, position, child_state)`.
treetime/treeanc.py
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. Parameters ---------- node : PhyloTree.Clade Tree node, which is the child node attached to the branch. keep_var_ambigs : boolean If true, generates mutations based on the *original* compressed sequence, which may include ambiguities. Note sites that only have 1 unambiguous base and ambiguous bases ("AAAAANN") are stripped of ambiguous bases *before* compression, so ambiguous bases will **not** be preserved. Returns ------- muts : list List of mutations. Each mutation is represented as tuple of :code:`(parent_state, position, child_state)`. """ # if ambiguous site are to be restored and node is terminal, # assign original sequence, else reconstructed cseq node_seq = node.cseq if keep_var_ambigs and hasattr(node, "original_cseq") and node.is_terminal(): node_seq = node.original_cseq muts = [] diff_pos = np.where(node.up.cseq!=node_seq)[0] for p in diff_pos: anc = node.up.cseq[p] der = node_seq[p] # expand to the positions in real sequence muts.extend([(anc, pos, der) for pos in self.reduced_to_full_sequence_map[p]]) #sort by position return sorted(muts, key=lambda x:x[1])
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. Parameters ---------- node : PhyloTree.Clade Tree node, which is the child node attached to the branch. keep_var_ambigs : boolean If true, generates mutations based on the *original* compressed sequence, which may include ambiguities. Note sites that only have 1 unambiguous base and ambiguous bases ("AAAAANN") are stripped of ambiguous bases *before* compression, so ambiguous bases will **not** be preserved. Returns ------- muts : list List of mutations. Each mutation is represented as tuple of :code:`(parent_state, position, child_state)`. """ # if ambiguous site are to be restored and node is terminal, # assign original sequence, else reconstructed cseq node_seq = node.cseq if keep_var_ambigs and hasattr(node, "original_cseq") and node.is_terminal(): node_seq = node.original_cseq muts = [] diff_pos = np.where(node.up.cseq!=node_seq)[0] for p in diff_pos: anc = node.up.cseq[p] der = node_seq[p] # expand to the positions in real sequence muts.extend([(anc, pos, der) for pos in self.reduced_to_full_sequence_map[p]]) #sort by position return sorted(muts, key=lambda x:x[1])
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L984-L1023
[ "def", "get_mutations", "(", "self", ",", "node", ",", "keep_var_ambigs", "=", "False", ")", ":", "# if ambiguous site are to be restored and node is terminal,", "# assign original sequence, else reconstructed cseq", "node_seq", "=", "node", ".", "cseq", "if", "keep_var_ambigs", "and", "hasattr", "(", "node", ",", "\"original_cseq\"", ")", "and", "node", ".", "is_terminal", "(", ")", ":", "node_seq", "=", "node", ".", "original_cseq", "muts", "=", "[", "]", "diff_pos", "=", "np", ".", "where", "(", "node", ".", "up", ".", "cseq", "!=", "node_seq", ")", "[", "0", "]", "for", "p", "in", "diff_pos", ":", "anc", "=", "node", ".", "up", ".", "cseq", "[", "p", "]", "der", "=", "node_seq", "[", "p", "]", "# expand to the positions in real sequence", "muts", ".", "extend", "(", "[", "(", "anc", ",", "pos", ",", "der", ")", "for", "pos", "in", "self", ".", "reduced_to_full_sequence_map", "[", "p", "]", "]", ")", "#sort by position", "return", "sorted", "(", "muts", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.get_branch_mutation_matrix
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_sequence : bool, optional expand the sequence to the full sequence, if false (default) the there will be one mutation matrix for each column in the reduced alignment Returns ------- numpy.array an Lxqxq stack of matrices (q=alphabet size, L (reduced)sequence length)
treetime/treeanc.py
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_sequence : bool, optional expand the sequence to the full sequence, if false (default) the there will be one mutation matrix for each column in the reduced alignment Returns ------- numpy.array an Lxqxq stack of matrices (q=alphabet size, L (reduced)sequence length) """ pp,pc = self.marginal_branch_profile(node) # calculate pc_i [e^Qt]_ij pp_j for each site expQt = self.gtr.expQt(self._branch_length_to_gtr(node)) if len(expQt.shape)==3: # site specific model mut_matrix_stack = np.einsum('ai,aj,ija->aij', pc, pp, expQt) else: mut_matrix_stack = np.einsum('ai,aj,ij->aij', pc, pp, expQt) # normalize this distribution normalizer = mut_matrix_stack.sum(axis=2).sum(axis=1) mut_matrix_stack = np.einsum('aij,a->aij', mut_matrix_stack, 1.0/normalizer) # expand to full sequence if requested if full_sequence: return mut_matrix_stack[self.full_to_reduced_sequence_map] else: return mut_matrix_stack
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_sequence : bool, optional expand the sequence to the full sequence, if false (default) the there will be one mutation matrix for each column in the reduced alignment Returns ------- numpy.array an Lxqxq stack of matrices (q=alphabet size, L (reduced)sequence length) """ pp,pc = self.marginal_branch_profile(node) # calculate pc_i [e^Qt]_ij pp_j for each site expQt = self.gtr.expQt(self._branch_length_to_gtr(node)) if len(expQt.shape)==3: # site specific model mut_matrix_stack = np.einsum('ai,aj,ija->aij', pc, pp, expQt) else: mut_matrix_stack = np.einsum('ai,aj,ij->aij', pc, pp, expQt) # normalize this distribution normalizer = mut_matrix_stack.sum(axis=2).sum(axis=1) mut_matrix_stack = np.einsum('aij,a->aij', mut_matrix_stack, 1.0/normalizer) # expand to full sequence if requested if full_sequence: return mut_matrix_stack[self.full_to_reduced_sequence_map] else: return mut_matrix_stack
[ "uses", "results", "from", "marginal", "ancestral", "inference", "to", "return", "a", "joint", "distribution", "of", "the", "sequence", "states", "at", "both", "ends", "of", "the", "branch", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1026-L1061
[ "def", "get_branch_mutation_matrix", "(", "self", ",", "node", ",", "full_sequence", "=", "False", ")", ":", "pp", ",", "pc", "=", "self", ".", "marginal_branch_profile", "(", "node", ")", "# calculate pc_i [e^Qt]_ij pp_j for each site", "expQt", "=", "self", ".", "gtr", ".", "expQt", "(", "self", ".", "_branch_length_to_gtr", "(", "node", ")", ")", "if", "len", "(", "expQt", ".", "shape", ")", "==", "3", ":", "# site specific model", "mut_matrix_stack", "=", "np", ".", "einsum", "(", "'ai,aj,ija->aij'", ",", "pc", ",", "pp", ",", "expQt", ")", "else", ":", "mut_matrix_stack", "=", "np", ".", "einsum", "(", "'ai,aj,ij->aij'", ",", "pc", ",", "pp", ",", "expQt", ")", "# normalize this distribution", "normalizer", "=", "mut_matrix_stack", ".", "sum", "(", "axis", "=", "2", ")", ".", "sum", "(", "axis", "=", "1", ")", "mut_matrix_stack", "=", "np", ".", "einsum", "(", "'aij,a->aij'", ",", "mut_matrix_stack", ",", "1.0", "/", "normalizer", ")", "# expand to full sequence if requested", "if", "full_sequence", ":", "return", "mut_matrix_stack", "[", "self", ".", "full_to_reduced_sequence_map", "]", "else", ":", "return", "mut_matrix_stack" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.expanded_sequence
Expand a nodes compressed sequence into the real sequence Parameters ---------- node : PhyloTree.Clade Tree node Returns ------- seq : np.array Sequence as np.array of chars
treetime/treeanc.py
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 as np.array of chars """ if include_additional_constant_sites: L = self.seq_len else: L = self.seq_len - self.additional_constant_sites return node.cseq[self.full_to_reduced_sequence_map[:L]]
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 as np.array of chars """ if include_additional_constant_sites: L = self.seq_len else: L = self.seq_len - self.additional_constant_sites return node.cseq[self.full_to_reduced_sequence_map[:L]]
[ "Expand", "a", "nodes", "compressed", "sequence", "into", "the", "real", "sequence" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1064-L1083
[ "def", "expanded_sequence", "(", "self", ",", "node", ",", "include_additional_constant_sites", "=", "False", ")", ":", "if", "include_additional_constant_sites", ":", "L", "=", "self", ".", "seq_len", "else", ":", "L", "=", "self", ".", "seq_len", "-", "self", ".", "additional_constant_sites", "return", "node", ".", "cseq", "[", "self", ".", "full_to_reduced_sequence_map", "[", ":", "L", "]", "]" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.dict_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, users can still call :py:meth:`expanded_sequence` if they require the full sequence. Parameters ---------- node : PhyloTree.Clade Tree node Returns ------- seq : dict dict where keys are the basepair position (numbering from 0) and value is the variant call
treetime/treeanc.py
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:meth:`treetime.TreeAnc.expanded_sequence` for VCF-based objects throughout TreeAnc. However, users can still call :py:meth:`expanded_sequence` if they require the full sequence. Parameters ---------- node : PhyloTree.Clade Tree node Returns ------- seq : dict dict where keys are the basepair position (numbering from 0) and value is the variant call """ seq = {} node_seq = node.cseq if keep_var_ambigs and hasattr(node, "original_cseq") and node.is_terminal(): node_seq = node.original_cseq for pos in self.nonref_positions: cseqLoc = self.full_to_reduced_sequence_map[pos] base = node_seq[cseqLoc] if self.ref[pos] != base: seq[pos] = base return seq
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:meth:`treetime.TreeAnc.expanded_sequence` for VCF-based objects throughout TreeAnc. However, users can still call :py:meth:`expanded_sequence` if they require the full sequence. Parameters ---------- node : PhyloTree.Clade Tree node Returns ------- seq : dict dict where keys are the basepair position (numbering from 0) and value is the variant call """ seq = {} node_seq = node.cseq if keep_var_ambigs and hasattr(node, "original_cseq") and node.is_terminal(): node_seq = node.original_cseq for pos in self.nonref_positions: cseqLoc = self.full_to_reduced_sequence_map[pos] base = node_seq[cseqLoc] if self.ref[pos] != base: seq[pos] = base return seq
[ "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", "users", "can", "still", "call", ":", "py", ":", "meth", ":", "expanded_sequence", "if", "they", "require", "the", "full", "sequence", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1086-L1117
[ "def", "dict_sequence", "(", "self", ",", "node", ",", "keep_var_ambigs", "=", "False", ")", ":", "seq", "=", "{", "}", "node_seq", "=", "node", ".", "cseq", "if", "keep_var_ambigs", "and", "hasattr", "(", "node", ",", "\"original_cseq\"", ")", "and", "node", ".", "is_terminal", "(", ")", ":", "node_seq", "=", "node", ".", "original_cseq", "for", "pos", "in", "self", ".", "nonref_positions", ":", "cseqLoc", "=", "self", ".", "full_to_reduced_sequence_map", "[", "pos", "]", "base", "=", "node_seq", "[", "cseqLoc", "]", "if", "self", ".", "ref", "[", "pos", "]", "!=", "base", ":", "seq", "[", "pos", "]", "=", "base", "return", "seq" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._fitch_anc
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 internal nodes. Keyword Args ------------ Returns ------- Ndiff : int Number of the characters that changed since the previous reconstruction. These changes are determined from the pre-set sequence attributes of the nodes. If there are no sequences available (i.e., no reconstruction has been made before), returns the total number of characters in the tree.
treetime/treeanc.py
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 propagating from the root to the leaves, reconstructs the sequences of the internal nodes. Keyword Args ------------ Returns ------- Ndiff : int Number of the characters that changed since the previous reconstruction. These changes are determined from the pre-set sequence attributes of the nodes. If there are no sequences available (i.e., no reconstruction has been made before), returns the total number of characters in the tree. """ # set fitch profiiles to each terminal node for l in self.tree.get_terminals(): l.state = [[k] for k in l.cseq] L = len(self.tree.get_terminals()[0].cseq) self.logger("TreeAnc._fitch_anc: Walking up the tree, creating the Fitch profiles",2) for node in self.tree.get_nonterminals(order='postorder'): node.state = [self._fitch_state(node, k) for k in range(L)] ambs = [i for i in range(L) if len(self.tree.root.state[i])>1] if len(ambs) > 0: for amb in ambs: self.logger("Ambiguous state of the root sequence " "in the position %d: %s, " "choosing %s" % (amb, str(self.tree.root.state[amb]), self.tree.root.state[amb][0]), 4) self.tree.root.cseq = np.array([k[np.random.randint(len(k)) if len(k)>1 else 0] for k in self.tree.root.state]) if self.is_vcf: self.tree.root.sequence = self.dict_sequence(self.tree.root) else: self.tree.root.sequence = self.expanded_sequence(self.tree.root) self.logger("TreeAnc._fitch_anc: Walking down the self.tree, generating sequences from the " "Fitch profiles.", 2) N_diff = 0 for node in self.tree.get_nonterminals(order='preorder'): if node.up != None: # not root sequence = np.array([node.up.cseq[i] if node.up.cseq[i] in node.state[i] else node.state[i][0] for i in range(L)]) if hasattr(node, 'sequence'): N_diff += (sequence!=node.cseq).sum() else: N_diff += L node.cseq = sequence if self.is_vcf: node.sequence = self.dict_sequence(node) else: node.sequence = self.expanded_sequence(node) node.mutations = self.get_mutations(node) node.profile = seq2prof(node.cseq, self.gtr.profile_map) del node.state # no need to store Fitch states self.logger("Done ancestral state reconstruction",3) for node in self.tree.get_terminals(): node.profile = seq2prof(node.original_cseq, self.gtr.profile_map) return N_diff
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 propagating from the root to the leaves, reconstructs the sequences of the internal nodes. Keyword Args ------------ Returns ------- Ndiff : int Number of the characters that changed since the previous reconstruction. These changes are determined from the pre-set sequence attributes of the nodes. If there are no sequences available (i.e., no reconstruction has been made before), returns the total number of characters in the tree. """ # set fitch profiiles to each terminal node for l in self.tree.get_terminals(): l.state = [[k] for k in l.cseq] L = len(self.tree.get_terminals()[0].cseq) self.logger("TreeAnc._fitch_anc: Walking up the tree, creating the Fitch profiles",2) for node in self.tree.get_nonterminals(order='postorder'): node.state = [self._fitch_state(node, k) for k in range(L)] ambs = [i for i in range(L) if len(self.tree.root.state[i])>1] if len(ambs) > 0: for amb in ambs: self.logger("Ambiguous state of the root sequence " "in the position %d: %s, " "choosing %s" % (amb, str(self.tree.root.state[amb]), self.tree.root.state[amb][0]), 4) self.tree.root.cseq = np.array([k[np.random.randint(len(k)) if len(k)>1 else 0] for k in self.tree.root.state]) if self.is_vcf: self.tree.root.sequence = self.dict_sequence(self.tree.root) else: self.tree.root.sequence = self.expanded_sequence(self.tree.root) self.logger("TreeAnc._fitch_anc: Walking down the self.tree, generating sequences from the " "Fitch profiles.", 2) N_diff = 0 for node in self.tree.get_nonterminals(order='preorder'): if node.up != None: # not root sequence = np.array([node.up.cseq[i] if node.up.cseq[i] in node.state[i] else node.state[i][0] for i in range(L)]) if hasattr(node, 'sequence'): N_diff += (sequence!=node.cseq).sum() else: N_diff += L node.cseq = sequence if self.is_vcf: node.sequence = self.dict_sequence(node) else: node.sequence = self.expanded_sequence(node) node.mutations = self.get_mutations(node) node.profile = seq2prof(node.cseq, self.gtr.profile_map) del node.state # no need to store Fitch states self.logger("Done ancestral state reconstruction",3) for node in self.tree.get_terminals(): node.profile = seq2prof(node.original_cseq, self.gtr.profile_map) return N_diff
[ "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", "internal", "nodes", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1122-L1194
[ "def", "_fitch_anc", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# set fitch profiiles to each terminal node", "for", "l", "in", "self", ".", "tree", ".", "get_terminals", "(", ")", ":", "l", ".", "state", "=", "[", "[", "k", "]", "for", "k", "in", "l", ".", "cseq", "]", "L", "=", "len", "(", "self", ".", "tree", ".", "get_terminals", "(", ")", "[", "0", "]", ".", "cseq", ")", "self", ".", "logger", "(", "\"TreeAnc._fitch_anc: Walking up the tree, creating the Fitch profiles\"", ",", "2", ")", "for", "node", "in", "self", ".", "tree", ".", "get_nonterminals", "(", "order", "=", "'postorder'", ")", ":", "node", ".", "state", "=", "[", "self", ".", "_fitch_state", "(", "node", ",", "k", ")", "for", "k", "in", "range", "(", "L", ")", "]", "ambs", "=", "[", "i", "for", "i", "in", "range", "(", "L", ")", "if", "len", "(", "self", ".", "tree", ".", "root", ".", "state", "[", "i", "]", ")", ">", "1", "]", "if", "len", "(", "ambs", ")", ">", "0", ":", "for", "amb", "in", "ambs", ":", "self", ".", "logger", "(", "\"Ambiguous state of the root sequence \"", "\"in the position %d: %s, \"", "\"choosing %s\"", "%", "(", "amb", ",", "str", "(", "self", ".", "tree", ".", "root", ".", "state", "[", "amb", "]", ")", ",", "self", ".", "tree", ".", "root", ".", "state", "[", "amb", "]", "[", "0", "]", ")", ",", "4", ")", "self", ".", "tree", ".", "root", ".", "cseq", "=", "np", ".", "array", "(", "[", "k", "[", "np", ".", "random", ".", "randint", "(", "len", "(", "k", ")", ")", "if", "len", "(", "k", ")", ">", "1", "else", "0", "]", "for", "k", "in", "self", ".", "tree", ".", "root", ".", "state", "]", ")", "if", "self", ".", "is_vcf", ":", "self", ".", "tree", ".", "root", ".", "sequence", "=", "self", ".", "dict_sequence", "(", "self", ".", "tree", ".", "root", ")", "else", ":", "self", ".", "tree", ".", "root", ".", "sequence", "=", "self", ".", "expanded_sequence", "(", "self", ".", "tree", ".", "root", ")", "self", ".", "logger", "(", "\"TreeAnc._fitch_anc: Walking down the self.tree, generating sequences from the \"", "\"Fitch profiles.\"", ",", "2", ")", "N_diff", "=", "0", "for", "node", "in", "self", ".", "tree", ".", "get_nonterminals", "(", "order", "=", "'preorder'", ")", ":", "if", "node", ".", "up", "!=", "None", ":", "# not root", "sequence", "=", "np", ".", "array", "(", "[", "node", ".", "up", ".", "cseq", "[", "i", "]", "if", "node", ".", "up", ".", "cseq", "[", "i", "]", "in", "node", ".", "state", "[", "i", "]", "else", "node", ".", "state", "[", "i", "]", "[", "0", "]", "for", "i", "in", "range", "(", "L", ")", "]", ")", "if", "hasattr", "(", "node", ",", "'sequence'", ")", ":", "N_diff", "+=", "(", "sequence", "!=", "node", ".", "cseq", ")", ".", "sum", "(", ")", "else", ":", "N_diff", "+=", "L", "node", ".", "cseq", "=", "sequence", "if", "self", ".", "is_vcf", ":", "node", ".", "sequence", "=", "self", ".", "dict_sequence", "(", "node", ")", "else", ":", "node", ".", "sequence", "=", "self", ".", "expanded_sequence", "(", "node", ")", "node", ".", "mutations", "=", "self", ".", "get_mutations", "(", "node", ")", "node", ".", "profile", "=", "seq2prof", "(", "node", ".", "cseq", ",", "self", ".", "gtr", ".", "profile_map", ")", "del", "node", ".", "state", "# no need to store Fitch states", "self", ".", "logger", "(", "\"Done ancestral state reconstruction\"", ",", "3", ")", "for", "node", "in", "self", ".", "tree", ".", "get_terminals", "(", ")", ":", "node", ".", "profile", "=", "seq2prof", "(", "node", ".", "original_cseq", ",", "self", ".", "gtr", ".", "profile_map", ")", "return", "N_diff" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._fitch_state
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 ---------- node : PhyloTree.Clade: Internal node which the profiles are to be determined pos : int Position in the node's sequence which the profiles should be determinedf for. Returns ------- state : numpy.array Fitch profile for the character at position pos of the given node.
treetime/treeanc.py
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 ---------- node : PhyloTree.Clade: Internal node which the profiles are to be determined pos : int Position in the node's sequence which the profiles should be determinedf for. Returns ------- state : numpy.array Fitch profile for the character at position pos of the given node. """ state = self._fitch_intersect([k.state[pos] for k in node.clades]) if len(state) == 0: state = np.concatenate([k.state[pos] for k in node.clades]) return state
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 ---------- node : PhyloTree.Clade: Internal node which the profiles are to be determined pos : int Position in the node's sequence which the profiles should be determinedf for. Returns ------- state : numpy.array Fitch profile for the character at position pos of the given node. """ state = self._fitch_intersect([k.state[pos] for k in node.clades]) if len(state) == 0: state = np.concatenate([k.state[pos] for k in node.clades]) return state
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1197-L1221
[ "def", "_fitch_state", "(", "self", ",", "node", ",", "pos", ")", ":", "state", "=", "self", ".", "_fitch_intersect", "(", "[", "k", ".", "state", "[", "pos", "]", "for", "k", "in", "node", ".", "clades", "]", ")", "if", "len", "(", "state", ")", "==", "0", ":", "state", "=", "np", ".", "concatenate", "(", "[", "k", ".", "state", "[", "pos", "]", "for", "k", "in", "node", ".", "clades", "]", ")", "return", "state" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._fitch_intersect
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
treetime/treeanc.py
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) b3 = [val for val in arr1 if val in s2] return b3 arrays = list(arrays) # allow assignment N = len(arrays) while N > 1: arr1 = arrays.pop() arr2 = arrays.pop() arr = pairwise_intersect(arr1, arr2) arrays.append(arr) N = len(arrays) return arrays[0]
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) b3 = [val for val in arr1 if val in s2] return b3 arrays = list(arrays) # allow assignment N = len(arrays) while N > 1: arr1 = arrays.pop() arr2 = arrays.pop() arr = pairwise_intersect(arr1, arr2) arrays.append(arr) N = len(arrays) return arrays[0]
[ "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" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1224-L1244
[ "def", "_fitch_intersect", "(", "self", ",", "arrays", ")", ":", "def", "pairwise_intersect", "(", "arr1", ",", "arr2", ")", ":", "s2", "=", "set", "(", "arr2", ")", "b3", "=", "[", "val", "for", "val", "in", "arr1", "if", "val", "in", "s2", "]", "return", "b3", "arrays", "=", "list", "(", "arrays", ")", "# allow assignment", "N", "=", "len", "(", "arrays", ")", "while", "N", ">", "1", ":", "arr1", "=", "arrays", ".", "pop", "(", ")", "arr2", "=", "arrays", ".", "pop", "(", ")", "arr", "=", "pairwise_intersect", "(", "arr1", ",", "arr2", ")", "arrays", ".", "append", "(", "arr", ")", "N", "=", "len", "(", "arrays", ")", "return", "arrays", "[", "0", "]" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.sequence_LH
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, optional does the position refer to the full or compressed sequence, by default compressed sequence is assumed. Returns ------- float likelihood
treetime/treeanc.py
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, optional does the position refer to the full or compressed sequence, by default compressed sequence is assumed. Returns ------- float likelihood """ if not hasattr(self.tree, "total_sequence_LH"): self.logger("TreeAnc.sequence_LH: you need to run marginal ancestral inference first!", 1) self.infer_ancestral_sequences(marginal=True) if pos is not None: if full_sequence: compressed_pos = self.full_to_reduced_sequence_map[pos] else: compressed_pos = pos return self.tree.sequence_LH[compressed_pos] else: return self.tree.total_sequence_LH
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, optional does the position refer to the full or compressed sequence, by default compressed sequence is assumed. Returns ------- float likelihood """ if not hasattr(self.tree, "total_sequence_LH"): self.logger("TreeAnc.sequence_LH: you need to run marginal ancestral inference first!", 1) self.infer_ancestral_sequences(marginal=True) if pos is not None: if full_sequence: compressed_pos = self.full_to_reduced_sequence_map[pos] else: compressed_pos = pos return self.tree.sequence_LH[compressed_pos] else: return self.tree.total_sequence_LH
[ "return", "the", "likelihood", "of", "the", "observed", "sequences", "given", "the", "tree" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1251-L1276
[ "def", "sequence_LH", "(", "self", ",", "pos", "=", "None", ",", "full_sequence", "=", "False", ")", ":", "if", "not", "hasattr", "(", "self", ".", "tree", ",", "\"total_sequence_LH\"", ")", ":", "self", ".", "logger", "(", "\"TreeAnc.sequence_LH: you need to run marginal ancestral inference first!\"", ",", "1", ")", "self", ".", "infer_ancestral_sequences", "(", "marginal", "=", "True", ")", "if", "pos", "is", "not", "None", ":", "if", "full_sequence", ":", "compressed_pos", "=", "self", ".", "full_to_reduced_sequence_map", "[", "pos", "]", "else", ":", "compressed_pos", "=", "pos", "return", "self", ".", "tree", ".", "sequence_LH", "[", "compressed_pos", "]", "else", ":", "return", "self", ".", "tree", ".", "total_sequence_LH" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.ancestral_likelihood
Calculate the likelihood of the given realization of the sequences in the tree Returns ------- log_lh : float The tree likelihood given the sequences
treetime/treeanc.py
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]) for node in self.tree.find_clades(order='postorder'): if node.up is None: # root node # 0-1 profile profile = seq2prof(node.cseq, self.gtr.profile_map) # get the probabilities to observe each nucleotide profile *= self.gtr.Pi profile = profile.sum(axis=1) log_lh += np.log(profile) # product over all characters continue t = node.branch_length indices = np.array([(np.argmax(self.gtr.alphabet==a), np.argmax(self.gtr.alphabet==b)) for a, b in zip(node.up.cseq, node.cseq)]) logQt = np.log(self.gtr.expQt(t)) lh = logQt[indices[:, 1], indices[:, 0]] log_lh += lh return log_lh
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]) for node in self.tree.find_clades(order='postorder'): if node.up is None: # root node # 0-1 profile profile = seq2prof(node.cseq, self.gtr.profile_map) # get the probabilities to observe each nucleotide profile *= self.gtr.Pi profile = profile.sum(axis=1) log_lh += np.log(profile) # product over all characters continue t = node.branch_length indices = np.array([(np.argmax(self.gtr.alphabet==a), np.argmax(self.gtr.alphabet==b)) for a, b in zip(node.up.cseq, node.cseq)]) logQt = np.log(self.gtr.expQt(t)) lh = logQt[indices[:, 1], indices[:, 0]] log_lh += lh return log_lh
[ "Calculate", "the", "likelihood", "of", "the", "given", "realization", "of", "the", "sequences", "in", "the", "tree" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1279-L1311
[ "def", "ancestral_likelihood", "(", "self", ")", ":", "log_lh", "=", "np", ".", "zeros", "(", "self", ".", "multiplicity", ".", "shape", "[", "0", "]", ")", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'postorder'", ")", ":", "if", "node", ".", "up", "is", "None", ":", "# root node", "# 0-1 profile", "profile", "=", "seq2prof", "(", "node", ".", "cseq", ",", "self", ".", "gtr", ".", "profile_map", ")", "# get the probabilities to observe each nucleotide", "profile", "*=", "self", ".", "gtr", ".", "Pi", "profile", "=", "profile", ".", "sum", "(", "axis", "=", "1", ")", "log_lh", "+=", "np", ".", "log", "(", "profile", ")", "# product over all characters", "continue", "t", "=", "node", ".", "branch_length", "indices", "=", "np", ".", "array", "(", "[", "(", "np", ".", "argmax", "(", "self", ".", "gtr", ".", "alphabet", "==", "a", ")", ",", "np", ".", "argmax", "(", "self", ".", "gtr", ".", "alphabet", "==", "b", ")", ")", "for", "a", ",", "b", "in", "zip", "(", "node", ".", "up", ".", "cseq", ",", "node", ".", "cseq", ")", "]", ")", "logQt", "=", "np", ".", "log", "(", "self", ".", "gtr", ".", "expQt", "(", "t", ")", ")", "lh", "=", "logQt", "[", "indices", "[", ":", ",", "1", "]", ",", "indices", "[", ":", ",", "0", "]", "]", "log_lh", "+=", "lh", "return", "log_lh" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._branch_length_to_gtr
Set branch lengths to either mutation lengths of given branch lengths. The assigend values are to be used in the following ML analysis.
treetime/treeanc.py
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, node.mutation_length) else: return max(ttconf.MIN_BRANCH_LENGTH*self.one_mutation, node.branch_length)
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, node.mutation_length) else: return max(ttconf.MIN_BRANCH_LENGTH*self.one_mutation, node.branch_length)
[ "Set", "branch", "lengths", "to", "either", "mutation", "lengths", "of", "given", "branch", "lengths", ".", "The", "assigend", "values", "are", "to", "be", "used", "in", "the", "following", "ML", "analysis", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1313-L1321
[ "def", "_branch_length_to_gtr", "(", "self", ",", "node", ")", ":", "if", "self", ".", "use_mutation_length", ":", "return", "max", "(", "ttconf", ".", "MIN_BRANCH_LENGTH", "*", "self", ".", "one_mutation", ",", "node", ".", "mutation_length", ")", "else", ":", "return", "max", "(", "ttconf", ".", "MIN_BRANCH_LENGTH", "*", "self", ".", "one_mutation", ",", "node", ".", "branch_length", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._ml_anc_marginal
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. Parameters ---------- store_compressed : bool, default True attach a reduced representation of sequence changed to each branch final : bool, default True stop full length by expanding sites with identical alignment patterns sample_from_profile : bool or str assign sequences probabilistically according to the inferred probabilities of ancestral states instead of to their ML value. This parameter can also take the value 'root' in which case probabilistic sampling will happen at the root but at no other node.
treetime/treeanc.py
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 log probabilities and is hence handled by a separate function. Parameters ---------- store_compressed : bool, default True attach a reduced representation of sequence changed to each branch final : bool, default True stop full length by expanding sites with identical alignment patterns sample_from_profile : bool or str assign sequences probabilistically according to the inferred probabilities of ancestral states instead of to their ML value. This parameter can also take the value 'root' in which case probabilistic sampling will happen at the root but at no other node. """ tree = self.tree # number of nucleotides changed from prev reconstruction N_diff = 0 L = self.multiplicity.shape[0] n_states = self.gtr.alphabet.shape[0] self.logger("TreeAnc._ml_anc_marginal: type of reconstruction: Marginal", 2) self.logger("Attaching sequence profiles to leafs... ", 3) # set the leaves profiles for leaf in tree.get_terminals(): # in any case, set the profile leaf.marginal_subtree_LH = seq2prof(leaf.original_cseq, self.gtr.profile_map) leaf.marginal_subtree_LH_prefactor = np.zeros(L) self.logger("Walking up the tree, computing likelihoods... ", 3) # propagate leaves --> root, set the marginal-likelihood messages for node in tree.get_nonterminals(order='postorder'): #leaves -> root # regardless of what was before, set the profile to ones tmp_log_subtree_LH = np.zeros((L,n_states), dtype=float) node.marginal_subtree_LH_prefactor = np.zeros(L, dtype=float) for ch in node.clades: ch.marginal_log_Lx = self.gtr.propagate_profile(ch.marginal_subtree_LH, self._branch_length_to_gtr(ch), return_log=True) # raw prob to transfer prob up tmp_log_subtree_LH += ch.marginal_log_Lx node.marginal_subtree_LH_prefactor += ch.marginal_subtree_LH_prefactor node.marginal_subtree_LH, offset = normalize_profile(tmp_log_subtree_LH, log=True) node.marginal_subtree_LH_prefactor += offset # and store log-prefactor self.logger("Computing root node sequence and total tree likelihood...",3) # Msg to the root from the distant part (equ frequencies) if len(self.gtr.Pi.shape)==1: tree.root.marginal_outgroup_LH = np.repeat([self.gtr.Pi], tree.root.marginal_subtree_LH.shape[0], axis=0) else: tree.root.marginal_outgroup_LH = np.copy(self.gtr.Pi.T) tree.root.marginal_profile, pre = normalize_profile(tree.root.marginal_outgroup_LH*tree.root.marginal_subtree_LH) marginal_LH_prefactor = tree.root.marginal_subtree_LH_prefactor + pre # choose sequence characters from this profile. # treat root node differently to avoid piling up mutations on the longer branch if sample_from_profile=='root': root_sample_from_profile = True other_sample_from_profile = False elif isinstance(sample_from_profile, bool): root_sample_from_profile = sample_from_profile other_sample_from_profile = sample_from_profile seq, prof_vals, idxs = prof2seq(tree.root.marginal_profile, self.gtr, sample_from_prof=root_sample_from_profile, normalize=False) self.tree.sequence_LH = marginal_LH_prefactor self.tree.total_sequence_LH = (self.tree.sequence_LH*self.multiplicity).sum() self.tree.root.cseq = seq gc.collect() if final: if self.is_vcf: self.tree.root.sequence = self.dict_sequence(self.tree.root) else: self.tree.root.sequence = self.expanded_sequence(self.tree.root) self.logger("Walking down the tree, computing maximum likelihood sequences...",3) # propagate root -->> leaves, reconstruct the internal node sequences # provided the upstream message + the message from the complementary subtree for node in tree.find_clades(order='preorder'): if node.up is None: # skip if node is root continue # integrate the information coming from parents with the information # of all children my multiplying it to the prev computed profile node.marginal_outgroup_LH, pre = normalize_profile(np.log(node.up.marginal_profile) - node.marginal_log_Lx, log=True, return_offset=False) tmp_msg_from_parent = self.gtr.evolve(node.marginal_outgroup_LH, self._branch_length_to_gtr(node), return_log=False) node.marginal_profile, pre = normalize_profile(node.marginal_subtree_LH * tmp_msg_from_parent, return_offset=False) # choose sequence based maximal marginal LH. seq, prof_vals, idxs = prof2seq(node.marginal_profile, self.gtr, sample_from_prof=other_sample_from_profile, normalize=False) if hasattr(node, 'cseq') and node.cseq is not None: N_diff += (seq!=node.cseq).sum() else: N_diff += L #assign new sequence node.cseq = seq if final: if self.is_vcf: node.sequence = self.dict_sequence(node) else: node.sequence = self.expanded_sequence(node) node.mutations = self.get_mutations(node) # note that the root doesn't contribute to N_diff (intended, since root sequence is often ambiguous) self.logger("TreeAnc._ml_anc_marginal: ...done", 3) if store_compressed: self._store_compressed_sequence_pairs() # do clean-up: if not debug: for node in self.tree.find_clades(): try: del node.marginal_log_Lx del node.marginal_subtree_LH_prefactor except: pass gc.collect() return N_diff
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 log probabilities and is hence handled by a separate function. Parameters ---------- store_compressed : bool, default True attach a reduced representation of sequence changed to each branch final : bool, default True stop full length by expanding sites with identical alignment patterns sample_from_profile : bool or str assign sequences probabilistically according to the inferred probabilities of ancestral states instead of to their ML value. This parameter can also take the value 'root' in which case probabilistic sampling will happen at the root but at no other node. """ tree = self.tree # number of nucleotides changed from prev reconstruction N_diff = 0 L = self.multiplicity.shape[0] n_states = self.gtr.alphabet.shape[0] self.logger("TreeAnc._ml_anc_marginal: type of reconstruction: Marginal", 2) self.logger("Attaching sequence profiles to leafs... ", 3) # set the leaves profiles for leaf in tree.get_terminals(): # in any case, set the profile leaf.marginal_subtree_LH = seq2prof(leaf.original_cseq, self.gtr.profile_map) leaf.marginal_subtree_LH_prefactor = np.zeros(L) self.logger("Walking up the tree, computing likelihoods... ", 3) # propagate leaves --> root, set the marginal-likelihood messages for node in tree.get_nonterminals(order='postorder'): #leaves -> root # regardless of what was before, set the profile to ones tmp_log_subtree_LH = np.zeros((L,n_states), dtype=float) node.marginal_subtree_LH_prefactor = np.zeros(L, dtype=float) for ch in node.clades: ch.marginal_log_Lx = self.gtr.propagate_profile(ch.marginal_subtree_LH, self._branch_length_to_gtr(ch), return_log=True) # raw prob to transfer prob up tmp_log_subtree_LH += ch.marginal_log_Lx node.marginal_subtree_LH_prefactor += ch.marginal_subtree_LH_prefactor node.marginal_subtree_LH, offset = normalize_profile(tmp_log_subtree_LH, log=True) node.marginal_subtree_LH_prefactor += offset # and store log-prefactor self.logger("Computing root node sequence and total tree likelihood...",3) # Msg to the root from the distant part (equ frequencies) if len(self.gtr.Pi.shape)==1: tree.root.marginal_outgroup_LH = np.repeat([self.gtr.Pi], tree.root.marginal_subtree_LH.shape[0], axis=0) else: tree.root.marginal_outgroup_LH = np.copy(self.gtr.Pi.T) tree.root.marginal_profile, pre = normalize_profile(tree.root.marginal_outgroup_LH*tree.root.marginal_subtree_LH) marginal_LH_prefactor = tree.root.marginal_subtree_LH_prefactor + pre # choose sequence characters from this profile. # treat root node differently to avoid piling up mutations on the longer branch if sample_from_profile=='root': root_sample_from_profile = True other_sample_from_profile = False elif isinstance(sample_from_profile, bool): root_sample_from_profile = sample_from_profile other_sample_from_profile = sample_from_profile seq, prof_vals, idxs = prof2seq(tree.root.marginal_profile, self.gtr, sample_from_prof=root_sample_from_profile, normalize=False) self.tree.sequence_LH = marginal_LH_prefactor self.tree.total_sequence_LH = (self.tree.sequence_LH*self.multiplicity).sum() self.tree.root.cseq = seq gc.collect() if final: if self.is_vcf: self.tree.root.sequence = self.dict_sequence(self.tree.root) else: self.tree.root.sequence = self.expanded_sequence(self.tree.root) self.logger("Walking down the tree, computing maximum likelihood sequences...",3) # propagate root -->> leaves, reconstruct the internal node sequences # provided the upstream message + the message from the complementary subtree for node in tree.find_clades(order='preorder'): if node.up is None: # skip if node is root continue # integrate the information coming from parents with the information # of all children my multiplying it to the prev computed profile node.marginal_outgroup_LH, pre = normalize_profile(np.log(node.up.marginal_profile) - node.marginal_log_Lx, log=True, return_offset=False) tmp_msg_from_parent = self.gtr.evolve(node.marginal_outgroup_LH, self._branch_length_to_gtr(node), return_log=False) node.marginal_profile, pre = normalize_profile(node.marginal_subtree_LH * tmp_msg_from_parent, return_offset=False) # choose sequence based maximal marginal LH. seq, prof_vals, idxs = prof2seq(node.marginal_profile, self.gtr, sample_from_prof=other_sample_from_profile, normalize=False) if hasattr(node, 'cseq') and node.cseq is not None: N_diff += (seq!=node.cseq).sum() else: N_diff += L #assign new sequence node.cseq = seq if final: if self.is_vcf: node.sequence = self.dict_sequence(node) else: node.sequence = self.expanded_sequence(node) node.mutations = self.get_mutations(node) # note that the root doesn't contribute to N_diff (intended, since root sequence is often ambiguous) self.logger("TreeAnc._ml_anc_marginal: ...done", 3) if store_compressed: self._store_compressed_sequence_pairs() # do clean-up: if not debug: for node in self.tree.find_clades(): try: del node.marginal_log_Lx del node.marginal_subtree_LH_prefactor except: pass gc.collect() return N_diff
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1324-L1461
[ "def", "_ml_anc_marginal", "(", "self", ",", "store_compressed", "=", "False", ",", "final", "=", "True", ",", "sample_from_profile", "=", "False", ",", "debug", "=", "False", ",", "*", "*", "kwargs", ")", ":", "tree", "=", "self", ".", "tree", "# number of nucleotides changed from prev reconstruction", "N_diff", "=", "0", "L", "=", "self", ".", "multiplicity", ".", "shape", "[", "0", "]", "n_states", "=", "self", ".", "gtr", ".", "alphabet", ".", "shape", "[", "0", "]", "self", ".", "logger", "(", "\"TreeAnc._ml_anc_marginal: type of reconstruction: Marginal\"", ",", "2", ")", "self", ".", "logger", "(", "\"Attaching sequence profiles to leafs... \"", ",", "3", ")", "# set the leaves profiles", "for", "leaf", "in", "tree", ".", "get_terminals", "(", ")", ":", "# in any case, set the profile", "leaf", ".", "marginal_subtree_LH", "=", "seq2prof", "(", "leaf", ".", "original_cseq", ",", "self", ".", "gtr", ".", "profile_map", ")", "leaf", ".", "marginal_subtree_LH_prefactor", "=", "np", ".", "zeros", "(", "L", ")", "self", ".", "logger", "(", "\"Walking up the tree, computing likelihoods... \"", ",", "3", ")", "# propagate leaves --> root, set the marginal-likelihood messages", "for", "node", "in", "tree", ".", "get_nonterminals", "(", "order", "=", "'postorder'", ")", ":", "#leaves -> root", "# regardless of what was before, set the profile to ones", "tmp_log_subtree_LH", "=", "np", ".", "zeros", "(", "(", "L", ",", "n_states", ")", ",", "dtype", "=", "float", ")", "node", ".", "marginal_subtree_LH_prefactor", "=", "np", ".", "zeros", "(", "L", ",", "dtype", "=", "float", ")", "for", "ch", "in", "node", ".", "clades", ":", "ch", ".", "marginal_log_Lx", "=", "self", ".", "gtr", ".", "propagate_profile", "(", "ch", ".", "marginal_subtree_LH", ",", "self", ".", "_branch_length_to_gtr", "(", "ch", ")", ",", "return_log", "=", "True", ")", "# raw prob to transfer prob up", "tmp_log_subtree_LH", "+=", "ch", ".", "marginal_log_Lx", "node", ".", "marginal_subtree_LH_prefactor", "+=", "ch", ".", "marginal_subtree_LH_prefactor", "node", ".", "marginal_subtree_LH", ",", "offset", "=", "normalize_profile", "(", "tmp_log_subtree_LH", ",", "log", "=", "True", ")", "node", ".", "marginal_subtree_LH_prefactor", "+=", "offset", "# and store log-prefactor", "self", ".", "logger", "(", "\"Computing root node sequence and total tree likelihood...\"", ",", "3", ")", "# Msg to the root from the distant part (equ frequencies)", "if", "len", "(", "self", ".", "gtr", ".", "Pi", ".", "shape", ")", "==", "1", ":", "tree", ".", "root", ".", "marginal_outgroup_LH", "=", "np", ".", "repeat", "(", "[", "self", ".", "gtr", ".", "Pi", "]", ",", "tree", ".", "root", ".", "marginal_subtree_LH", ".", "shape", "[", "0", "]", ",", "axis", "=", "0", ")", "else", ":", "tree", ".", "root", ".", "marginal_outgroup_LH", "=", "np", ".", "copy", "(", "self", ".", "gtr", ".", "Pi", ".", "T", ")", "tree", ".", "root", ".", "marginal_profile", ",", "pre", "=", "normalize_profile", "(", "tree", ".", "root", ".", "marginal_outgroup_LH", "*", "tree", ".", "root", ".", "marginal_subtree_LH", ")", "marginal_LH_prefactor", "=", "tree", ".", "root", ".", "marginal_subtree_LH_prefactor", "+", "pre", "# choose sequence characters from this profile.", "# treat root node differently to avoid piling up mutations on the longer branch", "if", "sample_from_profile", "==", "'root'", ":", "root_sample_from_profile", "=", "True", "other_sample_from_profile", "=", "False", "elif", "isinstance", "(", "sample_from_profile", ",", "bool", ")", ":", "root_sample_from_profile", "=", "sample_from_profile", "other_sample_from_profile", "=", "sample_from_profile", "seq", ",", "prof_vals", ",", "idxs", "=", "prof2seq", "(", "tree", ".", "root", ".", "marginal_profile", ",", "self", ".", "gtr", ",", "sample_from_prof", "=", "root_sample_from_profile", ",", "normalize", "=", "False", ")", "self", ".", "tree", ".", "sequence_LH", "=", "marginal_LH_prefactor", "self", ".", "tree", ".", "total_sequence_LH", "=", "(", "self", ".", "tree", ".", "sequence_LH", "*", "self", ".", "multiplicity", ")", ".", "sum", "(", ")", "self", ".", "tree", ".", "root", ".", "cseq", "=", "seq", "gc", ".", "collect", "(", ")", "if", "final", ":", "if", "self", ".", "is_vcf", ":", "self", ".", "tree", ".", "root", ".", "sequence", "=", "self", ".", "dict_sequence", "(", "self", ".", "tree", ".", "root", ")", "else", ":", "self", ".", "tree", ".", "root", ".", "sequence", "=", "self", ".", "expanded_sequence", "(", "self", ".", "tree", ".", "root", ")", "self", ".", "logger", "(", "\"Walking down the tree, computing maximum likelihood sequences...\"", ",", "3", ")", "# propagate root -->> leaves, reconstruct the internal node sequences", "# provided the upstream message + the message from the complementary subtree", "for", "node", "in", "tree", ".", "find_clades", "(", "order", "=", "'preorder'", ")", ":", "if", "node", ".", "up", "is", "None", ":", "# skip if node is root", "continue", "# integrate the information coming from parents with the information", "# of all children my multiplying it to the prev computed profile", "node", ".", "marginal_outgroup_LH", ",", "pre", "=", "normalize_profile", "(", "np", ".", "log", "(", "node", ".", "up", ".", "marginal_profile", ")", "-", "node", ".", "marginal_log_Lx", ",", "log", "=", "True", ",", "return_offset", "=", "False", ")", "tmp_msg_from_parent", "=", "self", ".", "gtr", ".", "evolve", "(", "node", ".", "marginal_outgroup_LH", ",", "self", ".", "_branch_length_to_gtr", "(", "node", ")", ",", "return_log", "=", "False", ")", "node", ".", "marginal_profile", ",", "pre", "=", "normalize_profile", "(", "node", ".", "marginal_subtree_LH", "*", "tmp_msg_from_parent", ",", "return_offset", "=", "False", ")", "# choose sequence based maximal marginal LH.", "seq", ",", "prof_vals", ",", "idxs", "=", "prof2seq", "(", "node", ".", "marginal_profile", ",", "self", ".", "gtr", ",", "sample_from_prof", "=", "other_sample_from_profile", ",", "normalize", "=", "False", ")", "if", "hasattr", "(", "node", ",", "'cseq'", ")", "and", "node", ".", "cseq", "is", "not", "None", ":", "N_diff", "+=", "(", "seq", "!=", "node", ".", "cseq", ")", ".", "sum", "(", ")", "else", ":", "N_diff", "+=", "L", "#assign new sequence", "node", ".", "cseq", "=", "seq", "if", "final", ":", "if", "self", ".", "is_vcf", ":", "node", ".", "sequence", "=", "self", ".", "dict_sequence", "(", "node", ")", "else", ":", "node", ".", "sequence", "=", "self", ".", "expanded_sequence", "(", "node", ")", "node", ".", "mutations", "=", "self", ".", "get_mutations", "(", "node", ")", "# note that the root doesn't contribute to N_diff (intended, since root sequence is often ambiguous)", "self", ".", "logger", "(", "\"TreeAnc._ml_anc_marginal: ...done\"", ",", "3", ")", "if", "store_compressed", ":", "self", ".", "_store_compressed_sequence_pairs", "(", ")", "# do clean-up:", "if", "not", "debug", ":", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "try", ":", "del", "node", ".", "marginal_log_Lx", "del", "node", ".", "marginal_subtree_LH_prefactor", "except", ":", "pass", "gc", ".", "collect", "(", ")", "return", "N_diff" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._ml_anc_joint
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. Parameters ---------- store_compressed : bool, default True attach a reduced representation of sequence changed to each branch final : bool, default True stop full length by expanding sites with identical alignment patterns sample_from_profile : str This parameter can take the value 'root' in which case probabilistic sampling will happen at the root. otherwise sequences at ALL nodes are set to the value that jointly optimized the likelihood.
treetime/treeanc.py
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 can hence operate in log space. Parameters ---------- store_compressed : bool, default True attach a reduced representation of sequence changed to each branch final : bool, default True stop full length by expanding sites with identical alignment patterns sample_from_profile : str This parameter can take the value 'root' in which case probabilistic sampling will happen at the root. otherwise sequences at ALL nodes are set to the value that jointly optimized the likelihood. """ N_diff = 0 # number of sites differ from perv reconstruction L = self.multiplicity.shape[0] n_states = self.gtr.alphabet.shape[0] self.logger("TreeAnc._ml_anc_joint: type of reconstruction: Joint", 2) self.logger("TreeAnc._ml_anc_joint: Walking up the tree, computing likelihoods... ", 3) # for the internal nodes, scan over all states j of this node, maximize the likelihood for node in self.tree.find_clades(order='postorder'): if node.up is None: node.joint_Cx=None # not needed for root continue # preallocate storage node.joint_Lx = np.zeros((L, n_states)) # likelihood array node.joint_Cx = np.zeros((L, n_states), dtype=int) # max LH indices branch_len = self._branch_length_to_gtr(node) # transition matrix from parent states to the current node states. # denoted as Pij(i), where j - parent state, i - node state log_transitions = np.log(np.maximum(ttconf.TINY_NUMBER, self.gtr.expQt(branch_len))) if node.is_terminal(): try: msg_from_children = np.log(np.maximum(seq2prof(node.original_cseq, self.gtr.profile_map), ttconf.TINY_NUMBER)) except: raise ValueError("sequence assignment to node "+node.name+" failed") msg_from_children[np.isnan(msg_from_children) | np.isinf(msg_from_children)] = -ttconf.BIG_NUMBER else: # Product (sum-Log) over all child subtree likelihoods. # this is prod_ch L_x(i) msg_from_children = np.sum(np.stack([c.joint_Lx for c in node.clades], axis=0), axis=0) # for every possible state of the parent node, # get the best state of the current node # and compute the likelihood of this state for char_i, char in enumerate(self.gtr.alphabet): # Pij(i) * L_ch(i) for given parent state j msg_to_parent = (log_transitions[:,char_i].T + msg_from_children) # For this parent state, choose the best state of the current node: node.joint_Cx[:, char_i] = msg_to_parent.argmax(axis=1) # compute the likelihood of the best state of the current node # given the state of the parent (char_i) node.joint_Lx[:, char_i] = msg_to_parent.max(axis=1) # root node profile = likelihood of the total tree msg_from_children = np.sum(np.stack([c.joint_Lx for c in self.tree.root], axis = 0), axis=0) # Pi(i) * Prod_ch Lch(i) self.tree.root.joint_Lx = msg_from_children + np.log(self.gtr.Pi).T normalized_profile = (self.tree.root.joint_Lx.T - self.tree.root.joint_Lx.max(axis=1)).T # choose sequence characters from this profile. # treat root node differently to avoid piling up mutations on the longer branch if sample_from_profile=='root': root_sample_from_profile = True elif isinstance(sample_from_profile, bool): root_sample_from_profile = sample_from_profile seq, anc_lh_vals, idxs = prof2seq(np.exp(normalized_profile), self.gtr, sample_from_prof = root_sample_from_profile) # compute the likelihood of the most probable root sequence self.tree.sequence_LH = np.choose(idxs, self.tree.root.joint_Lx.T) self.tree.sequence_joint_LH = (self.tree.sequence_LH*self.multiplicity).sum() self.tree.root.cseq = seq self.tree.root.seq_idx = idxs if final: if self.is_vcf: self.tree.root.sequence = self.dict_sequence(self.tree.root) else: self.tree.root.sequence = self.expanded_sequence(self.tree.root) self.logger("TreeAnc._ml_anc_joint: Walking down the tree, computing maximum likelihood sequences...",3) # for each node, resolve the conditioning on the parent node for node in self.tree.find_clades(order='preorder'): # root node has no mutations, everything else has been alread y set if node.up is None: node.mutations = [] continue # choose the value of the Cx(i), corresponding to the state of the # parent node i. This is the state of the current node node.seq_idx = np.choose(node.up.seq_idx, node.joint_Cx.T) # reconstruct seq, etc tmp_sequence = np.choose(node.seq_idx, self.gtr.alphabet) if hasattr(node, 'sequence') and node.cseq is not None: N_diff += (tmp_sequence!=node.cseq).sum() else: N_diff += L node.cseq = tmp_sequence if final: node.mutations = self.get_mutations(node) if self.is_vcf: node.sequence = self.dict_sequence(node) else: node.sequence = self.expanded_sequence(node) self.logger("TreeAnc._ml_anc_joint: ...done", 3) if store_compressed: self._store_compressed_sequence_pairs() # do clean-up if not debug: for node in self.tree.find_clades(order='preorder'): del node.joint_Lx del node.joint_Cx del node.seq_idx return N_diff
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 can hence operate in log space. Parameters ---------- store_compressed : bool, default True attach a reduced representation of sequence changed to each branch final : bool, default True stop full length by expanding sites with identical alignment patterns sample_from_profile : str This parameter can take the value 'root' in which case probabilistic sampling will happen at the root. otherwise sequences at ALL nodes are set to the value that jointly optimized the likelihood. """ N_diff = 0 # number of sites differ from perv reconstruction L = self.multiplicity.shape[0] n_states = self.gtr.alphabet.shape[0] self.logger("TreeAnc._ml_anc_joint: type of reconstruction: Joint", 2) self.logger("TreeAnc._ml_anc_joint: Walking up the tree, computing likelihoods... ", 3) # for the internal nodes, scan over all states j of this node, maximize the likelihood for node in self.tree.find_clades(order='postorder'): if node.up is None: node.joint_Cx=None # not needed for root continue # preallocate storage node.joint_Lx = np.zeros((L, n_states)) # likelihood array node.joint_Cx = np.zeros((L, n_states), dtype=int) # max LH indices branch_len = self._branch_length_to_gtr(node) # transition matrix from parent states to the current node states. # denoted as Pij(i), where j - parent state, i - node state log_transitions = np.log(np.maximum(ttconf.TINY_NUMBER, self.gtr.expQt(branch_len))) if node.is_terminal(): try: msg_from_children = np.log(np.maximum(seq2prof(node.original_cseq, self.gtr.profile_map), ttconf.TINY_NUMBER)) except: raise ValueError("sequence assignment to node "+node.name+" failed") msg_from_children[np.isnan(msg_from_children) | np.isinf(msg_from_children)] = -ttconf.BIG_NUMBER else: # Product (sum-Log) over all child subtree likelihoods. # this is prod_ch L_x(i) msg_from_children = np.sum(np.stack([c.joint_Lx for c in node.clades], axis=0), axis=0) # for every possible state of the parent node, # get the best state of the current node # and compute the likelihood of this state for char_i, char in enumerate(self.gtr.alphabet): # Pij(i) * L_ch(i) for given parent state j msg_to_parent = (log_transitions[:,char_i].T + msg_from_children) # For this parent state, choose the best state of the current node: node.joint_Cx[:, char_i] = msg_to_parent.argmax(axis=1) # compute the likelihood of the best state of the current node # given the state of the parent (char_i) node.joint_Lx[:, char_i] = msg_to_parent.max(axis=1) # root node profile = likelihood of the total tree msg_from_children = np.sum(np.stack([c.joint_Lx for c in self.tree.root], axis = 0), axis=0) # Pi(i) * Prod_ch Lch(i) self.tree.root.joint_Lx = msg_from_children + np.log(self.gtr.Pi).T normalized_profile = (self.tree.root.joint_Lx.T - self.tree.root.joint_Lx.max(axis=1)).T # choose sequence characters from this profile. # treat root node differently to avoid piling up mutations on the longer branch if sample_from_profile=='root': root_sample_from_profile = True elif isinstance(sample_from_profile, bool): root_sample_from_profile = sample_from_profile seq, anc_lh_vals, idxs = prof2seq(np.exp(normalized_profile), self.gtr, sample_from_prof = root_sample_from_profile) # compute the likelihood of the most probable root sequence self.tree.sequence_LH = np.choose(idxs, self.tree.root.joint_Lx.T) self.tree.sequence_joint_LH = (self.tree.sequence_LH*self.multiplicity).sum() self.tree.root.cseq = seq self.tree.root.seq_idx = idxs if final: if self.is_vcf: self.tree.root.sequence = self.dict_sequence(self.tree.root) else: self.tree.root.sequence = self.expanded_sequence(self.tree.root) self.logger("TreeAnc._ml_anc_joint: Walking down the tree, computing maximum likelihood sequences...",3) # for each node, resolve the conditioning on the parent node for node in self.tree.find_clades(order='preorder'): # root node has no mutations, everything else has been alread y set if node.up is None: node.mutations = [] continue # choose the value of the Cx(i), corresponding to the state of the # parent node i. This is the state of the current node node.seq_idx = np.choose(node.up.seq_idx, node.joint_Cx.T) # reconstruct seq, etc tmp_sequence = np.choose(node.seq_idx, self.gtr.alphabet) if hasattr(node, 'sequence') and node.cseq is not None: N_diff += (tmp_sequence!=node.cseq).sum() else: N_diff += L node.cseq = tmp_sequence if final: node.mutations = self.get_mutations(node) if self.is_vcf: node.sequence = self.dict_sequence(node) else: node.sequence = self.expanded_sequence(node) self.logger("TreeAnc._ml_anc_joint: ...done", 3) if store_compressed: self._store_compressed_sequence_pairs() # do clean-up if not debug: for node in self.tree.find_clades(order='preorder'): del node.joint_Lx del node.joint_Cx del node.seq_idx return N_diff
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1464-L1596
[ "def", "_ml_anc_joint", "(", "self", ",", "store_compressed", "=", "True", ",", "final", "=", "True", ",", "sample_from_profile", "=", "False", ",", "debug", "=", "False", ",", "*", "*", "kwargs", ")", ":", "N_diff", "=", "0", "# number of sites differ from perv reconstruction", "L", "=", "self", ".", "multiplicity", ".", "shape", "[", "0", "]", "n_states", "=", "self", ".", "gtr", ".", "alphabet", ".", "shape", "[", "0", "]", "self", ".", "logger", "(", "\"TreeAnc._ml_anc_joint: type of reconstruction: Joint\"", ",", "2", ")", "self", ".", "logger", "(", "\"TreeAnc._ml_anc_joint: Walking up the tree, computing likelihoods... \"", ",", "3", ")", "# for the internal nodes, scan over all states j of this node, maximize the likelihood", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'postorder'", ")", ":", "if", "node", ".", "up", "is", "None", ":", "node", ".", "joint_Cx", "=", "None", "# not needed for root", "continue", "# preallocate storage", "node", ".", "joint_Lx", "=", "np", ".", "zeros", "(", "(", "L", ",", "n_states", ")", ")", "# likelihood array", "node", ".", "joint_Cx", "=", "np", ".", "zeros", "(", "(", "L", ",", "n_states", ")", ",", "dtype", "=", "int", ")", "# max LH indices", "branch_len", "=", "self", ".", "_branch_length_to_gtr", "(", "node", ")", "# transition matrix from parent states to the current node states.", "# denoted as Pij(i), where j - parent state, i - node state", "log_transitions", "=", "np", ".", "log", "(", "np", ".", "maximum", "(", "ttconf", ".", "TINY_NUMBER", ",", "self", ".", "gtr", ".", "expQt", "(", "branch_len", ")", ")", ")", "if", "node", ".", "is_terminal", "(", ")", ":", "try", ":", "msg_from_children", "=", "np", ".", "log", "(", "np", ".", "maximum", "(", "seq2prof", "(", "node", ".", "original_cseq", ",", "self", ".", "gtr", ".", "profile_map", ")", ",", "ttconf", ".", "TINY_NUMBER", ")", ")", "except", ":", "raise", "ValueError", "(", "\"sequence assignment to node \"", "+", "node", ".", "name", "+", "\" failed\"", ")", "msg_from_children", "[", "np", ".", "isnan", "(", "msg_from_children", ")", "|", "np", ".", "isinf", "(", "msg_from_children", ")", "]", "=", "-", "ttconf", ".", "BIG_NUMBER", "else", ":", "# Product (sum-Log) over all child subtree likelihoods.", "# this is prod_ch L_x(i)", "msg_from_children", "=", "np", ".", "sum", "(", "np", ".", "stack", "(", "[", "c", ".", "joint_Lx", "for", "c", "in", "node", ".", "clades", "]", ",", "axis", "=", "0", ")", ",", "axis", "=", "0", ")", "# for every possible state of the parent node,", "# get the best state of the current node", "# and compute the likelihood of this state", "for", "char_i", ",", "char", "in", "enumerate", "(", "self", ".", "gtr", ".", "alphabet", ")", ":", "# Pij(i) * L_ch(i) for given parent state j", "msg_to_parent", "=", "(", "log_transitions", "[", ":", ",", "char_i", "]", ".", "T", "+", "msg_from_children", ")", "# For this parent state, choose the best state of the current node:", "node", ".", "joint_Cx", "[", ":", ",", "char_i", "]", "=", "msg_to_parent", ".", "argmax", "(", "axis", "=", "1", ")", "# compute the likelihood of the best state of the current node", "# given the state of the parent (char_i)", "node", ".", "joint_Lx", "[", ":", ",", "char_i", "]", "=", "msg_to_parent", ".", "max", "(", "axis", "=", "1", ")", "# root node profile = likelihood of the total tree", "msg_from_children", "=", "np", ".", "sum", "(", "np", ".", "stack", "(", "[", "c", ".", "joint_Lx", "for", "c", "in", "self", ".", "tree", ".", "root", "]", ",", "axis", "=", "0", ")", ",", "axis", "=", "0", ")", "# Pi(i) * Prod_ch Lch(i)", "self", ".", "tree", ".", "root", ".", "joint_Lx", "=", "msg_from_children", "+", "np", ".", "log", "(", "self", ".", "gtr", ".", "Pi", ")", ".", "T", "normalized_profile", "=", "(", "self", ".", "tree", ".", "root", ".", "joint_Lx", ".", "T", "-", "self", ".", "tree", ".", "root", ".", "joint_Lx", ".", "max", "(", "axis", "=", "1", ")", ")", ".", "T", "# choose sequence characters from this profile.", "# treat root node differently to avoid piling up mutations on the longer branch", "if", "sample_from_profile", "==", "'root'", ":", "root_sample_from_profile", "=", "True", "elif", "isinstance", "(", "sample_from_profile", ",", "bool", ")", ":", "root_sample_from_profile", "=", "sample_from_profile", "seq", ",", "anc_lh_vals", ",", "idxs", "=", "prof2seq", "(", "np", ".", "exp", "(", "normalized_profile", ")", ",", "self", ".", "gtr", ",", "sample_from_prof", "=", "root_sample_from_profile", ")", "# compute the likelihood of the most probable root sequence", "self", ".", "tree", ".", "sequence_LH", "=", "np", ".", "choose", "(", "idxs", ",", "self", ".", "tree", ".", "root", ".", "joint_Lx", ".", "T", ")", "self", ".", "tree", ".", "sequence_joint_LH", "=", "(", "self", ".", "tree", ".", "sequence_LH", "*", "self", ".", "multiplicity", ")", ".", "sum", "(", ")", "self", ".", "tree", ".", "root", ".", "cseq", "=", "seq", "self", ".", "tree", ".", "root", ".", "seq_idx", "=", "idxs", "if", "final", ":", "if", "self", ".", "is_vcf", ":", "self", ".", "tree", ".", "root", ".", "sequence", "=", "self", ".", "dict_sequence", "(", "self", ".", "tree", ".", "root", ")", "else", ":", "self", ".", "tree", ".", "root", ".", "sequence", "=", "self", ".", "expanded_sequence", "(", "self", ".", "tree", ".", "root", ")", "self", ".", "logger", "(", "\"TreeAnc._ml_anc_joint: Walking down the tree, computing maximum likelihood sequences...\"", ",", "3", ")", "# for each node, resolve the conditioning on the parent node", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'preorder'", ")", ":", "# root node has no mutations, everything else has been alread y set", "if", "node", ".", "up", "is", "None", ":", "node", ".", "mutations", "=", "[", "]", "continue", "# choose the value of the Cx(i), corresponding to the state of the", "# parent node i. This is the state of the current node", "node", ".", "seq_idx", "=", "np", ".", "choose", "(", "node", ".", "up", ".", "seq_idx", ",", "node", ".", "joint_Cx", ".", "T", ")", "# reconstruct seq, etc", "tmp_sequence", "=", "np", ".", "choose", "(", "node", ".", "seq_idx", ",", "self", ".", "gtr", ".", "alphabet", ")", "if", "hasattr", "(", "node", ",", "'sequence'", ")", "and", "node", ".", "cseq", "is", "not", "None", ":", "N_diff", "+=", "(", "tmp_sequence", "!=", "node", ".", "cseq", ")", ".", "sum", "(", ")", "else", ":", "N_diff", "+=", "L", "node", ".", "cseq", "=", "tmp_sequence", "if", "final", ":", "node", ".", "mutations", "=", "self", ".", "get_mutations", "(", "node", ")", "if", "self", ".", "is_vcf", ":", "node", ".", "sequence", "=", "self", ".", "dict_sequence", "(", "node", ")", "else", ":", "node", ".", "sequence", "=", "self", ".", "expanded_sequence", "(", "node", ")", "self", ".", "logger", "(", "\"TreeAnc._ml_anc_joint: ...done\"", ",", "3", ")", "if", "store_compressed", ":", "self", ".", "_store_compressed_sequence_pairs", "(", ")", "# do clean-up", "if", "not", "debug", ":", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'preorder'", ")", ":", "del", "node", ".", "joint_Lx", "del", "node", ".", "joint_Cx", "del", "node", ".", "seq_idx", "return", "N_diff" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._store_compressed_sequence_to_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 ----------- node : PhyloTree.Clade Tree node. **Note** because the method operates on the sequences on both sides of a branch, sequence reconstruction must be performed prior to calling this method.
treetime/treeanc.py
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 ----------- node : PhyloTree.Clade Tree node. **Note** because the method operates on the sequences on both sides of a branch, sequence reconstruction must be performed prior to calling this method. """ seq_pairs, multiplicity = self.gtr.compress_sequence_pair(node.up.cseq, node.cseq, pattern_multiplicity = self.multiplicity, ignore_gaps = self.ignore_gaps) node.compressed_sequence = {'pair':seq_pairs, 'multiplicity':multiplicity}
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 ----------- node : PhyloTree.Clade Tree node. **Note** because the method operates on the sequences on both sides of a branch, sequence reconstruction must be performed prior to calling this method. """ seq_pairs, multiplicity = self.gtr.compress_sequence_pair(node.up.cseq, node.cseq, pattern_multiplicity = self.multiplicity, ignore_gaps = self.ignore_gaps) node.compressed_sequence = {'pair':seq_pairs, 'multiplicity':multiplicity}
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1599-L1618
[ "def", "_store_compressed_sequence_to_node", "(", "self", ",", "node", ")", ":", "seq_pairs", ",", "multiplicity", "=", "self", ".", "gtr", ".", "compress_sequence_pair", "(", "node", ".", "up", ".", "cseq", ",", "node", ".", "cseq", ",", "pattern_multiplicity", "=", "self", ".", "multiplicity", ",", "ignore_gaps", "=", "self", ".", "ignore_gaps", ")", "node", ".", "compressed_sequence", "=", "{", "'pair'", ":", "seq_pairs", ",", "'multiplicity'", ":", "multiplicity", "}" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc._store_compressed_sequence_pairs
Traverse the tree, and for each node store the compressed sequence pair. **Note** sequence reconstruction should be performed prior to calling this method.
treetime/treeanc.py
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) for node in self.tree.find_clades(): if node.up is None: continue self._store_compressed_sequence_to_node(node) self.logger("TreeAnc._store_compressed_sequence_pairs...done",3)
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) for node in self.tree.find_clades(): if node.up is None: continue self._store_compressed_sequence_to_node(node) self.logger("TreeAnc._store_compressed_sequence_pairs...done",3)
[ "Traverse", "the", "tree", "and", "for", "each", "node", "store", "the", "compressed", "sequence", "pair", ".", "**", "Note", "**", "sequence", "reconstruction", "should", "be", "performed", "prior", "to", "calling", "this", "method", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1621-L1632
[ "def", "_store_compressed_sequence_pairs", "(", "self", ")", ":", "self", ".", "logger", "(", "\"TreeAnc._store_compressed_sequence_pairs...\"", ",", "2", ")", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "node", ".", "up", "is", "None", ":", "continue", "self", ".", "_store_compressed_sequence_to_node", "(", "node", ")", "self", ".", "logger", "(", "\"TreeAnc._store_compressed_sequence_pairs...done\"", ",", "3", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.optimize_branch_length
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.array object (node.sequence attribute). Therefore, before calling this method, sequence reconstruction with either of the available models must be performed. Parameters ---------- mode : str Optimize branch length assuming the joint ML sequence assignment of both ends of the branch (:code:`joint`), or trace over all possible sequence assignments on both ends of the branch (:code:`marginal`) (slower, experimental). **kwargs : Keyword arguments Keyword Args ------------ verbose : int Output level store_old : bool If True, the old lengths will be saved in :code:`node._old_dist` attribute. Useful for testing, and special post-processing.
treetime/treeanc.py
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.array object (node.sequence attribute). Therefore, before calling this method, sequence reconstruction with either of the available models must be performed. Parameters ---------- mode : str Optimize branch length assuming the joint ML sequence assignment of both ends of the branch (:code:`joint`), or trace over all possible sequence assignments on both ends of the branch (:code:`marginal`) (slower, experimental). **kwargs : Keyword arguments Keyword Args ------------ verbose : int Output level store_old : bool If True, the old lengths will be saved in :code:`node._old_dist` attribute. Useful for testing, and special post-processing. """ self.logger("TreeAnc.optimize_branch_length: running branch length optimization in mode %s..."%mode,1) if (self.tree is None) or (self.aln is None): self.logger("TreeAnc.optimize_branch_length: ERROR, alignment or tree are missing", 0) return ttconf.ERROR store_old_dist = False if 'store_old' in kwargs: store_old_dist = kwargs['store_old'] if mode=='marginal': # a marginal ancestral reconstruction is required for # marginal branch length inference if not hasattr(self.tree.root, "marginal_profile"): self.infer_ancestral_sequences(marginal=True) max_bl = 0 for node in self.tree.find_clades(order='postorder'): if node.up is None: continue # this is the root if store_old_dist: node._old_length = node.branch_length if mode=='marginal': new_len = self.optimal_marginal_branch_length(node) elif mode=='joint': new_len = self.optimal_branch_length(node) else: self.logger("treeanc.optimize_branch_length: unsupported optimization mode",4, warn=True) new_len = node.branch_length if new_len < 0: continue self.logger("Optimization results: old_len=%.4e, new_len=%.4e, naive=%.4e" " Updating branch length..."%(node.branch_length, new_len, len(node.mutations)*self.one_mutation), 5) node.branch_length = new_len node.mutation_length=new_len max_bl = max(max_bl, new_len) # as branch lengths changed, the params must be fixed self.tree.root.up = None self.tree.root.dist2root = 0.0 if max_bl>0.15 and mode=='joint': self.logger("TreeAnc.optimize_branch_length: THIS TREE HAS LONG BRANCHES." " \n\t ****TreeTime IS NOT DESIGNED TO OPTIMIZE LONG BRANCHES." " \n\t ****PLEASE OPTIMIZE BRANCHES WITH ANOTHER TOOL AND RERUN WITH" " \n\t ****branch_length_mode='input'", 0, warn=True) self._prepare_nodes() return ttconf.SUCCESS
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.array object (node.sequence attribute). Therefore, before calling this method, sequence reconstruction with either of the available models must be performed. Parameters ---------- mode : str Optimize branch length assuming the joint ML sequence assignment of both ends of the branch (:code:`joint`), or trace over all possible sequence assignments on both ends of the branch (:code:`marginal`) (slower, experimental). **kwargs : Keyword arguments Keyword Args ------------ verbose : int Output level store_old : bool If True, the old lengths will be saved in :code:`node._old_dist` attribute. Useful for testing, and special post-processing. """ self.logger("TreeAnc.optimize_branch_length: running branch length optimization in mode %s..."%mode,1) if (self.tree is None) or (self.aln is None): self.logger("TreeAnc.optimize_branch_length: ERROR, alignment or tree are missing", 0) return ttconf.ERROR store_old_dist = False if 'store_old' in kwargs: store_old_dist = kwargs['store_old'] if mode=='marginal': # a marginal ancestral reconstruction is required for # marginal branch length inference if not hasattr(self.tree.root, "marginal_profile"): self.infer_ancestral_sequences(marginal=True) max_bl = 0 for node in self.tree.find_clades(order='postorder'): if node.up is None: continue # this is the root if store_old_dist: node._old_length = node.branch_length if mode=='marginal': new_len = self.optimal_marginal_branch_length(node) elif mode=='joint': new_len = self.optimal_branch_length(node) else: self.logger("treeanc.optimize_branch_length: unsupported optimization mode",4, warn=True) new_len = node.branch_length if new_len < 0: continue self.logger("Optimization results: old_len=%.4e, new_len=%.4e, naive=%.4e" " Updating branch length..."%(node.branch_length, new_len, len(node.mutations)*self.one_mutation), 5) node.branch_length = new_len node.mutation_length=new_len max_bl = max(max_bl, new_len) # as branch lengths changed, the params must be fixed self.tree.root.up = None self.tree.root.dist2root = 0.0 if max_bl>0.15 and mode=='joint': self.logger("TreeAnc.optimize_branch_length: THIS TREE HAS LONG BRANCHES." " \n\t ****TreeTime IS NOT DESIGNED TO OPTIMIZE LONG BRANCHES." " \n\t ****PLEASE OPTIMIZE BRANCHES WITH ANOTHER TOOL AND RERUN WITH" " \n\t ****branch_length_mode='input'", 0, warn=True) self._prepare_nodes() return ttconf.SUCCESS
[ "Perform", "optimization", "for", "the", "branch", "lengths", "of", "the", "entire", "tree", ".", "This", "method", "only", "does", "a", "single", "path", "and", "needs", "to", "be", "iterated", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1641-L1724
[ "def", "optimize_branch_length", "(", "self", ",", "mode", "=", "'joint'", ",", "*", "*", "kwargs", ")", ":", "self", ".", "logger", "(", "\"TreeAnc.optimize_branch_length: running branch length optimization in mode %s...\"", "%", "mode", ",", "1", ")", "if", "(", "self", ".", "tree", "is", "None", ")", "or", "(", "self", ".", "aln", "is", "None", ")", ":", "self", ".", "logger", "(", "\"TreeAnc.optimize_branch_length: ERROR, alignment or tree are missing\"", ",", "0", ")", "return", "ttconf", ".", "ERROR", "store_old_dist", "=", "False", "if", "'store_old'", "in", "kwargs", ":", "store_old_dist", "=", "kwargs", "[", "'store_old'", "]", "if", "mode", "==", "'marginal'", ":", "# a marginal ancestral reconstruction is required for", "# marginal branch length inference", "if", "not", "hasattr", "(", "self", ".", "tree", ".", "root", ",", "\"marginal_profile\"", ")", ":", "self", ".", "infer_ancestral_sequences", "(", "marginal", "=", "True", ")", "max_bl", "=", "0", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'postorder'", ")", ":", "if", "node", ".", "up", "is", "None", ":", "continue", "# this is the root", "if", "store_old_dist", ":", "node", ".", "_old_length", "=", "node", ".", "branch_length", "if", "mode", "==", "'marginal'", ":", "new_len", "=", "self", ".", "optimal_marginal_branch_length", "(", "node", ")", "elif", "mode", "==", "'joint'", ":", "new_len", "=", "self", ".", "optimal_branch_length", "(", "node", ")", "else", ":", "self", ".", "logger", "(", "\"treeanc.optimize_branch_length: unsupported optimization mode\"", ",", "4", ",", "warn", "=", "True", ")", "new_len", "=", "node", ".", "branch_length", "if", "new_len", "<", "0", ":", "continue", "self", ".", "logger", "(", "\"Optimization results: old_len=%.4e, new_len=%.4e, naive=%.4e\"", "\" Updating branch length...\"", "%", "(", "node", ".", "branch_length", ",", "new_len", ",", "len", "(", "node", ".", "mutations", ")", "*", "self", ".", "one_mutation", ")", ",", "5", ")", "node", ".", "branch_length", "=", "new_len", "node", ".", "mutation_length", "=", "new_len", "max_bl", "=", "max", "(", "max_bl", ",", "new_len", ")", "# as branch lengths changed, the params must be fixed", "self", ".", "tree", ".", "root", ".", "up", "=", "None", "self", ".", "tree", ".", "root", ".", "dist2root", "=", "0.0", "if", "max_bl", ">", "0.15", "and", "mode", "==", "'joint'", ":", "self", ".", "logger", "(", "\"TreeAnc.optimize_branch_length: THIS TREE HAS LONG BRANCHES.\"", "\" \\n\\t ****TreeTime IS NOT DESIGNED TO OPTIMIZE LONG BRANCHES.\"", "\" \\n\\t ****PLEASE OPTIMIZE BRANCHES WITH ANOTHER TOOL AND RERUN WITH\"", "\" \\n\\t ****branch_length_mode='input'\"", ",", "0", ",", "warn", "=", "True", ")", "self", ".", "_prepare_nodes", "(", ")", "return", "ttconf", ".", "SUCCESS" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.optimize_branch_length_global
EXPERIMENTAL GLOBAL OPTIMIZATION
treetime/treeanc.py
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')): n.branch_length = si**2 self.infer_ancestral_sequences(marginal=True) gradient = [] for si, n in zip(s, self.tree.find_clades(order='preorder')): if n.up: pp, pc = self.marginal_branch_profile(n) Qtds = self.gtr.expQsds(si).T Qt = self.gtr.expQs(si).T res = pp.dot(Qt) overlap = np.sum(res*pc, axis=1) res_ds = pp.dot(Qtds) overlap_ds = np.sum(res_ds*pc, axis=1) logP = np.sum(self.multiplicity*overlap_ds/overlap) gradient.append(logP) else: gradient.append(2*(si**2-0.001)) print(-self.tree.sequence_marginal_LH) return (-self.tree.sequence_marginal_LH + (s[0]**2-0.001)**2, -1.0*np.array(gradient)) from scipy.optimize import minimize x0 = np.sqrt([n.branch_length for n in self.tree.find_clades(order='preorder')]) sol = minimize(neg_log, x0, jac=True) for new_len, node in zip(sol['x'], self.tree.find_clades()): self.logger("Optimization results: old_len=%.4f, new_len=%.4f " " Updating branch length..."%(node.branch_length, new_len), 5) node.branch_length = new_len**2 node.mutation_length=new_len**2 # as branch lengths changed, the params must be fixed self.tree.root.up = None self.tree.root.dist2root = 0.0 self._prepare_nodes()
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')): n.branch_length = si**2 self.infer_ancestral_sequences(marginal=True) gradient = [] for si, n in zip(s, self.tree.find_clades(order='preorder')): if n.up: pp, pc = self.marginal_branch_profile(n) Qtds = self.gtr.expQsds(si).T Qt = self.gtr.expQs(si).T res = pp.dot(Qt) overlap = np.sum(res*pc, axis=1) res_ds = pp.dot(Qtds) overlap_ds = np.sum(res_ds*pc, axis=1) logP = np.sum(self.multiplicity*overlap_ds/overlap) gradient.append(logP) else: gradient.append(2*(si**2-0.001)) print(-self.tree.sequence_marginal_LH) return (-self.tree.sequence_marginal_LH + (s[0]**2-0.001)**2, -1.0*np.array(gradient)) from scipy.optimize import minimize x0 = np.sqrt([n.branch_length for n in self.tree.find_clades(order='preorder')]) sol = minimize(neg_log, x0, jac=True) for new_len, node in zip(sol['x'], self.tree.find_clades()): self.logger("Optimization results: old_len=%.4f, new_len=%.4f " " Updating branch length..."%(node.branch_length, new_len), 5) node.branch_length = new_len**2 node.mutation_length=new_len**2 # as branch lengths changed, the params must be fixed self.tree.root.up = None self.tree.root.dist2root = 0.0 self._prepare_nodes()
[ "EXPERIMENTAL", "GLOBAL", "OPTIMIZATION" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1727-L1775
[ "def", "optimize_branch_length_global", "(", "self", ",", "*", "*", "kwargs", ")", ":", "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'", ")", ")", ":", "n", ".", "branch_length", "=", "si", "**", "2", "self", ".", "infer_ancestral_sequences", "(", "marginal", "=", "True", ")", "gradient", "=", "[", "]", "for", "si", ",", "n", "in", "zip", "(", "s", ",", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'preorder'", ")", ")", ":", "if", "n", ".", "up", ":", "pp", ",", "pc", "=", "self", ".", "marginal_branch_profile", "(", "n", ")", "Qtds", "=", "self", ".", "gtr", ".", "expQsds", "(", "si", ")", ".", "T", "Qt", "=", "self", ".", "gtr", ".", "expQs", "(", "si", ")", ".", "T", "res", "=", "pp", ".", "dot", "(", "Qt", ")", "overlap", "=", "np", ".", "sum", "(", "res", "*", "pc", ",", "axis", "=", "1", ")", "res_ds", "=", "pp", ".", "dot", "(", "Qtds", ")", "overlap_ds", "=", "np", ".", "sum", "(", "res_ds", "*", "pc", ",", "axis", "=", "1", ")", "logP", "=", "np", ".", "sum", "(", "self", ".", "multiplicity", "*", "overlap_ds", "/", "overlap", ")", "gradient", ".", "append", "(", "logP", ")", "else", ":", "gradient", ".", "append", "(", "2", "*", "(", "si", "**", "2", "-", "0.001", ")", ")", "print", "(", "-", "self", ".", "tree", ".", "sequence_marginal_LH", ")", "return", "(", "-", "self", ".", "tree", ".", "sequence_marginal_LH", "+", "(", "s", "[", "0", "]", "**", "2", "-", "0.001", ")", "**", "2", ",", "-", "1.0", "*", "np", ".", "array", "(", "gradient", ")", ")", "from", "scipy", ".", "optimize", "import", "minimize", "x0", "=", "np", ".", "sqrt", "(", "[", "n", ".", "branch_length", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'preorder'", ")", "]", ")", "sol", "=", "minimize", "(", "neg_log", ",", "x0", ",", "jac", "=", "True", ")", "for", "new_len", ",", "node", "in", "zip", "(", "sol", "[", "'x'", "]", ",", "self", ".", "tree", ".", "find_clades", "(", ")", ")", ":", "self", ".", "logger", "(", "\"Optimization results: old_len=%.4f, new_len=%.4f \"", "\" Updating branch length...\"", "%", "(", "node", ".", "branch_length", ",", "new_len", ")", ",", "5", ")", "node", ".", "branch_length", "=", "new_len", "**", "2", "node", ".", "mutation_length", "=", "new_len", "**", "2", "# as branch lengths changed, the params must be fixed", "self", ".", "tree", ".", "root", ".", "up", "=", "None", "self", ".", "tree", ".", "root", ".", "dist2root", "=", "0.0", "self", ".", "_prepare_nodes", "(", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.optimal_branch_length
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 length of the given branch
treetime/treeanc.py
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 length of the given branch ''' if node.up is None: return self.one_mutation parent = node.up if hasattr(node, 'compressed_sequence'): new_len = self.gtr.optimal_t_compressed(node.compressed_sequence['pair'], node.compressed_sequence['multiplicity']) else: new_len = self.gtr.optimal_t(parent.cseq, node.cseq, pattern_multiplicity=self.multiplicity, ignore_gaps=self.ignore_gaps) return new_len
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 length of the given branch ''' if node.up is None: return self.one_mutation parent = node.up if hasattr(node, 'compressed_sequence'): new_len = self.gtr.optimal_t_compressed(node.compressed_sequence['pair'], node.compressed_sequence['multiplicity']) else: new_len = self.gtr.optimal_t(parent.cseq, node.cseq, pattern_multiplicity=self.multiplicity, ignore_gaps=self.ignore_gaps) return new_len
[ "Calculate", "optimal", "branch", "length", "given", "the", "sequences", "of", "node", "and", "parent" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1778-L1804
[ "def", "optimal_branch_length", "(", "self", ",", "node", ")", ":", "if", "node", ".", "up", "is", "None", ":", "return", "self", ".", "one_mutation", "parent", "=", "node", ".", "up", "if", "hasattr", "(", "node", ",", "'compressed_sequence'", ")", ":", "new_len", "=", "self", ".", "gtr", ".", "optimal_t_compressed", "(", "node", ".", "compressed_sequence", "[", "'pair'", "]", ",", "node", ".", "compressed_sequence", "[", "'multiplicity'", "]", ")", "else", ":", "new_len", "=", "self", ".", "gtr", ".", "optimal_t", "(", "parent", ".", "cseq", ",", "node", ".", "cseq", ",", "pattern_multiplicity", "=", "self", ".", "multiplicity", ",", "ignore_gaps", "=", "self", ".", "ignore_gaps", ")", "return", "new_len" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.marginal_branch_profile
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 ------- pp, pc : Pair of vectors (profile parent, pp) and (profile child, pc) that are of shape (L,n) where L is sequence length and n is alphabet size. note that this correspond to the compressed sequences.
treetime/treeanc.py
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 ------- pp, pc : Pair of vectors (profile parent, pp) and (profile child, pc) that are of shape (L,n) where L is sequence length and n is alphabet size. note that this correspond to the compressed sequences. ''' parent = node.up if parent is None: raise Exception("Branch profiles can't be calculated for the root!") if not hasattr(node, 'marginal_outgroup_LH'): raise Exception("marginal ancestral inference needs to be performed first!") pc = node.marginal_subtree_LH pp = node.marginal_outgroup_LH return pp, pc
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 ------- pp, pc : Pair of vectors (profile parent, pp) and (profile child, pc) that are of shape (L,n) where L is sequence length and n is alphabet size. note that this correspond to the compressed sequences. ''' parent = node.up if parent is None: raise Exception("Branch profiles can't be calculated for the root!") if not hasattr(node, 'marginal_outgroup_LH'): raise Exception("marginal ancestral inference needs to be performed first!") pc = node.marginal_subtree_LH pp = node.marginal_outgroup_LH return pp, pc
[ "calculate", "the", "marginal", "distribution", "of", "sequence", "states", "on", "both", "ends", "of", "the", "branch", "leading", "to", "node" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1807-L1832
[ "def", "marginal_branch_profile", "(", "self", ",", "node", ")", ":", "parent", "=", "node", ".", "up", "if", "parent", "is", "None", ":", "raise", "Exception", "(", "\"Branch profiles can't be calculated for the root!\"", ")", "if", "not", "hasattr", "(", "node", ",", "'marginal_outgroup_LH'", ")", ":", "raise", "Exception", "(", "\"marginal ancestral inference needs to be performed first!\"", ")", "pc", "=", "node", ".", "marginal_subtree_LH", "pp", "=", "node", ".", "marginal_outgroup_LH", "return", "pp", ",", "pc" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.optimal_marginal_branch_length
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 ------- branch_length : float branch length of the branch leading to the node. note: this can be unstable on iteration
treetime/treeanc.py
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 ------- branch_length : float branch length of the branch leading to the node. note: this can be unstable on iteration ''' if node.up is None: return self.one_mutation pp, pc = self.marginal_branch_profile(node) return self.gtr.optimal_t_compressed((pp, pc), self.multiplicity, profiles=True, tol=tol)
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 ------- branch_length : float branch length of the branch leading to the node. note: this can be unstable on iteration ''' if node.up is None: return self.one_mutation pp, pc = self.marginal_branch_profile(node) return self.gtr.optimal_t_compressed((pp, pc), self.multiplicity, profiles=True, tol=tol)
[ "calculate", "the", "marginal", "distribution", "of", "sequence", "states", "on", "both", "ends", "of", "the", "branch", "leading", "to", "node" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1835-L1855
[ "def", "optimal_marginal_branch_length", "(", "self", ",", "node", ",", "tol", "=", "1e-10", ")", ":", "if", "node", ".", "up", "is", "None", ":", "return", "self", ".", "one_mutation", "pp", ",", "pc", "=", "self", ".", "marginal_branch_profile", "(", "node", ")", "return", "self", ".", "gtr", ".", "optimal_t_compressed", "(", "(", "pp", ",", "pc", ")", ",", "self", ".", "multiplicity", ",", "profiles", "=", "True", ",", "tol", "=", "tol", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.prune_short_branches
If the branch length is less than the minimal value, remove the branch from the tree. **Requires** ancestral sequence reconstruction
treetime/treeanc.py
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 node in self.tree.find_clades(): if node.up is None or node.is_terminal(): continue # probability of the two seqs separated by zero time is not zero if self.gtr.prob_t(node.up.cseq, node.cseq, 0.0, pattern_multiplicity=self.multiplicity) > 0.1: # re-assign the node children directly to its parent node.up.clades = [k for k in node.up.clades if k != node] + node.clades for clade in node.clades: clade.up = node.up
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 node in self.tree.find_clades(): if node.up is None or node.is_terminal(): continue # probability of the two seqs separated by zero time is not zero if self.gtr.prob_t(node.up.cseq, node.cseq, 0.0, pattern_multiplicity=self.multiplicity) > 0.1: # re-assign the node children directly to its parent node.up.clades = [k for k in node.up.clades if k != node] + node.clades for clade in node.clades: clade.up = node.up
[ "If", "the", "branch", "length", "is", "less", "than", "the", "minimal", "value", "remove", "the", "branch", "from", "the", "tree", ".", "**", "Requires", "**", "ancestral", "sequence", "reconstruction" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1858-L1874
[ "def", "prune_short_branches", "(", "self", ")", ":", "self", ".", "logger", "(", "\"TreeAnc.prune_short_branches: pruning short branches (max prob at zero)...\"", ",", "1", ")", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "node", ".", "up", "is", "None", "or", "node", ".", "is_terminal", "(", ")", ":", "continue", "# probability of the two seqs separated by zero time is not zero", "if", "self", ".", "gtr", ".", "prob_t", "(", "node", ".", "up", ".", "cseq", ",", "node", ".", "cseq", ",", "0.0", ",", "pattern_multiplicity", "=", "self", ".", "multiplicity", ")", ">", "0.1", ":", "# re-assign the node children directly to its parent", "node", ".", "up", ".", "clades", "=", "[", "k", "for", "k", "in", "node", ".", "up", ".", "clades", "if", "k", "!=", "node", "]", "+", "node", ".", "clades", "for", "clade", "in", "node", ".", "clades", ":", "clade", ".", "up", "=", "node", ".", "up" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.optimize_seq_and_branch_len
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. The first step is to pre-reconstruct ancestral states using Fitch reconstruction algorithm or ML using existing branch length estimates. Then, optimize branch lengths and re-do reconstruction until convergence using ML method. Parameters ----------- reuse_branch_len : bool If True, rely on the initial branch lengths, and start with the maximum-likelihood ancestral sequence inference using existing branch lengths. Otherwise, do initial reconstruction of ancestral states with Fitch algorithm, which uses only the tree topology. prune_short : bool If True, the branches with zero optimal length will be pruned from the tree, creating polytomies. The polytomies could be further processed using :py:meth:`treetime.TreeTime.resolve_polytomies` from the TreeTime class. marginal_sequences : bool Assign sequences to their marginally most likely value, rather than the values that are jointly most likely across all nodes. branch_length_mode : str 'joint', 'marginal', or 'input'. Branch lengths are left unchanged in case of 'input'. 'joint' and 'marginal' cause branch length optimization while setting sequences to the ML value or tracing over all possible internal sequence states. max_iter : int Maximal number of times sequence and branch length iteration are optimized infer_gtr : bool Infer a GTR model from the observed substitutions.
treetime/treeanc.py
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 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. The first step is to pre-reconstruct ancestral states using Fitch reconstruction algorithm or ML using existing branch length estimates. Then, optimize branch lengths and re-do reconstruction until convergence using ML method. Parameters ----------- reuse_branch_len : bool If True, rely on the initial branch lengths, and start with the maximum-likelihood ancestral sequence inference using existing branch lengths. Otherwise, do initial reconstruction of ancestral states with Fitch algorithm, which uses only the tree topology. prune_short : bool If True, the branches with zero optimal length will be pruned from the tree, creating polytomies. The polytomies could be further processed using :py:meth:`treetime.TreeTime.resolve_polytomies` from the TreeTime class. marginal_sequences : bool Assign sequences to their marginally most likely value, rather than the values that are jointly most likely across all nodes. branch_length_mode : str 'joint', 'marginal', or 'input'. Branch lengths are left unchanged in case of 'input'. 'joint' and 'marginal' cause branch length optimization while setting sequences to the ML value or tracing over all possible internal sequence states. max_iter : int Maximal number of times sequence and branch length iteration are optimized infer_gtr : bool Infer a GTR model from the observed substitutions. """ if branch_length_mode=='marginal': marginal_sequences = True self.logger("TreeAnc.optimize_sequences_and_branch_length: sequences...", 1) if reuse_branch_len: N_diff = self.reconstruct_anc(method='probabilistic', infer_gtr=infer_gtr, marginal=marginal_sequences, **kwargs) self.optimize_branch_len(verbose=0, store_old=False, mode=branch_length_mode) else: N_diff = self.reconstruct_anc(method='fitch', infer_gtr=infer_gtr, **kwargs) self.optimize_branch_len(verbose=0, store_old=False, marginal=False) n = 0 while n<max_iter: n += 1 if prune_short: self.prune_short_branches() N_diff = self.reconstruct_anc(method='probabilistic', infer_gtr=False, marginal=marginal_sequences, **kwargs) self.logger("TreeAnc.optimize_sequences_and_branch_length: Iteration %d." " #Nuc changed since prev reconstructions: %d" %(n, N_diff), 2) if N_diff < 1: break self.optimize_branch_len(verbose=0, store_old=False, mode=branch_length_mode) self.tree.unconstrained_sequence_LH = (self.tree.sequence_LH*self.multiplicity).sum() self._prepare_nodes() # fix dist2root and up-links after reconstruction self.logger("TreeAnc.optimize_sequences_and_branch_length: Unconstrained sequence LH:%f" % self.tree.unconstrained_sequence_LH , 2) return ttconf.SUCCESS
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 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. The first step is to pre-reconstruct ancestral states using Fitch reconstruction algorithm or ML using existing branch length estimates. Then, optimize branch lengths and re-do reconstruction until convergence using ML method. Parameters ----------- reuse_branch_len : bool If True, rely on the initial branch lengths, and start with the maximum-likelihood ancestral sequence inference using existing branch lengths. Otherwise, do initial reconstruction of ancestral states with Fitch algorithm, which uses only the tree topology. prune_short : bool If True, the branches with zero optimal length will be pruned from the tree, creating polytomies. The polytomies could be further processed using :py:meth:`treetime.TreeTime.resolve_polytomies` from the TreeTime class. marginal_sequences : bool Assign sequences to their marginally most likely value, rather than the values that are jointly most likely across all nodes. branch_length_mode : str 'joint', 'marginal', or 'input'. Branch lengths are left unchanged in case of 'input'. 'joint' and 'marginal' cause branch length optimization while setting sequences to the ML value or tracing over all possible internal sequence states. max_iter : int Maximal number of times sequence and branch length iteration are optimized infer_gtr : bool Infer a GTR model from the observed substitutions. """ if branch_length_mode=='marginal': marginal_sequences = True self.logger("TreeAnc.optimize_sequences_and_branch_length: sequences...", 1) if reuse_branch_len: N_diff = self.reconstruct_anc(method='probabilistic', infer_gtr=infer_gtr, marginal=marginal_sequences, **kwargs) self.optimize_branch_len(verbose=0, store_old=False, mode=branch_length_mode) else: N_diff = self.reconstruct_anc(method='fitch', infer_gtr=infer_gtr, **kwargs) self.optimize_branch_len(verbose=0, store_old=False, marginal=False) n = 0 while n<max_iter: n += 1 if prune_short: self.prune_short_branches() N_diff = self.reconstruct_anc(method='probabilistic', infer_gtr=False, marginal=marginal_sequences, **kwargs) self.logger("TreeAnc.optimize_sequences_and_branch_length: Iteration %d." " #Nuc changed since prev reconstructions: %d" %(n, N_diff), 2) if N_diff < 1: break self.optimize_branch_len(verbose=0, store_old=False, mode=branch_length_mode) self.tree.unconstrained_sequence_LH = (self.tree.sequence_LH*self.multiplicity).sum() self._prepare_nodes() # fix dist2root and up-links after reconstruction self.logger("TreeAnc.optimize_sequences_and_branch_length: Unconstrained sequence LH:%f" % self.tree.unconstrained_sequence_LH , 2) return ttconf.SUCCESS
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1884-L1960
[ "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", ")", ":", "if", "branch_length_mode", "==", "'marginal'", ":", "marginal_sequences", "=", "True", "self", ".", "logger", "(", "\"TreeAnc.optimize_sequences_and_branch_length: sequences...\"", ",", "1", ")", "if", "reuse_branch_len", ":", "N_diff", "=", "self", ".", "reconstruct_anc", "(", "method", "=", "'probabilistic'", ",", "infer_gtr", "=", "infer_gtr", ",", "marginal", "=", "marginal_sequences", ",", "*", "*", "kwargs", ")", "self", ".", "optimize_branch_len", "(", "verbose", "=", "0", ",", "store_old", "=", "False", ",", "mode", "=", "branch_length_mode", ")", "else", ":", "N_diff", "=", "self", ".", "reconstruct_anc", "(", "method", "=", "'fitch'", ",", "infer_gtr", "=", "infer_gtr", ",", "*", "*", "kwargs", ")", "self", ".", "optimize_branch_len", "(", "verbose", "=", "0", ",", "store_old", "=", "False", ",", "marginal", "=", "False", ")", "n", "=", "0", "while", "n", "<", "max_iter", ":", "n", "+=", "1", "if", "prune_short", ":", "self", ".", "prune_short_branches", "(", ")", "N_diff", "=", "self", ".", "reconstruct_anc", "(", "method", "=", "'probabilistic'", ",", "infer_gtr", "=", "False", ",", "marginal", "=", "marginal_sequences", ",", "*", "*", "kwargs", ")", "self", ".", "logger", "(", "\"TreeAnc.optimize_sequences_and_branch_length: Iteration %d.\"", "\" #Nuc changed since prev reconstructions: %d\"", "%", "(", "n", ",", "N_diff", ")", ",", "2", ")", "if", "N_diff", "<", "1", ":", "break", "self", ".", "optimize_branch_len", "(", "verbose", "=", "0", ",", "store_old", "=", "False", ",", "mode", "=", "branch_length_mode", ")", "self", ".", "tree", ".", "unconstrained_sequence_LH", "=", "(", "self", ".", "tree", ".", "sequence_LH", "*", "self", ".", "multiplicity", ")", ".", "sum", "(", ")", "self", ".", "_prepare_nodes", "(", ")", "# fix dist2root and up-links after reconstruction", "self", ".", "logger", "(", "\"TreeAnc.optimize_sequences_and_branch_length: Unconstrained sequence LH:%f\"", "%", "self", ".", "tree", ".", "unconstrained_sequence_LH", ",", "2", ")", "return", "ttconf", ".", "SUCCESS" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.get_reconstructed_alignment
Get the multiple sequence alignment, including reconstructed sequences for the internal nodes. Returns ------- new_aln : MultipleSeqAlignment Alignment including sequences of all internal nodes
treetime/treeanc.py
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 """ from Bio.Align import MultipleSeqAlignment from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord self.logger("TreeAnc.get_reconstructed_alignment ...",2) if not hasattr(self.tree.root, 'sequence'): self.logger("TreeAnc.reconstructed_alignment... reconstruction not yet done",3) self.reconstruct_anc('probabilistic') new_aln = MultipleSeqAlignment([SeqRecord(id=n.name, seq=Seq("".join(n.sequence)), description="") for n in self.tree.find_clades()]) return new_aln
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 """ from Bio.Align import MultipleSeqAlignment from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord self.logger("TreeAnc.get_reconstructed_alignment ...",2) if not hasattr(self.tree.root, 'sequence'): self.logger("TreeAnc.reconstructed_alignment... reconstruction not yet done",3) self.reconstruct_anc('probabilistic') new_aln = MultipleSeqAlignment([SeqRecord(id=n.name, seq=Seq("".join(n.sequence)), description="") for n in self.tree.find_clades()]) return new_aln
[ "Get", "the", "multiple", "sequence", "alignment", "including", "reconstructed", "sequences", "for", "the", "internal", "nodes", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1966-L1988
[ "def", "get_reconstructed_alignment", "(", "self", ")", ":", "from", "Bio", ".", "Align", "import", "MultipleSeqAlignment", "from", "Bio", ".", "Seq", "import", "Seq", "from", "Bio", ".", "SeqRecord", "import", "SeqRecord", "self", ".", "logger", "(", "\"TreeAnc.get_reconstructed_alignment ...\"", ",", "2", ")", "if", "not", "hasattr", "(", "self", ".", "tree", ".", "root", ",", "'sequence'", ")", ":", "self", ".", "logger", "(", "\"TreeAnc.reconstructed_alignment... reconstruction not yet done\"", ",", "3", ")", "self", ".", "reconstruct_anc", "(", "'probabilistic'", ")", "new_aln", "=", "MultipleSeqAlignment", "(", "[", "SeqRecord", "(", "id", "=", "n", ".", "name", ",", "seq", "=", "Seq", "(", "\"\"", ".", "join", "(", "n", ".", "sequence", ")", ")", ",", "description", "=", "\"\"", ")", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", "]", ")", "return", "new_aln" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeAnc.get_tree_dict
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, generates dict sequences based on the *original* compressed sequences, which may include ambiguities. Note sites that only have 1 unambiguous base and ambiguous bases ("AAAAANN") are stripped of ambiguous bases *before* compression, so ambiguous bases at this sites will *not* be preserved. Returns ------- tree_dict : dict Format: :: { 'reference':'AGCTCGA...A', 'sequences': { 'seq1':{4:'A', 7:'-'}, 'seq2':{100:'C'} }, 'positions': [1,4,7,10,100...], 'inferred_const_sites': [7,100....] } reference: str The reference sequence to which the variable sites are mapped sequences: nested dict A dict for each sequence with the position and alternative call for each variant positions: list All variable positions in the alignment inferred_cost_sites: list *(optional)* Positions that were constant except ambiguous bases, which were converted into constant sites by TreeAnc (ex: 'AAAN' -> 'AAAA') Raises ------ TypeError Description
treetime/treeanc.py
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, generates dict sequences based on the *original* compressed sequences, which may include ambiguities. Note sites that only have 1 unambiguous base and ambiguous bases ("AAAAANN") are stripped of ambiguous bases *before* compression, so ambiguous bases at this sites will *not* be preserved. Returns ------- tree_dict : dict Format: :: { 'reference':'AGCTCGA...A', 'sequences': { 'seq1':{4:'A', 7:'-'}, 'seq2':{100:'C'} }, 'positions': [1,4,7,10,100...], 'inferred_const_sites': [7,100....] } reference: str The reference sequence to which the variable sites are mapped sequences: nested dict A dict for each sequence with the position and alternative call for each variant positions: list All variable positions in the alignment inferred_cost_sites: list *(optional)* Positions that were constant except ambiguous bases, which were converted into constant sites by TreeAnc (ex: 'AAAN' -> 'AAAA') Raises ------ TypeError Description """ if self.is_vcf: tree_dict = {} tree_dict['reference'] = self.ref tree_dict['positions'] = self.nonref_positions tree_aln = {} for n in self.tree.find_clades(): if hasattr(n, 'sequence'): if keep_var_ambigs: #regenerate dict to include ambig bases tree_aln[n.name] = self.dict_sequence(n, keep_var_ambigs) else: tree_aln[n.name] = n.sequence tree_dict['sequences'] = tree_aln if len(self.inferred_const_sites) != 0: tree_dict['inferred_const_sites'] = self.inferred_const_sites return tree_dict else: raise TypeError("A dict can only be returned for trees created with VCF-input!")
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, generates dict sequences based on the *original* compressed sequences, which may include ambiguities. Note sites that only have 1 unambiguous base and ambiguous bases ("AAAAANN") are stripped of ambiguous bases *before* compression, so ambiguous bases at this sites will *not* be preserved. Returns ------- tree_dict : dict Format: :: { 'reference':'AGCTCGA...A', 'sequences': { 'seq1':{4:'A', 7:'-'}, 'seq2':{100:'C'} }, 'positions': [1,4,7,10,100...], 'inferred_const_sites': [7,100....] } reference: str The reference sequence to which the variable sites are mapped sequences: nested dict A dict for each sequence with the position and alternative call for each variant positions: list All variable positions in the alignment inferred_cost_sites: list *(optional)* Positions that were constant except ambiguous bases, which were converted into constant sites by TreeAnc (ex: 'AAAN' -> 'AAAA') Raises ------ TypeError Description """ if self.is_vcf: tree_dict = {} tree_dict['reference'] = self.ref tree_dict['positions'] = self.nonref_positions tree_aln = {} for n in self.tree.find_clades(): if hasattr(n, 'sequence'): if keep_var_ambigs: #regenerate dict to include ambig bases tree_aln[n.name] = self.dict_sequence(n, keep_var_ambigs) else: tree_aln[n.name] = n.sequence tree_dict['sequences'] = tree_aln if len(self.inferred_const_sites) != 0: tree_dict['inferred_const_sites'] = self.inferred_const_sites return tree_dict else: raise TypeError("A dict can only be returned for trees created with VCF-input!")
[ "For", "VCF", "-", "based", "objects", "returns", "a", "nested", "dict", "with", "all", "the", "information", "required", "to", "reconstruct", "sequences", "for", "all", "nodes", "(", "terminal", "and", "internal", ")", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treeanc.py#L1991-L2053
[ "def", "get_tree_dict", "(", "self", ",", "keep_var_ambigs", "=", "False", ")", ":", "if", "self", ".", "is_vcf", ":", "tree_dict", "=", "{", "}", "tree_dict", "[", "'reference'", "]", "=", "self", ".", "ref", "tree_dict", "[", "'positions'", "]", "=", "self", ".", "nonref_positions", "tree_aln", "=", "{", "}", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "hasattr", "(", "n", ",", "'sequence'", ")", ":", "if", "keep_var_ambigs", ":", "#regenerate dict to include ambig bases", "tree_aln", "[", "n", ".", "name", "]", "=", "self", ".", "dict_sequence", "(", "n", ",", "keep_var_ambigs", ")", "else", ":", "tree_aln", "[", "n", ".", "name", "]", "=", "n", ".", "sequence", "tree_dict", "[", "'sequences'", "]", "=", "tree_aln", "if", "len", "(", "self", ".", "inferred_const_sites", ")", "!=", "0", ":", "tree_dict", "[", "'inferred_const_sites'", "]", "=", "self", ".", "inferred_const_sites", "return", "tree_dict", "else", ":", "raise", "TypeError", "(", "\"A dict can only be returned for trees created with VCF-input!\"", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR_site_specific.Q
function that return the product of the transition matrix and the equilibrium frequencies to obtain the rate matrix of the GTR model
treetime/gtr_site_specific.py
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[-1]): np.fill_diagonal(tmp[:,:,x], -diag_vals[:,x]) return tmp
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[-1]): np.fill_diagonal(tmp[:,:,x], -diag_vals[:,x]) return tmp
[ "function", "that", "return", "the", "product", "of", "the", "transition", "matrix", "and", "the", "equilibrium", "frequencies", "to", "obtain", "the", "rate", "matrix", "of", "the", "GTR", "model" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr_site_specific.py#L22-L31
[ "def", "Q", "(", "self", ")", ":", "tmp", "=", "np", ".", "einsum", "(", "'ia,ij->ija'", ",", "self", ".", "Pi", ",", "self", ".", "W", ")", "diag_vals", "=", "np", ".", "sum", "(", "tmp", ",", "axis", "=", "0", ")", "for", "x", "in", "range", "(", "tmp", ".", "shape", "[", "-", "1", "]", ")", ":", "np", ".", "fill_diagonal", "(", "tmp", "[", ":", ",", ":", ",", "x", "]", ",", "-", "diag_vals", "[", ":", ",", "x", "]", ")", "return", "tmp" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR_site_specific.assign_rates
Overwrite the GTR model given the provided data Parameters ---------- mu : float Substitution rate W : nxn matrix Substitution matrix pi : n vector Equilibrium frequencies
treetime/gtr_site_specific.py
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 frequencies """ n = len(self.alphabet) self.mu = np.copy(mu) if pi is not None and pi.shape[0]==n: self.seq_len = pi.shape[-1] Pi = np.copy(pi) else: if pi is not None and len(pi)!=n: self.logger("length of equilibrium frequency vector does not match alphabet length", 4, warn=True) self.logger("Ignoring input equilibrium frequencies", 4, warn=True) Pi = np.ones(shape=(n,self.seq_len)) self.Pi = Pi/np.sum(Pi, axis=0) if W is None or W.shape!=(n,n): if (W is not None) and W.shape!=(n,n): self.logger("Substitution matrix size does not match alphabet size", 4, warn=True) self.logger("Ignoring input substitution matrix", 4, warn=True) # flow matrix W = np.ones((n,n)) else: W=0.5*(np.copy(W)+np.copy(W).T) np.fill_diagonal(W,0) avg_pi = self.Pi.mean(axis=-1) average_rate = W.dot(avg_pi).dot(avg_pi) self.W = W/average_rate self.mu *=average_rate self._eig()
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 frequencies """ n = len(self.alphabet) self.mu = np.copy(mu) if pi is not None and pi.shape[0]==n: self.seq_len = pi.shape[-1] Pi = np.copy(pi) else: if pi is not None and len(pi)!=n: self.logger("length of equilibrium frequency vector does not match alphabet length", 4, warn=True) self.logger("Ignoring input equilibrium frequencies", 4, warn=True) Pi = np.ones(shape=(n,self.seq_len)) self.Pi = Pi/np.sum(Pi, axis=0) if W is None or W.shape!=(n,n): if (W is not None) and W.shape!=(n,n): self.logger("Substitution matrix size does not match alphabet size", 4, warn=True) self.logger("Ignoring input substitution matrix", 4, warn=True) # flow matrix W = np.ones((n,n)) else: W=0.5*(np.copy(W)+np.copy(W).T) np.fill_diagonal(W,0) avg_pi = self.Pi.mean(axis=-1) average_rate = W.dot(avg_pi).dot(avg_pi) self.W = W/average_rate self.mu *=average_rate self._eig()
[ "Overwrite", "the", "GTR", "model", "given", "the", "provided", "data" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr_site_specific.py#L33-L79
[ "def", "assign_rates", "(", "self", ",", "mu", "=", "1.0", ",", "pi", "=", "None", ",", "W", "=", "None", ")", ":", "n", "=", "len", "(", "self", ".", "alphabet", ")", "self", ".", "mu", "=", "np", ".", "copy", "(", "mu", ")", "if", "pi", "is", "not", "None", "and", "pi", ".", "shape", "[", "0", "]", "==", "n", ":", "self", ".", "seq_len", "=", "pi", ".", "shape", "[", "-", "1", "]", "Pi", "=", "np", ".", "copy", "(", "pi", ")", "else", ":", "if", "pi", "is", "not", "None", "and", "len", "(", "pi", ")", "!=", "n", ":", "self", ".", "logger", "(", "\"length of equilibrium frequency vector does not match alphabet length\"", ",", "4", ",", "warn", "=", "True", ")", "self", ".", "logger", "(", "\"Ignoring input equilibrium frequencies\"", ",", "4", ",", "warn", "=", "True", ")", "Pi", "=", "np", ".", "ones", "(", "shape", "=", "(", "n", ",", "self", ".", "seq_len", ")", ")", "self", ".", "Pi", "=", "Pi", "/", "np", ".", "sum", "(", "Pi", ",", "axis", "=", "0", ")", "if", "W", "is", "None", "or", "W", ".", "shape", "!=", "(", "n", ",", "n", ")", ":", "if", "(", "W", "is", "not", "None", ")", "and", "W", ".", "shape", "!=", "(", "n", ",", "n", ")", ":", "self", ".", "logger", "(", "\"Substitution matrix size does not match alphabet size\"", ",", "4", ",", "warn", "=", "True", ")", "self", ".", "logger", "(", "\"Ignoring input substitution matrix\"", ",", "4", ",", "warn", "=", "True", ")", "# flow matrix", "W", "=", "np", ".", "ones", "(", "(", "n", ",", "n", ")", ")", "else", ":", "W", "=", "0.5", "*", "(", "np", ".", "copy", "(", "W", ")", "+", "np", ".", "copy", "(", "W", ")", ".", "T", ")", "np", ".", "fill_diagonal", "(", "W", ",", "0", ")", "avg_pi", "=", "self", ".", "Pi", ".", "mean", "(", "axis", "=", "-", "1", ")", "average_rate", "=", "W", ".", "dot", "(", "avg_pi", ")", ".", "dot", "(", "avg_pi", ")", "self", ".", "W", "=", "W", "/", "average_rate", "self", ".", "mu", "*=", "average_rate", "self", ".", "_eig", "(", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR_site_specific.random
Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (should be standard: 'nuc', 'nuc_gap', 'aa', 'aa_gap')
treetime/gtr_site_specific.py
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 (should be standard: 'nuc', 'nuc_gap', 'aa', 'aa_gap') """ from scipy.stats import gamma alphabet=alphabets[alphabet] gtr = cls(alphabet=alphabet, seq_len=L) n = gtr.alphabet.shape[0] if pi_dirichlet_alpha: pi = 1.0*gamma.rvs(pi_dirichlet_alpha, size=(n,L)) else: pi = np.ones((n,L)) pi /= pi.sum(axis=0) if W_dirichlet_alpha: tmp = 1.0*gamma.rvs(W_dirichlet_alpha, size=(n,n)) else: tmp = np.ones((n,n)) tmp = np.tril(tmp,k=-1) W = tmp + tmp.T if mu_gamma_alpha: mu = gamma.rvs(mu_gamma_alpha, size=(L,)) else: mu = np.ones(L) gtr.assign_rates(mu=mu, pi=pi, W=W) gtr.mu *= avg_mu/np.mean(gtr.mu) return gtr
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 (should be standard: 'nuc', 'nuc_gap', 'aa', 'aa_gap') """ from scipy.stats import gamma alphabet=alphabets[alphabet] gtr = cls(alphabet=alphabet, seq_len=L) n = gtr.alphabet.shape[0] if pi_dirichlet_alpha: pi = 1.0*gamma.rvs(pi_dirichlet_alpha, size=(n,L)) else: pi = np.ones((n,L)) pi /= pi.sum(axis=0) if W_dirichlet_alpha: tmp = 1.0*gamma.rvs(W_dirichlet_alpha, size=(n,n)) else: tmp = np.ones((n,n)) tmp = np.tril(tmp,k=-1) W = tmp + tmp.T if mu_gamma_alpha: mu = gamma.rvs(mu_gamma_alpha, size=(L,)) else: mu = np.ones(L) gtr.assign_rates(mu=mu, pi=pi, W=W) gtr.mu *= avg_mu/np.mean(gtr.mu) return gtr
[ "Creates", "a", "random", "GTR", "model" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr_site_specific.py#L83-L125
[ "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", ")", ":", "from", "scipy", ".", "stats", "import", "gamma", "alphabet", "=", "alphabets", "[", "alphabet", "]", "gtr", "=", "cls", "(", "alphabet", "=", "alphabet", ",", "seq_len", "=", "L", ")", "n", "=", "gtr", ".", "alphabet", ".", "shape", "[", "0", "]", "if", "pi_dirichlet_alpha", ":", "pi", "=", "1.0", "*", "gamma", ".", "rvs", "(", "pi_dirichlet_alpha", ",", "size", "=", "(", "n", ",", "L", ")", ")", "else", ":", "pi", "=", "np", ".", "ones", "(", "(", "n", ",", "L", ")", ")", "pi", "/=", "pi", ".", "sum", "(", "axis", "=", "0", ")", "if", "W_dirichlet_alpha", ":", "tmp", "=", "1.0", "*", "gamma", ".", "rvs", "(", "W_dirichlet_alpha", ",", "size", "=", "(", "n", ",", "n", ")", ")", "else", ":", "tmp", "=", "np", ".", "ones", "(", "(", "n", ",", "n", ")", ")", "tmp", "=", "np", ".", "tril", "(", "tmp", ",", "k", "=", "-", "1", ")", "W", "=", "tmp", "+", "tmp", ".", "T", "if", "mu_gamma_alpha", ":", "mu", "=", "gamma", ".", "rvs", "(", "mu_gamma_alpha", ",", "size", "=", "(", "L", ",", ")", ")", "else", ":", "mu", "=", "np", ".", "ones", "(", "L", ")", "gtr", ".", "assign_rates", "(", "mu", "=", "mu", ",", "pi", "=", "pi", ",", "W", "=", "W", ")", "gtr", ".", "mu", "*=", "avg_mu", "/", "np", ".", "mean", "(", "gtr", ".", "mu", ")", "return", "gtr" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR_site_specific.custom
Create a GTR model by specifying the matrix explicitly Parameters ---------- mu : float Substitution rate W : nxn matrix Substitution matrix pi : n vector Equilibrium frequencies **kwargs: Key word arguments to be passed Keyword Args ------------ alphabet : str Specify alphabet when applicable. If the alphabet specification is required, but no alphabet is specified, the nucleotide alphabet will be used as default.
treetime/gtr_site_specific.py
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 Equilibrium frequencies **kwargs: Key word arguments to be passed Keyword Args ------------ alphabet : str Specify alphabet when applicable. If the alphabet specification is required, but no alphabet is specified, the nucleotide alphabet will be used as default. """ gtr = cls(**kwargs) gtr.assign_rates(mu=mu, pi=pi, W=W) return gtr
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 Equilibrium frequencies **kwargs: Key word arguments to be passed Keyword Args ------------ alphabet : str Specify alphabet when applicable. If the alphabet specification is required, but no alphabet is specified, the nucleotide alphabet will be used as default. """ gtr = cls(**kwargs) gtr.assign_rates(mu=mu, pi=pi, W=W) return gtr
[ "Create", "a", "GTR", "model", "by", "specifying", "the", "matrix", "explicitly" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr_site_specific.py#L128-L158
[ "def", "custom", "(", "cls", ",", "mu", "=", "1.0", ",", "pi", "=", "None", ",", "W", "=", "None", ",", "*", "*", "kwargs", ")", ":", "gtr", "=", "cls", "(", "*", "*", "kwargs", ")", "gtr", ".", "assign_rates", "(", "mu", "=", "mu", ",", "pi", "=", "pi", ",", "W", "=", "W", ")", "return", "gtr" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR_site_specific.infer
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}` are the transitions, :math:`pi_i` are the equilibrium state frequencies, :math:`W_{ij}` is the "substitution attempt matrix", while :math:`T_i` is the time on the tree spent in character state :math:`i`. To regularize the process, we add pseudocounts and also need to account for the fact that the root of the tree is in a particular state. the modified equation is :math:`n_{ij} + pc = pi_i W_{ij} (T_j+pc+root\_state)` Parameters ---------- nija : nxn matrix The number of times a change in character state is observed between state j and i at position a Tia :n vector The time spent in each character state at position a root_state : n vector The number of characters in state i in the sequence of the root node. pc : float Pseudocounts, this determines the lower cutoff on the rate when no substitutions are observed **kwargs: Key word arguments to be passed Keyword Args ------------ alphabet : str Specify alphabet when applicable. If the alphabet specification is required, but no alphabet is specified, the nucleotide alphabet will be used as default.
treetime/gtr_site_specific.py
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` where :math:`n_{ij}` are the transitions, :math:`pi_i` are the equilibrium state frequencies, :math:`W_{ij}` is the "substitution attempt matrix", while :math:`T_i` is the time on the tree spent in character state :math:`i`. To regularize the process, we add pseudocounts and also need to account for the fact that the root of the tree is in a particular state. the modified equation is :math:`n_{ij} + pc = pi_i W_{ij} (T_j+pc+root\_state)` Parameters ---------- nija : nxn matrix The number of times a change in character state is observed between state j and i at position a Tia :n vector The time spent in each character state at position a root_state : n vector The number of characters in state i in the sequence of the root node. pc : float Pseudocounts, this determines the lower cutoff on the rate when no substitutions are observed **kwargs: Key word arguments to be passed Keyword Args ------------ alphabet : str Specify alphabet when applicable. If the alphabet specification is required, but no alphabet is specified, the nucleotide alphabet will be used as default. """ from scipy import linalg as LA gtr = cls(**kwargs) gtr.logger("GTR: model inference ",1) q = len(gtr.alphabet) L = sub_ija.shape[-1] n_iter = 0 n_ija = np.copy(sub_ija) n_ija[range(q),range(q),:] = 0 n_ij = n_ija.sum(axis=-1) m_ia = np.sum(n_ija,axis=1) + root_state + pc n_a = n_ija.sum(axis=1).sum(axis=0) + pc Lambda = np.sum(root_state,axis=0) + q*pc p_ia_old=np.zeros((q,L)) p_ia = np.ones((q,L))/q mu_a = np.ones(L) W_ij = np.ones((q,q)) - np.eye(q) while (LA.norm(p_ia_old-p_ia)>dp) and n_iter<Nit: n_iter += 1 p_ia_old = np.copy(p_ia) S_ij = np.einsum('a,ia,ja',mu_a, p_ia, T_ia) W_ij = (n_ij + n_ij.T + pc)/(S_ij + S_ij.T + pc) avg_pi = p_ia.mean(axis=-1) average_rate = W_ij.dot(avg_pi).dot(avg_pi) W_ij = W_ij/average_rate mu_a *=average_rate p_ia = m_ia/(mu_a*np.dot(W_ij,T_ia)+Lambda) p_ia = p_ia/p_ia.sum(axis=0) mu_a = n_a/(pc+np.einsum('ia,ij,ja->a', p_ia, W_ij, T_ia)) if n_iter >= Nit: gtr.logger('WARNING: maximum number of iterations has been reached in GTR inference',3, warn=True) if LA.norm(p_ia_old-p_ia) > dp: gtr.logger('the iterative scheme has not converged',3,warn=True) if gtr.gap_index is not None: for p in range(p_ia.shape[-1]): if p_ia[gtr.gap_index,p]<gap_limit: gtr.logger('The model allows for gaps which are estimated to occur at a low fraction of %1.3e'%p_ia[gtr.gap_index]+ '\n\t\tthis can potentially result in artificats.'+ '\n\t\tgap fraction will be set to %1.4f'%gap_limit,2,warn=True) p_ia[gtr.gap_index,p] = gap_limit p_ia[:,p] /= p_ia[:,p].sum() gtr.assign_rates(mu=mu_a, W=W_ij, pi=p_ia) return gtr
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` where :math:`n_{ij}` are the transitions, :math:`pi_i` are the equilibrium state frequencies, :math:`W_{ij}` is the "substitution attempt matrix", while :math:`T_i` is the time on the tree spent in character state :math:`i`. To regularize the process, we add pseudocounts and also need to account for the fact that the root of the tree is in a particular state. the modified equation is :math:`n_{ij} + pc = pi_i W_{ij} (T_j+pc+root\_state)` Parameters ---------- nija : nxn matrix The number of times a change in character state is observed between state j and i at position a Tia :n vector The time spent in each character state at position a root_state : n vector The number of characters in state i in the sequence of the root node. pc : float Pseudocounts, this determines the lower cutoff on the rate when no substitutions are observed **kwargs: Key word arguments to be passed Keyword Args ------------ alphabet : str Specify alphabet when applicable. If the alphabet specification is required, but no alphabet is specified, the nucleotide alphabet will be used as default. """ from scipy import linalg as LA gtr = cls(**kwargs) gtr.logger("GTR: model inference ",1) q = len(gtr.alphabet) L = sub_ija.shape[-1] n_iter = 0 n_ija = np.copy(sub_ija) n_ija[range(q),range(q),:] = 0 n_ij = n_ija.sum(axis=-1) m_ia = np.sum(n_ija,axis=1) + root_state + pc n_a = n_ija.sum(axis=1).sum(axis=0) + pc Lambda = np.sum(root_state,axis=0) + q*pc p_ia_old=np.zeros((q,L)) p_ia = np.ones((q,L))/q mu_a = np.ones(L) W_ij = np.ones((q,q)) - np.eye(q) while (LA.norm(p_ia_old-p_ia)>dp) and n_iter<Nit: n_iter += 1 p_ia_old = np.copy(p_ia) S_ij = np.einsum('a,ia,ja',mu_a, p_ia, T_ia) W_ij = (n_ij + n_ij.T + pc)/(S_ij + S_ij.T + pc) avg_pi = p_ia.mean(axis=-1) average_rate = W_ij.dot(avg_pi).dot(avg_pi) W_ij = W_ij/average_rate mu_a *=average_rate p_ia = m_ia/(mu_a*np.dot(W_ij,T_ia)+Lambda) p_ia = p_ia/p_ia.sum(axis=0) mu_a = n_a/(pc+np.einsum('ia,ij,ja->a', p_ia, W_ij, T_ia)) if n_iter >= Nit: gtr.logger('WARNING: maximum number of iterations has been reached in GTR inference',3, warn=True) if LA.norm(p_ia_old-p_ia) > dp: gtr.logger('the iterative scheme has not converged',3,warn=True) if gtr.gap_index is not None: for p in range(p_ia.shape[-1]): if p_ia[gtr.gap_index,p]<gap_limit: gtr.logger('The model allows for gaps which are estimated to occur at a low fraction of %1.3e'%p_ia[gtr.gap_index]+ '\n\t\tthis can potentially result in artificats.'+ '\n\t\tgap fraction will be set to %1.4f'%gap_limit,2,warn=True) p_ia[gtr.gap_index,p] = gap_limit p_ia[:,p] /= p_ia[:,p].sum() gtr.assign_rates(mu=mu_a, W=W_ij, pi=p_ia) return gtr
[ "Infer", "a", "GTR", "model", "by", "specifying", "the", "number", "of", "transitions", "and", "time", "spent", "in", "each", "character", ".", "The", "basic", "equation", "that", "is", "being", "solved", "is" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr_site_specific.py#L161-L258
[ "def", "infer", "(", "cls", ",", "sub_ija", ",", "T_ia", ",", "root_state", ",", "pc", "=", "0.01", ",", "gap_limit", "=", "0.01", ",", "Nit", "=", "30", ",", "dp", "=", "1e-5", ",", "*", "*", "kwargs", ")", ":", "from", "scipy", "import", "linalg", "as", "LA", "gtr", "=", "cls", "(", "*", "*", "kwargs", ")", "gtr", ".", "logger", "(", "\"GTR: model inference \"", ",", "1", ")", "q", "=", "len", "(", "gtr", ".", "alphabet", ")", "L", "=", "sub_ija", ".", "shape", "[", "-", "1", "]", "n_iter", "=", "0", "n_ija", "=", "np", ".", "copy", "(", "sub_ija", ")", "n_ija", "[", "range", "(", "q", ")", ",", "range", "(", "q", ")", ",", ":", "]", "=", "0", "n_ij", "=", "n_ija", ".", "sum", "(", "axis", "=", "-", "1", ")", "m_ia", "=", "np", ".", "sum", "(", "n_ija", ",", "axis", "=", "1", ")", "+", "root_state", "+", "pc", "n_a", "=", "n_ija", ".", "sum", "(", "axis", "=", "1", ")", ".", "sum", "(", "axis", "=", "0", ")", "+", "pc", "Lambda", "=", "np", ".", "sum", "(", "root_state", ",", "axis", "=", "0", ")", "+", "q", "*", "pc", "p_ia_old", "=", "np", ".", "zeros", "(", "(", "q", ",", "L", ")", ")", "p_ia", "=", "np", ".", "ones", "(", "(", "q", ",", "L", ")", ")", "/", "q", "mu_a", "=", "np", ".", "ones", "(", "L", ")", "W_ij", "=", "np", ".", "ones", "(", "(", "q", ",", "q", ")", ")", "-", "np", ".", "eye", "(", "q", ")", "while", "(", "LA", ".", "norm", "(", "p_ia_old", "-", "p_ia", ")", ">", "dp", ")", "and", "n_iter", "<", "Nit", ":", "n_iter", "+=", "1", "p_ia_old", "=", "np", ".", "copy", "(", "p_ia", ")", "S_ij", "=", "np", ".", "einsum", "(", "'a,ia,ja'", ",", "mu_a", ",", "p_ia", ",", "T_ia", ")", "W_ij", "=", "(", "n_ij", "+", "n_ij", ".", "T", "+", "pc", ")", "/", "(", "S_ij", "+", "S_ij", ".", "T", "+", "pc", ")", "avg_pi", "=", "p_ia", ".", "mean", "(", "axis", "=", "-", "1", ")", "average_rate", "=", "W_ij", ".", "dot", "(", "avg_pi", ")", ".", "dot", "(", "avg_pi", ")", "W_ij", "=", "W_ij", "/", "average_rate", "mu_a", "*=", "average_rate", "p_ia", "=", "m_ia", "/", "(", "mu_a", "*", "np", ".", "dot", "(", "W_ij", ",", "T_ia", ")", "+", "Lambda", ")", "p_ia", "=", "p_ia", "/", "p_ia", ".", "sum", "(", "axis", "=", "0", ")", "mu_a", "=", "n_a", "/", "(", "pc", "+", "np", ".", "einsum", "(", "'ia,ij,ja->a'", ",", "p_ia", ",", "W_ij", ",", "T_ia", ")", ")", "if", "n_iter", ">=", "Nit", ":", "gtr", ".", "logger", "(", "'WARNING: maximum number of iterations has been reached in GTR inference'", ",", "3", ",", "warn", "=", "True", ")", "if", "LA", ".", "norm", "(", "p_ia_old", "-", "p_ia", ")", ">", "dp", ":", "gtr", ".", "logger", "(", "'the iterative scheme has not converged'", ",", "3", ",", "warn", "=", "True", ")", "if", "gtr", ".", "gap_index", "is", "not", "None", ":", "for", "p", "in", "range", "(", "p_ia", ".", "shape", "[", "-", "1", "]", ")", ":", "if", "p_ia", "[", "gtr", ".", "gap_index", ",", "p", "]", "<", "gap_limit", ":", "gtr", ".", "logger", "(", "'The model allows for gaps which are estimated to occur at a low fraction of %1.3e'", "%", "p_ia", "[", "gtr", ".", "gap_index", "]", "+", "'\\n\\t\\tthis can potentially result in artificats.'", "+", "'\\n\\t\\tgap fraction will be set to %1.4f'", "%", "gap_limit", ",", "2", ",", "warn", "=", "True", ")", "p_ia", "[", "gtr", ".", "gap_index", ",", "p", "]", "=", "gap_limit", "p_ia", "[", ":", ",", "p", "]", "/=", "p_ia", "[", ":", ",", "p", "]", ".", "sum", "(", ")", "gtr", ".", "assign_rates", "(", "mu", "=", "mu_a", ",", "W", "=", "W_ij", ",", "pi", "=", "p_ia", ")", "return", "gtr" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR_site_specific.prob_t
Compute the probability to observe seq_ch (child sequence) after time t starting from seq_p (parent sequence). Parameters ---------- seq_p : character array Parent sequence seq_c : character array Child sequence t : double Time (branch len) separating the profiles. pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. return_log : bool It True, return log-probability. Returns ------- prob : np.array Resulting probability
treetime/gtr_site_specific.py
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 : character array Parent sequence seq_c : character array Child sequence t : double Time (branch len) separating the profiles. pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. return_log : bool It True, return log-probability. Returns ------- prob : np.array Resulting probability """ if t<0: logP = -ttconf.BIG_NUMBER else: tmp_eQT = self.expQt(t) bad_indices=(tmp_eQT==0) logQt = np.log(tmp_eQT + ttconf.TINY_NUMBER*(bad_indices)) logQt[np.isnan(logQt) | np.isinf(logQt) | bad_indices] = -ttconf.BIG_NUMBER seq_indices_c = np.zeros(len(seq_ch), dtype=int) seq_indices_p = np.zeros(len(seq_p), dtype=int) for ai, a in self.alphabet: seq_indices_p[seq_p==a] = ai seq_indices_c[seq_ch==a] = ai if len(logQt.shape)==2: logP = np.sum(logQt[seq_indices_p, seq_indices_c]*pattern_multiplicity) else: logP = np.sum(logQt[seq_indices_p, seq_indices_c, np.arange(len(seq_c))]*pattern_multiplicity) return logP if return_log else np.exp(logP)
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 : character array Parent sequence seq_c : character array Child sequence t : double Time (branch len) separating the profiles. pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. return_log : bool It True, return log-probability. Returns ------- prob : np.array Resulting probability """ if t<0: logP = -ttconf.BIG_NUMBER else: tmp_eQT = self.expQt(t) bad_indices=(tmp_eQT==0) logQt = np.log(tmp_eQT + ttconf.TINY_NUMBER*(bad_indices)) logQt[np.isnan(logQt) | np.isinf(logQt) | bad_indices] = -ttconf.BIG_NUMBER seq_indices_c = np.zeros(len(seq_ch), dtype=int) seq_indices_p = np.zeros(len(seq_p), dtype=int) for ai, a in self.alphabet: seq_indices_p[seq_p==a] = ai seq_indices_c[seq_ch==a] = ai if len(logQt.shape)==2: logP = np.sum(logQt[seq_indices_p, seq_indices_c]*pattern_multiplicity) else: logP = np.sum(logQt[seq_indices_p, seq_indices_c, np.arange(len(seq_c))]*pattern_multiplicity) return logP if return_log else np.exp(logP)
[ "Compute", "the", "probability", "to", "observe", "seq_ch", "(", "child", "sequence", ")", "after", "time", "t", "starting", "from", "seq_p", "(", "parent", "sequence", ")", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr_site_specific.py#L366-L417
[ "def", "prob_t", "(", "self", ",", "seq_p", ",", "seq_ch", ",", "t", ",", "pattern_multiplicity", "=", "None", ",", "return_log", "=", "False", ",", "ignore_gaps", "=", "True", ")", ":", "if", "t", "<", "0", ":", "logP", "=", "-", "ttconf", ".", "BIG_NUMBER", "else", ":", "tmp_eQT", "=", "self", ".", "expQt", "(", "t", ")", "bad_indices", "=", "(", "tmp_eQT", "==", "0", ")", "logQt", "=", "np", ".", "log", "(", "tmp_eQT", "+", "ttconf", ".", "TINY_NUMBER", "*", "(", "bad_indices", ")", ")", "logQt", "[", "np", ".", "isnan", "(", "logQt", ")", "|", "np", ".", "isinf", "(", "logQt", ")", "|", "bad_indices", "]", "=", "-", "ttconf", ".", "BIG_NUMBER", "seq_indices_c", "=", "np", ".", "zeros", "(", "len", "(", "seq_ch", ")", ",", "dtype", "=", "int", ")", "seq_indices_p", "=", "np", ".", "zeros", "(", "len", "(", "seq_p", ")", ",", "dtype", "=", "int", ")", "for", "ai", ",", "a", "in", "self", ".", "alphabet", ":", "seq_indices_p", "[", "seq_p", "==", "a", "]", "=", "ai", "seq_indices_c", "[", "seq_ch", "==", "a", "]", "=", "ai", "if", "len", "(", "logQt", ".", "shape", ")", "==", "2", ":", "logP", "=", "np", ".", "sum", "(", "logQt", "[", "seq_indices_p", ",", "seq_indices_c", "]", "*", "pattern_multiplicity", ")", "else", ":", "logP", "=", "np", ".", "sum", "(", "logQt", "[", "seq_indices_p", ",", "seq_indices_c", ",", "np", ".", "arange", "(", "len", "(", "seq_c", ")", ")", "]", "*", "pattern_multiplicity", ")", "return", "logP", "if", "return_log", "else", "np", ".", "exp", "(", "logP", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.assign_rates
Overwrite the GTR model given the provided data Parameters ---------- mu : float Substitution rate W : nxn matrix Substitution matrix pi : n vector Equilibrium frequencies
treetime/gtr.py
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 frequencies """ n = len(self.alphabet) self.mu = mu if pi is not None and len(pi)==n: Pi = np.array(pi) else: if pi is not None and len(pi)!=n: self.logger("length of equilibrium frequency vector does not match alphabet length", 4, warn=True) self.logger("Ignoring input equilibrium frequencies", 4, warn=True) Pi = np.ones(shape=(n,)) self.Pi = Pi/np.sum(Pi) if W is None or W.shape!=(n,n): if (W is not None) and W.shape!=(n,n): self.logger("Substitution matrix size does not match alphabet size", 4, warn=True) self.logger("Ignoring input substitution matrix", 4, warn=True) # flow matrix W = np.ones((n,n)) np.fill_diagonal(W, 0.0) np.fill_diagonal(W, - W.sum(axis=0)) else: W=np.array(W) self.W = 0.5*(W+W.T) self._check_fix_Q(fixed_mu=True) self._eig()
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 frequencies """ n = len(self.alphabet) self.mu = mu if pi is not None and len(pi)==n: Pi = np.array(pi) else: if pi is not None and len(pi)!=n: self.logger("length of equilibrium frequency vector does not match alphabet length", 4, warn=True) self.logger("Ignoring input equilibrium frequencies", 4, warn=True) Pi = np.ones(shape=(n,)) self.Pi = Pi/np.sum(Pi) if W is None or W.shape!=(n,n): if (W is not None) and W.shape!=(n,n): self.logger("Substitution matrix size does not match alphabet size", 4, warn=True) self.logger("Ignoring input substitution matrix", 4, warn=True) # flow matrix W = np.ones((n,n)) np.fill_diagonal(W, 0.0) np.fill_diagonal(W, - W.sum(axis=0)) else: W=np.array(W) self.W = 0.5*(W+W.T) self._check_fix_Q(fixed_mu=True) self._eig()
[ "Overwrite", "the", "GTR", "model", "given", "the", "provided", "data" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L149-L192
[ "def", "assign_rates", "(", "self", ",", "mu", "=", "1.0", ",", "pi", "=", "None", ",", "W", "=", "None", ")", ":", "n", "=", "len", "(", "self", ".", "alphabet", ")", "self", ".", "mu", "=", "mu", "if", "pi", "is", "not", "None", "and", "len", "(", "pi", ")", "==", "n", ":", "Pi", "=", "np", ".", "array", "(", "pi", ")", "else", ":", "if", "pi", "is", "not", "None", "and", "len", "(", "pi", ")", "!=", "n", ":", "self", ".", "logger", "(", "\"length of equilibrium frequency vector does not match alphabet length\"", ",", "4", ",", "warn", "=", "True", ")", "self", ".", "logger", "(", "\"Ignoring input equilibrium frequencies\"", ",", "4", ",", "warn", "=", "True", ")", "Pi", "=", "np", ".", "ones", "(", "shape", "=", "(", "n", ",", ")", ")", "self", ".", "Pi", "=", "Pi", "/", "np", ".", "sum", "(", "Pi", ")", "if", "W", "is", "None", "or", "W", ".", "shape", "!=", "(", "n", ",", "n", ")", ":", "if", "(", "W", "is", "not", "None", ")", "and", "W", ".", "shape", "!=", "(", "n", ",", "n", ")", ":", "self", ".", "logger", "(", "\"Substitution matrix size does not match alphabet size\"", ",", "4", ",", "warn", "=", "True", ")", "self", ".", "logger", "(", "\"Ignoring input substitution matrix\"", ",", "4", ",", "warn", "=", "True", ")", "# flow matrix", "W", "=", "np", ".", "ones", "(", "(", "n", ",", "n", ")", ")", "np", ".", "fill_diagonal", "(", "W", ",", "0.0", ")", "np", ".", "fill_diagonal", "(", "W", ",", "-", "W", ".", "sum", "(", "axis", "=", "0", ")", ")", "else", ":", "W", "=", "np", ".", "array", "(", "W", ")", "self", ".", "W", "=", "0.5", "*", "(", "W", "+", "W", ".", "T", ")", "self", ".", "_check_fix_Q", "(", "fixed_mu", "=", "True", ")", "self", ".", "_eig", "(", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.standard
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 models** - JC69: Jukes-Cantor 1969 model. This model assumes equal frequencies of the nucleotides and equal transition rates between nucleotide states. For more info, see: Jukes and Cantor (1969). Evolution of Protein Molecules. New York: Academic Press. pp. 21-132. To create this model, use: :code:`mygtr = GTR.standard(model='jc69', mu=<my_mu>, alphabet=<my_alph>)` :code:`my_mu` - substitution rate (float) :code:`my_alph` - alphabet (str: :code:`'nuc'` or :code:`'nuc_nogap'`) - K80: Kimura 1980 model. Assumes equal concentrations across nucleotides, but allows different rates between transitions and transversions. The ratio of the transversion/transition rates is given by kappa parameter. For more info, see Kimura (1980), J. Mol. Evol. 16 (2): 111-120. doi:10.1007/BF01731581. Current implementation of the model does not account for the gaps. :code:`mygtr = GTR.standard(model='k80', mu=<my_mu>, kappa=<my_kappa>)` :code:`mu` - overall substitution rate (float) :code:`kappa` - ratio of transversion/transition rates (float) - F81: Felsenstein 1981 model. Assumes non-equal concentrations across nucleotides, but the transition rate between all states is assumed to be equal. See Felsenstein (1981), J. Mol. Evol. 17 (6): 368-376. doi:10.1007/BF01734359 for details. :code:`mygtr = GTR.standard(model='F81', mu=<mu>, pi=<pi>, alphabet=<alph>)` :code:`mu` - substitution rate (float) :code:`pi` - : nucleotide concentrations (numpy.array) :code:`alphabet' - alphabet to use. (:code:`'nuc'` or :code:`'nuc_nogap'`) - HKY85: Hasegawa, Kishino and Yano 1985 model. Allows different concentrations of the nucleotides (as in F81) + distinguishes between transition/transversion substitutions (similar to K80). Link: Hasegawa, Kishino, Yano (1985), J. Mol. Evol. 22 (2): 160-174. doi:10.1007/BF02101694 Current implementation of the model does not account for the gaps :code:`mygtr = GTR.standard(model='HKY85', mu=<mu>, pi=<pi>, kappa=<kappa>)` :code:`mu` - substitution rate (float) :code:`pi` - : nucleotide concentrations (numpy.array) :code:`kappa` - ratio of transversion/transition rates (float) - T92: Tamura 1992 model. Extending Kimura (1980) model for the case where a G+C-content bias exists. Link: Tamura K (1992), Mol. Biol. Evol. 9 (4): 678-687. DOI: 10.1093/oxfordjournals.molbev.a040752 Current implementation of the model does not account for the gaps :code:`mygtr = GTR.standard(model='T92', mu=<mu>, pi_GC=<pi_gc>, kappa=<kappa>)` :code:`mu` - substitution rate (float) :code:`pi_GC` - : relative GC content :code:`kappa` - ratio of transversion/transition rates (float) - TN93: Tamura and Nei 1993. The model distinguishes between the two different types of transition: (A <-> G) is allowed to have a different rate to (C<->T). Transversions have the same rate. The frequencies of the nucleotides are allowed to be different. Link: Tamura, Nei (1993), MolBiol Evol. 10 (3): 512-526. DOI:10.1093/oxfordjournals.molbev.a040023 :code:`mygtr = GTR.standard(model='TN93', mu=<mu>, kappa1=<k1>, kappa2=<k2>)` :code:`mu` - substitution rate (float) :code:`kappa1` - relative A<-->C, A<-->T, T<-->G and G<-->C rates (float) :code:`kappa` - relative C<-->T rate (float) .. Note:: Rate of A<-->G substitution is set to one. All other rates (kappa1, kappa2) are specified relative to this rate
treetime/gtr.py
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 models** - JC69: Jukes-Cantor 1969 model. This model assumes equal frequencies of the nucleotides and equal transition rates between nucleotide states. For more info, see: Jukes and Cantor (1969). Evolution of Protein Molecules. New York: Academic Press. pp. 21-132. To create this model, use: :code:`mygtr = GTR.standard(model='jc69', mu=<my_mu>, alphabet=<my_alph>)` :code:`my_mu` - substitution rate (float) :code:`my_alph` - alphabet (str: :code:`'nuc'` or :code:`'nuc_nogap'`) - K80: Kimura 1980 model. Assumes equal concentrations across nucleotides, but allows different rates between transitions and transversions. The ratio of the transversion/transition rates is given by kappa parameter. For more info, see Kimura (1980), J. Mol. Evol. 16 (2): 111-120. doi:10.1007/BF01731581. Current implementation of the model does not account for the gaps. :code:`mygtr = GTR.standard(model='k80', mu=<my_mu>, kappa=<my_kappa>)` :code:`mu` - overall substitution rate (float) :code:`kappa` - ratio of transversion/transition rates (float) - F81: Felsenstein 1981 model. Assumes non-equal concentrations across nucleotides, but the transition rate between all states is assumed to be equal. See Felsenstein (1981), J. Mol. Evol. 17 (6): 368-376. doi:10.1007/BF01734359 for details. :code:`mygtr = GTR.standard(model='F81', mu=<mu>, pi=<pi>, alphabet=<alph>)` :code:`mu` - substitution rate (float) :code:`pi` - : nucleotide concentrations (numpy.array) :code:`alphabet' - alphabet to use. (:code:`'nuc'` or :code:`'nuc_nogap'`) - HKY85: Hasegawa, Kishino and Yano 1985 model. Allows different concentrations of the nucleotides (as in F81) + distinguishes between transition/transversion substitutions (similar to K80). Link: Hasegawa, Kishino, Yano (1985), J. Mol. Evol. 22 (2): 160-174. doi:10.1007/BF02101694 Current implementation of the model does not account for the gaps :code:`mygtr = GTR.standard(model='HKY85', mu=<mu>, pi=<pi>, kappa=<kappa>)` :code:`mu` - substitution rate (float) :code:`pi` - : nucleotide concentrations (numpy.array) :code:`kappa` - ratio of transversion/transition rates (float) - T92: Tamura 1992 model. Extending Kimura (1980) model for the case where a G+C-content bias exists. Link: Tamura K (1992), Mol. Biol. Evol. 9 (4): 678-687. DOI: 10.1093/oxfordjournals.molbev.a040752 Current implementation of the model does not account for the gaps :code:`mygtr = GTR.standard(model='T92', mu=<mu>, pi_GC=<pi_gc>, kappa=<kappa>)` :code:`mu` - substitution rate (float) :code:`pi_GC` - : relative GC content :code:`kappa` - ratio of transversion/transition rates (float) - TN93: Tamura and Nei 1993. The model distinguishes between the two different types of transition: (A <-> G) is allowed to have a different rate to (C<->T). Transversions have the same rate. The frequencies of the nucleotides are allowed to be different. Link: Tamura, Nei (1993), MolBiol Evol. 10 (3): 512-526. DOI:10.1093/oxfordjournals.molbev.a040023 :code:`mygtr = GTR.standard(model='TN93', mu=<mu>, kappa1=<k1>, kappa2=<k2>)` :code:`mu` - substitution rate (float) :code:`kappa1` - relative A<-->C, A<-->T, T<-->G and G<-->C rates (float) :code:`kappa` - relative C<-->T rate (float) .. Note:: Rate of A<-->G substitution is set to one. All other rates (kappa1, kappa2) are specified relative to this rate """ from .nuc_models import JC69, K80, F81, HKY85, T92, TN93 from .aa_models import JTT92 if model.lower() in ['jc', 'jc69', 'jukes-cantor', 'jukes-cantor69', 'jukescantor', 'jukescantor69']: return JC69(**kwargs) elif model.lower() in ['k80', 'kimura80', 'kimura1980']: return K80(**kwargs) elif model.lower() in ['f81', 'felsenstein81', 'felsenstein1981']: return F81(**kwargs) elif model.lower() in ['hky', 'hky85', 'hky1985']: return HKY85(**kwargs) elif model.lower() in ['t92', 'tamura92', 'tamura1992']: return T92(**kwargs) elif model.lower() in ['tn93', 'tamura_nei_93', 'tamuranei93']: return TN93(**kwargs) elif model.lower() in ['jtt', 'jtt92']: return JTT92(**kwargs) else: raise KeyError("The GTR model '{}' is not in the list of available models." "".format(model))
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 models** - JC69: Jukes-Cantor 1969 model. This model assumes equal frequencies of the nucleotides and equal transition rates between nucleotide states. For more info, see: Jukes and Cantor (1969). Evolution of Protein Molecules. New York: Academic Press. pp. 21-132. To create this model, use: :code:`mygtr = GTR.standard(model='jc69', mu=<my_mu>, alphabet=<my_alph>)` :code:`my_mu` - substitution rate (float) :code:`my_alph` - alphabet (str: :code:`'nuc'` or :code:`'nuc_nogap'`) - K80: Kimura 1980 model. Assumes equal concentrations across nucleotides, but allows different rates between transitions and transversions. The ratio of the transversion/transition rates is given by kappa parameter. For more info, see Kimura (1980), J. Mol. Evol. 16 (2): 111-120. doi:10.1007/BF01731581. Current implementation of the model does not account for the gaps. :code:`mygtr = GTR.standard(model='k80', mu=<my_mu>, kappa=<my_kappa>)` :code:`mu` - overall substitution rate (float) :code:`kappa` - ratio of transversion/transition rates (float) - F81: Felsenstein 1981 model. Assumes non-equal concentrations across nucleotides, but the transition rate between all states is assumed to be equal. See Felsenstein (1981), J. Mol. Evol. 17 (6): 368-376. doi:10.1007/BF01734359 for details. :code:`mygtr = GTR.standard(model='F81', mu=<mu>, pi=<pi>, alphabet=<alph>)` :code:`mu` - substitution rate (float) :code:`pi` - : nucleotide concentrations (numpy.array) :code:`alphabet' - alphabet to use. (:code:`'nuc'` or :code:`'nuc_nogap'`) - HKY85: Hasegawa, Kishino and Yano 1985 model. Allows different concentrations of the nucleotides (as in F81) + distinguishes between transition/transversion substitutions (similar to K80). Link: Hasegawa, Kishino, Yano (1985), J. Mol. Evol. 22 (2): 160-174. doi:10.1007/BF02101694 Current implementation of the model does not account for the gaps :code:`mygtr = GTR.standard(model='HKY85', mu=<mu>, pi=<pi>, kappa=<kappa>)` :code:`mu` - substitution rate (float) :code:`pi` - : nucleotide concentrations (numpy.array) :code:`kappa` - ratio of transversion/transition rates (float) - T92: Tamura 1992 model. Extending Kimura (1980) model for the case where a G+C-content bias exists. Link: Tamura K (1992), Mol. Biol. Evol. 9 (4): 678-687. DOI: 10.1093/oxfordjournals.molbev.a040752 Current implementation of the model does not account for the gaps :code:`mygtr = GTR.standard(model='T92', mu=<mu>, pi_GC=<pi_gc>, kappa=<kappa>)` :code:`mu` - substitution rate (float) :code:`pi_GC` - : relative GC content :code:`kappa` - ratio of transversion/transition rates (float) - TN93: Tamura and Nei 1993. The model distinguishes between the two different types of transition: (A <-> G) is allowed to have a different rate to (C<->T). Transversions have the same rate. The frequencies of the nucleotides are allowed to be different. Link: Tamura, Nei (1993), MolBiol Evol. 10 (3): 512-526. DOI:10.1093/oxfordjournals.molbev.a040023 :code:`mygtr = GTR.standard(model='TN93', mu=<mu>, kappa1=<k1>, kappa2=<k2>)` :code:`mu` - substitution rate (float) :code:`kappa1` - relative A<-->C, A<-->T, T<-->G and G<-->C rates (float) :code:`kappa` - relative C<-->T rate (float) .. Note:: Rate of A<-->G substitution is set to one. All other rates (kappa1, kappa2) are specified relative to this rate """ from .nuc_models import JC69, K80, F81, HKY85, T92, TN93 from .aa_models import JTT92 if model.lower() in ['jc', 'jc69', 'jukes-cantor', 'jukes-cantor69', 'jukescantor', 'jukescantor69']: return JC69(**kwargs) elif model.lower() in ['k80', 'kimura80', 'kimura1980']: return K80(**kwargs) elif model.lower() in ['f81', 'felsenstein81', 'felsenstein1981']: return F81(**kwargs) elif model.lower() in ['hky', 'hky85', 'hky1985']: return HKY85(**kwargs) elif model.lower() in ['t92', 'tamura92', 'tamura1992']: return T92(**kwargs) elif model.lower() in ['tn93', 'tamura_nei_93', 'tamuranei93']: return TN93(**kwargs) elif model.lower() in ['jtt', 'jtt92']: return JTT92(**kwargs) else: raise KeyError("The GTR model '{}' is not in the list of available models." "".format(model))
[ "Create", "standard", "model", "of", "molecular", "evolution", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L229-L369
[ "def", "standard", "(", "model", ",", "*", "*", "kwargs", ")", ":", "from", ".", "nuc_models", "import", "JC69", ",", "K80", ",", "F81", ",", "HKY85", ",", "T92", ",", "TN93", "from", ".", "aa_models", "import", "JTT92", "if", "model", ".", "lower", "(", ")", "in", "[", "'jc'", ",", "'jc69'", ",", "'jukes-cantor'", ",", "'jukes-cantor69'", ",", "'jukescantor'", ",", "'jukescantor69'", "]", ":", "return", "JC69", "(", "*", "*", "kwargs", ")", "elif", "model", ".", "lower", "(", ")", "in", "[", "'k80'", ",", "'kimura80'", ",", "'kimura1980'", "]", ":", "return", "K80", "(", "*", "*", "kwargs", ")", "elif", "model", ".", "lower", "(", ")", "in", "[", "'f81'", ",", "'felsenstein81'", ",", "'felsenstein1981'", "]", ":", "return", "F81", "(", "*", "*", "kwargs", ")", "elif", "model", ".", "lower", "(", ")", "in", "[", "'hky'", ",", "'hky85'", ",", "'hky1985'", "]", ":", "return", "HKY85", "(", "*", "*", "kwargs", ")", "elif", "model", ".", "lower", "(", ")", "in", "[", "'t92'", ",", "'tamura92'", ",", "'tamura1992'", "]", ":", "return", "T92", "(", "*", "*", "kwargs", ")", "elif", "model", ".", "lower", "(", ")", "in", "[", "'tn93'", ",", "'tamura_nei_93'", ",", "'tamuranei93'", "]", ":", "return", "TN93", "(", "*", "*", "kwargs", ")", "elif", "model", ".", "lower", "(", ")", "in", "[", "'jtt'", ",", "'jtt92'", "]", ":", "return", "JTT92", "(", "*", "*", "kwargs", ")", "else", ":", "raise", "KeyError", "(", "\"The GTR model '{}' is not in the list of available models.\"", "\"\"", ".", "format", "(", "model", ")", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.random
Creates a random GTR model Parameters ---------- mu : float Substitution rate alphabet : str Alphabet name (should be standard: 'nuc', 'nuc_gap', 'aa', 'aa_gap')
treetime/gtr.py
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=alphabets[alphabet] gtr = cls(alphabet) n = gtr.alphabet.shape[0] pi = 1.0*np.random.randint(0,100,size=(n)) W = 1.0*np.random.randint(0,100,size=(n,n)) # with gaps gtr.assign_rates(mu=mu, pi=pi, W=W) return gtr
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=alphabets[alphabet] gtr = cls(alphabet) n = gtr.alphabet.shape[0] pi = 1.0*np.random.randint(0,100,size=(n)) W = 1.0*np.random.randint(0,100,size=(n,n)) # with gaps gtr.assign_rates(mu=mu, pi=pi, W=W) return gtr
[ "Creates", "a", "random", "GTR", "model" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L372-L395
[ "def", "random", "(", "cls", ",", "mu", "=", "1.0", ",", "alphabet", "=", "'nuc'", ")", ":", "alphabet", "=", "alphabets", "[", "alphabet", "]", "gtr", "=", "cls", "(", "alphabet", ")", "n", "=", "gtr", ".", "alphabet", ".", "shape", "[", "0", "]", "pi", "=", "1.0", "*", "np", ".", "random", ".", "randint", "(", "0", ",", "100", ",", "size", "=", "(", "n", ")", ")", "W", "=", "1.0", "*", "np", ".", "random", ".", "randint", "(", "0", ",", "100", ",", "size", "=", "(", "n", ",", "n", ")", ")", "# with gaps", "gtr", ".", "assign_rates", "(", "mu", "=", "mu", ",", "pi", "=", "pi", ",", "W", "=", "W", ")", "return", "gtr" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.infer
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}` are the transitions, :math:`pi_i` are the equilibrium state frequencies, :math:`W_{ij}` is the "substitution attempt matrix", while :math:`T_i` is the time on the tree spent in character state :math:`i`. To regularize the process, we add pseudocounts and also need to account for the fact that the root of the tree is in a particular state. the modified equation is :math:`n_{ij} + pc = pi_i W_{ij} (T_j+pc+root\_state)` Parameters ---------- nij : nxn matrix The number of times a change in character state is observed between state j and i Ti :n vector The time spent in each character state root_state : n vector The number of characters in state i in the sequence of the root node. pc : float Pseudocounts, this determines the lower cutoff on the rate when no substitutions are observed **kwargs: Key word arguments to be passed Keyword Args ------------ alphabet : str Specify alphabet when applicable. If the alphabet specification is required, but no alphabet is specified, the nucleotide alphabet will be used as default.
treetime/gtr.py
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}` are the transitions, :math:`pi_i` are the equilibrium state frequencies, :math:`W_{ij}` is the "substitution attempt matrix", while :math:`T_i` is the time on the tree spent in character state :math:`i`. To regularize the process, we add pseudocounts and also need to account for the fact that the root of the tree is in a particular state. the modified equation is :math:`n_{ij} + pc = pi_i W_{ij} (T_j+pc+root\_state)` Parameters ---------- nij : nxn matrix The number of times a change in character state is observed between state j and i Ti :n vector The time spent in each character state root_state : n vector The number of characters in state i in the sequence of the root node. pc : float Pseudocounts, this determines the lower cutoff on the rate when no substitutions are observed **kwargs: Key word arguments to be passed Keyword Args ------------ alphabet : str Specify alphabet when applicable. If the alphabet specification is required, but no alphabet is specified, the nucleotide alphabet will be used as default. """ from scipy import linalg as LA gtr = cls(**kwargs) gtr.logger("GTR: model inference ",1) dp = 1e-5 Nit = 40 pc_mat = pc*np.ones_like(nij) np.fill_diagonal(pc_mat, 0.0) count = 0 pi_old = np.zeros_like(Ti) if fixed_pi is None: pi = np.ones_like(Ti) else: pi = np.copy(fixed_pi) pi/=pi.sum() W_ij = np.ones_like(nij) mu = nij.sum()/Ti.sum() # if pi is fixed, this will immediately converge while LA.norm(pi_old-pi) > dp and count < Nit: gtr.logger(' '.join(map(str, ['GTR inference iteration',count,'change:',LA.norm(pi_old-pi)])), 3) count += 1 pi_old = np.copy(pi) W_ij = (nij+nij.T+2*pc_mat)/mu/(np.outer(pi,Ti) + np.outer(Ti,pi) + ttconf.TINY_NUMBER + 2*pc_mat) np.fill_diagonal(W_ij, 0) scale_factor = np.einsum('i,ij,j',pi,W_ij,pi) W_ij = W_ij/scale_factor if fixed_pi is None: pi = (np.sum(nij+pc_mat,axis=1)+root_state)/(ttconf.TINY_NUMBER + mu*np.dot(W_ij,Ti)+root_state.sum()+np.sum(pc_mat, axis=1)) pi /= pi.sum() mu = nij.sum()/(ttconf.TINY_NUMBER + np.sum(pi * (W_ij.dot(Ti)))) if count >= Nit: gtr.logger('WARNING: maximum number of iterations has been reached in GTR inference',3, warn=True) if LA.norm(pi_old-pi) > dp: gtr.logger('the iterative scheme has not converged',3,warn=True) elif np.abs(1-np.max(pi.sum(axis=0))) > dp: gtr.logger('the iterative scheme has converged, but proper normalization was not reached',3,warn=True) if gtr.gap_index is not None: if pi[gtr.gap_index]<gap_limit: gtr.logger('The model allows for gaps which are estimated to occur at a low fraction of %1.3e'%pi[gtr.gap_index]+ '\n\t\tthis can potentially result in artificats.'+ '\n\t\tgap fraction will be set to %1.4f'%gap_limit,2,warn=True) pi[gtr.gap_index] = gap_limit pi /= pi.sum() gtr.assign_rates(mu=mu, W=W_ij, pi=pi) return gtr
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}` are the transitions, :math:`pi_i` are the equilibrium state frequencies, :math:`W_{ij}` is the "substitution attempt matrix", while :math:`T_i` is the time on the tree spent in character state :math:`i`. To regularize the process, we add pseudocounts and also need to account for the fact that the root of the tree is in a particular state. the modified equation is :math:`n_{ij} + pc = pi_i W_{ij} (T_j+pc+root\_state)` Parameters ---------- nij : nxn matrix The number of times a change in character state is observed between state j and i Ti :n vector The time spent in each character state root_state : n vector The number of characters in state i in the sequence of the root node. pc : float Pseudocounts, this determines the lower cutoff on the rate when no substitutions are observed **kwargs: Key word arguments to be passed Keyword Args ------------ alphabet : str Specify alphabet when applicable. If the alphabet specification is required, but no alphabet is specified, the nucleotide alphabet will be used as default. """ from scipy import linalg as LA gtr = cls(**kwargs) gtr.logger("GTR: model inference ",1) dp = 1e-5 Nit = 40 pc_mat = pc*np.ones_like(nij) np.fill_diagonal(pc_mat, 0.0) count = 0 pi_old = np.zeros_like(Ti) if fixed_pi is None: pi = np.ones_like(Ti) else: pi = np.copy(fixed_pi) pi/=pi.sum() W_ij = np.ones_like(nij) mu = nij.sum()/Ti.sum() # if pi is fixed, this will immediately converge while LA.norm(pi_old-pi) > dp and count < Nit: gtr.logger(' '.join(map(str, ['GTR inference iteration',count,'change:',LA.norm(pi_old-pi)])), 3) count += 1 pi_old = np.copy(pi) W_ij = (nij+nij.T+2*pc_mat)/mu/(np.outer(pi,Ti) + np.outer(Ti,pi) + ttconf.TINY_NUMBER + 2*pc_mat) np.fill_diagonal(W_ij, 0) scale_factor = np.einsum('i,ij,j',pi,W_ij,pi) W_ij = W_ij/scale_factor if fixed_pi is None: pi = (np.sum(nij+pc_mat,axis=1)+root_state)/(ttconf.TINY_NUMBER + mu*np.dot(W_ij,Ti)+root_state.sum()+np.sum(pc_mat, axis=1)) pi /= pi.sum() mu = nij.sum()/(ttconf.TINY_NUMBER + np.sum(pi * (W_ij.dot(Ti)))) if count >= Nit: gtr.logger('WARNING: maximum number of iterations has been reached in GTR inference',3, warn=True) if LA.norm(pi_old-pi) > dp: gtr.logger('the iterative scheme has not converged',3,warn=True) elif np.abs(1-np.max(pi.sum(axis=0))) > dp: gtr.logger('the iterative scheme has converged, but proper normalization was not reached',3,warn=True) if gtr.gap_index is not None: if pi[gtr.gap_index]<gap_limit: gtr.logger('The model allows for gaps which are estimated to occur at a low fraction of %1.3e'%pi[gtr.gap_index]+ '\n\t\tthis can potentially result in artificats.'+ '\n\t\tgap fraction will be set to %1.4f'%gap_limit,2,warn=True) pi[gtr.gap_index] = gap_limit pi /= pi.sum() gtr.assign_rates(mu=mu, W=W_ij, pi=pi) return gtr
[ "Infer", "a", "GTR", "model", "by", "specifying", "the", "number", "of", "transitions", "and", "time", "spent", "in", "each", "character", ".", "The", "basic", "equation", "that", "is", "being", "solved", "is" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L399-L491
[ "def", "infer", "(", "cls", ",", "nij", ",", "Ti", ",", "root_state", ",", "fixed_pi", "=", "None", ",", "pc", "=", "5.0", ",", "gap_limit", "=", "0.01", ",", "*", "*", "kwargs", ")", ":", "from", "scipy", "import", "linalg", "as", "LA", "gtr", "=", "cls", "(", "*", "*", "kwargs", ")", "gtr", ".", "logger", "(", "\"GTR: model inference \"", ",", "1", ")", "dp", "=", "1e-5", "Nit", "=", "40", "pc_mat", "=", "pc", "*", "np", ".", "ones_like", "(", "nij", ")", "np", ".", "fill_diagonal", "(", "pc_mat", ",", "0.0", ")", "count", "=", "0", "pi_old", "=", "np", ".", "zeros_like", "(", "Ti", ")", "if", "fixed_pi", "is", "None", ":", "pi", "=", "np", ".", "ones_like", "(", "Ti", ")", "else", ":", "pi", "=", "np", ".", "copy", "(", "fixed_pi", ")", "pi", "/=", "pi", ".", "sum", "(", ")", "W_ij", "=", "np", ".", "ones_like", "(", "nij", ")", "mu", "=", "nij", ".", "sum", "(", ")", "/", "Ti", ".", "sum", "(", ")", "# if pi is fixed, this will immediately converge", "while", "LA", ".", "norm", "(", "pi_old", "-", "pi", ")", ">", "dp", "and", "count", "<", "Nit", ":", "gtr", ".", "logger", "(", "' '", ".", "join", "(", "map", "(", "str", ",", "[", "'GTR inference iteration'", ",", "count", ",", "'change:'", ",", "LA", ".", "norm", "(", "pi_old", "-", "pi", ")", "]", ")", ")", ",", "3", ")", "count", "+=", "1", "pi_old", "=", "np", ".", "copy", "(", "pi", ")", "W_ij", "=", "(", "nij", "+", "nij", ".", "T", "+", "2", "*", "pc_mat", ")", "/", "mu", "/", "(", "np", ".", "outer", "(", "pi", ",", "Ti", ")", "+", "np", ".", "outer", "(", "Ti", ",", "pi", ")", "+", "ttconf", ".", "TINY_NUMBER", "+", "2", "*", "pc_mat", ")", "np", ".", "fill_diagonal", "(", "W_ij", ",", "0", ")", "scale_factor", "=", "np", ".", "einsum", "(", "'i,ij,j'", ",", "pi", ",", "W_ij", ",", "pi", ")", "W_ij", "=", "W_ij", "/", "scale_factor", "if", "fixed_pi", "is", "None", ":", "pi", "=", "(", "np", ".", "sum", "(", "nij", "+", "pc_mat", ",", "axis", "=", "1", ")", "+", "root_state", ")", "/", "(", "ttconf", ".", "TINY_NUMBER", "+", "mu", "*", "np", ".", "dot", "(", "W_ij", ",", "Ti", ")", "+", "root_state", ".", "sum", "(", ")", "+", "np", ".", "sum", "(", "pc_mat", ",", "axis", "=", "1", ")", ")", "pi", "/=", "pi", ".", "sum", "(", ")", "mu", "=", "nij", ".", "sum", "(", ")", "/", "(", "ttconf", ".", "TINY_NUMBER", "+", "np", ".", "sum", "(", "pi", "*", "(", "W_ij", ".", "dot", "(", "Ti", ")", ")", ")", ")", "if", "count", ">=", "Nit", ":", "gtr", ".", "logger", "(", "'WARNING: maximum number of iterations has been reached in GTR inference'", ",", "3", ",", "warn", "=", "True", ")", "if", "LA", ".", "norm", "(", "pi_old", "-", "pi", ")", ">", "dp", ":", "gtr", ".", "logger", "(", "'the iterative scheme has not converged'", ",", "3", ",", "warn", "=", "True", ")", "elif", "np", ".", "abs", "(", "1", "-", "np", ".", "max", "(", "pi", ".", "sum", "(", "axis", "=", "0", ")", ")", ")", ">", "dp", ":", "gtr", ".", "logger", "(", "'the iterative scheme has converged, but proper normalization was not reached'", ",", "3", ",", "warn", "=", "True", ")", "if", "gtr", ".", "gap_index", "is", "not", "None", ":", "if", "pi", "[", "gtr", ".", "gap_index", "]", "<", "gap_limit", ":", "gtr", ".", "logger", "(", "'The model allows for gaps which are estimated to occur at a low fraction of %1.3e'", "%", "pi", "[", "gtr", ".", "gap_index", "]", "+", "'\\n\\t\\tthis can potentially result in artificats.'", "+", "'\\n\\t\\tgap fraction will be set to %1.4f'", "%", "gap_limit", ",", "2", ",", "warn", "=", "True", ")", "pi", "[", "gtr", ".", "gap_index", "]", "=", "gap_limit", "pi", "/=", "pi", ".", "sum", "(", ")", "gtr", ".", "assign_rates", "(", "mu", "=", "mu", ",", "W", "=", "W_ij", ",", "pi", "=", "pi", ")", "return", "gtr" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR._check_fix_Q
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.
treetime/gtr.py
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 manually # NEEDED TO BREAK RATE MATRIX DEGENERACY AND FORCE NP TO RETURN REAL ORTHONORMAL EIGENVECTORS self.W += self.break_degen + self.break_degen.T # fix W np.fill_diagonal(self.W, 0) Wdiag = -(self.Q).sum(axis=0)/self.Pi np.fill_diagonal(self.W, Wdiag) scale_factor = -np.sum(np.diagonal(self.Q)*self.Pi) self.W /= scale_factor if not fixed_mu: self.mu *= scale_factor if (self.Q.sum(axis=0) < 1e-10).sum() < self.alphabet.shape[0]: # fix failed print ("Cannot fix the diagonal of the GTR rate matrix. Should be all zero", self.Q.sum(axis=0)) import ipdb; ipdb.set_trace() raise ArithmeticError("Cannot fix the diagonal of the GTR rate matrix.")
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 manually # NEEDED TO BREAK RATE MATRIX DEGENERACY AND FORCE NP TO RETURN REAL ORTHONORMAL EIGENVECTORS self.W += self.break_degen + self.break_degen.T # fix W np.fill_diagonal(self.W, 0) Wdiag = -(self.Q).sum(axis=0)/self.Pi np.fill_diagonal(self.W, Wdiag) scale_factor = -np.sum(np.diagonal(self.Q)*self.Pi) self.W /= scale_factor if not fixed_mu: self.mu *= scale_factor if (self.Q.sum(axis=0) < 1e-10).sum() < self.alphabet.shape[0]: # fix failed print ("Cannot fix the diagonal of the GTR rate matrix. Should be all zero", self.Q.sum(axis=0)) import ipdb; ipdb.set_trace() raise ArithmeticError("Cannot fix the diagonal of the GTR rate matrix.")
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L496-L517
[ "def", "_check_fix_Q", "(", "self", ",", "fixed_mu", "=", "False", ")", ":", "# fix Q", "self", ".", "Pi", "/=", "self", ".", "Pi", ".", "sum", "(", ")", "# correct the Pi manually", "# NEEDED TO BREAK RATE MATRIX DEGENERACY AND FORCE NP TO RETURN REAL ORTHONORMAL EIGENVECTORS", "self", ".", "W", "+=", "self", ".", "break_degen", "+", "self", ".", "break_degen", ".", "T", "# fix W", "np", ".", "fill_diagonal", "(", "self", ".", "W", ",", "0", ")", "Wdiag", "=", "-", "(", "self", ".", "Q", ")", ".", "sum", "(", "axis", "=", "0", ")", "/", "self", ".", "Pi", "np", ".", "fill_diagonal", "(", "self", ".", "W", ",", "Wdiag", ")", "scale_factor", "=", "-", "np", ".", "sum", "(", "np", ".", "diagonal", "(", "self", ".", "Q", ")", "*", "self", ".", "Pi", ")", "self", ".", "W", "/=", "scale_factor", "if", "not", "fixed_mu", ":", "self", ".", "mu", "*=", "scale_factor", "if", "(", "self", ".", "Q", ".", "sum", "(", "axis", "=", "0", ")", "<", "1e-10", ")", ".", "sum", "(", ")", "<", "self", ".", "alphabet", ".", "shape", "[", "0", "]", ":", "# fix failed", "print", "(", "\"Cannot fix the diagonal of the GTR rate matrix. Should be all zero\"", ",", "self", ".", "Q", ".", "sum", "(", "axis", "=", "0", ")", ")", "import", "ipdb", "ipdb", ".", "set_trace", "(", ")", "raise", "ArithmeticError", "(", "\"Cannot fix the diagonal of the GTR rate matrix.\"", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR._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.
treetime/gtr.py
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, eigvecs = np.linalg.eig(self.Q) self.v = np.real(eigvecs) self.v_inv = np.linalg.inv(self.v) self.eigenvals = np.real(eigvals)
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, eigvecs = np.linalg.eig(self.Q) self.v = np.real(eigvecs) self.v_inv = np.linalg.inv(self.v) self.eigenvals = np.real(eigvals)
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L520-L530
[ "def", "_eig", "(", "self", ")", ":", "# eigendecomposition of the rate matrix", "eigvals", ",", "eigvecs", "=", "np", ".", "linalg", ".", "eig", "(", "self", ".", "Q", ")", "self", ".", "v", "=", "np", ".", "real", "(", "eigvecs", ")", "self", ".", "v_inv", "=", "np", ".", "linalg", ".", "inv", "(", "self", ".", "v", ")", "self", ".", "eigenvals", "=", "np", ".", "real", "(", "eigvals", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR._eig_sym
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.
treetime/gtr.py
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 = np.sqrt(self.Pi) symQ = self.W*np.outer(tmpp, tmpp) eigvals, eigvecs = np.linalg.eigh(symQ) tmp_v = eigvecs.T*tmpp one_norm = np.sum(np.abs(tmp_v), axis=1) self.v = tmp_v.T/one_norm self.v_inv = (eigvecs*one_norm).T/tmpp self.eigenvals = eigvals
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 = np.sqrt(self.Pi) symQ = self.W*np.outer(tmpp, tmpp) eigvals, eigvecs = np.linalg.eigh(symQ) tmp_v = eigvecs.T*tmpp one_norm = np.sum(np.abs(tmp_v), axis=1) self.v = tmp_v.T/one_norm self.v_inv = (eigvecs*one_norm).T/tmpp self.eigenvals = eigvals
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L533-L547
[ "def", "_eig_sym", "(", "self", ")", ":", "# eigendecomposition of the rate matrix", "tmpp", "=", "np", ".", "sqrt", "(", "self", ".", "Pi", ")", "symQ", "=", "self", ".", "W", "*", "np", ".", "outer", "(", "tmpp", ",", "tmpp", ")", "eigvals", ",", "eigvecs", "=", "np", ".", "linalg", ".", "eigh", "(", "symQ", ")", "tmp_v", "=", "eigvecs", ".", "T", "*", "tmpp", "one_norm", "=", "np", ".", "sum", "(", "np", ".", "abs", "(", "tmp_v", ")", ",", "axis", "=", "1", ")", "self", ".", "v", "=", "tmp_v", ".", "T", "/", "one_norm", "self", ".", "v_inv", "=", "(", "eigvecs", "*", "one_norm", ")", ".", "T", "/", "tmpp", "self", ".", "eigenvals", "=", "eigvals" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.compress_sequence_pair
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. Parameters ---------- seq_p: numpy array Parent sequence as numpy array of chars seq_ch: numpy array Child sequence as numpy array of chars pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. ignore_gap: bool Whether or not to include gapped positions of the alignment in the multiplicity count Returns ------- seq_pair : list :code:`[(0,1), (2,2), (3,4)]` list of parent_child state pairs as indices in the alphabet multiplicity : numpy array Number of times a particular pair is observed
treetime/gtr.py
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 sequences of parent and child. Parameters ---------- seq_p: numpy array Parent sequence as numpy array of chars seq_ch: numpy array Child sequence as numpy array of chars pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. ignore_gap: bool Whether or not to include gapped positions of the alignment in the multiplicity count Returns ------- seq_pair : list :code:`[(0,1), (2,2), (3,4)]` list of parent_child state pairs as indices in the alphabet multiplicity : numpy array Number of times a particular pair is observed ''' if pattern_multiplicity is None: pattern_multiplicity = np.ones_like(seq_p, dtype=float) from collections import Counter if seq_ch.shape != seq_p.shape: raise ValueError("GTR.compress_sequence_pair: Sequence lengths do not match!") if len(self.alphabet)<10: # for small alphabet, repeatedly check array for all state pairs pair_count = [] bool_seqs_p = [] bool_seqs_ch = [] for seq, bs in [(seq_p,bool_seqs_p), (seq_ch, bool_seqs_ch)]: for ni,nuc in enumerate(self.alphabet): bs.append(seq==nuc) for n1,nuc1 in enumerate(self.alphabet): if (self.gap_index is None) or (not ignore_gaps) or (n1!=self.gap_index): for n2,nuc2 in enumerate(self.alphabet): if (self.gap_index is None) or (not ignore_gaps) or (n2!=self.gap_index): count = ((bool_seqs_p[n1]&bool_seqs_ch[n2])*pattern_multiplicity).sum() if count: pair_count.append(((n1,n2), count)) else: # enumerate state pairs of the sequence for large alphabets num_seqs = [] for seq in [seq_p, seq_ch]: # for each sequence (parent and child) construct a numerical sequence [0,5,3,1,2,3...] tmp = np.ones_like(seq, dtype=int) for ni,nuc in enumerate(self.alphabet): tmp[seq==nuc] = ni # set each position corresponding to a state to the corresponding index num_seqs.append(tmp) pair_count = defaultdict(int) if ignore_gaps: # if gaps are ignored skip positions where one or the other sequence is gapped for i in range(len(seq_p)): if self.gap_index!=num_seqs[0][i] and self.gap_index!=num_seqs[1][i]: pair_count[(num_seqs[0][i],num_seqs[1][i])]+=pattern_multiplicity[i] else: # otherwise, just count for i in range(len(seq_p)): pair_count[(num_seqs[0][i],num_seqs[1][i])]+=pattern_multiplicity[i] pair_count = pair_count.items() return (np.array([x[0] for x in pair_count], dtype=int), # [(child_nuc, parent_nuc),()...] np.array([x[1] for x in pair_count], dtype=int))
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 sequences of parent and child. Parameters ---------- seq_p: numpy array Parent sequence as numpy array of chars seq_ch: numpy array Child sequence as numpy array of chars pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. ignore_gap: bool Whether or not to include gapped positions of the alignment in the multiplicity count Returns ------- seq_pair : list :code:`[(0,1), (2,2), (3,4)]` list of parent_child state pairs as indices in the alphabet multiplicity : numpy array Number of times a particular pair is observed ''' if pattern_multiplicity is None: pattern_multiplicity = np.ones_like(seq_p, dtype=float) from collections import Counter if seq_ch.shape != seq_p.shape: raise ValueError("GTR.compress_sequence_pair: Sequence lengths do not match!") if len(self.alphabet)<10: # for small alphabet, repeatedly check array for all state pairs pair_count = [] bool_seqs_p = [] bool_seqs_ch = [] for seq, bs in [(seq_p,bool_seqs_p), (seq_ch, bool_seqs_ch)]: for ni,nuc in enumerate(self.alphabet): bs.append(seq==nuc) for n1,nuc1 in enumerate(self.alphabet): if (self.gap_index is None) or (not ignore_gaps) or (n1!=self.gap_index): for n2,nuc2 in enumerate(self.alphabet): if (self.gap_index is None) or (not ignore_gaps) or (n2!=self.gap_index): count = ((bool_seqs_p[n1]&bool_seqs_ch[n2])*pattern_multiplicity).sum() if count: pair_count.append(((n1,n2), count)) else: # enumerate state pairs of the sequence for large alphabets num_seqs = [] for seq in [seq_p, seq_ch]: # for each sequence (parent and child) construct a numerical sequence [0,5,3,1,2,3...] tmp = np.ones_like(seq, dtype=int) for ni,nuc in enumerate(self.alphabet): tmp[seq==nuc] = ni # set each position corresponding to a state to the corresponding index num_seqs.append(tmp) pair_count = defaultdict(int) if ignore_gaps: # if gaps are ignored skip positions where one or the other sequence is gapped for i in range(len(seq_p)): if self.gap_index!=num_seqs[0][i] and self.gap_index!=num_seqs[1][i]: pair_count[(num_seqs[0][i],num_seqs[1][i])]+=pattern_multiplicity[i] else: # otherwise, just count for i in range(len(seq_p)): pair_count[(num_seqs[0][i],num_seqs[1][i])]+=pattern_multiplicity[i] pair_count = pair_count.items() return (np.array([x[0] for x in pair_count], dtype=int), # [(child_nuc, parent_nuc),()...] np.array([x[1] for x in pair_count], dtype=int))
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L550-L625
[ "def", "compress_sequence_pair", "(", "self", ",", "seq_p", ",", "seq_ch", ",", "pattern_multiplicity", "=", "None", ",", "ignore_gaps", "=", "False", ")", ":", "if", "pattern_multiplicity", "is", "None", ":", "pattern_multiplicity", "=", "np", ".", "ones_like", "(", "seq_p", ",", "dtype", "=", "float", ")", "from", "collections", "import", "Counter", "if", "seq_ch", ".", "shape", "!=", "seq_p", ".", "shape", ":", "raise", "ValueError", "(", "\"GTR.compress_sequence_pair: Sequence lengths do not match!\"", ")", "if", "len", "(", "self", ".", "alphabet", ")", "<", "10", ":", "# for small alphabet, repeatedly check array for all state pairs", "pair_count", "=", "[", "]", "bool_seqs_p", "=", "[", "]", "bool_seqs_ch", "=", "[", "]", "for", "seq", ",", "bs", "in", "[", "(", "seq_p", ",", "bool_seqs_p", ")", ",", "(", "seq_ch", ",", "bool_seqs_ch", ")", "]", ":", "for", "ni", ",", "nuc", "in", "enumerate", "(", "self", ".", "alphabet", ")", ":", "bs", ".", "append", "(", "seq", "==", "nuc", ")", "for", "n1", ",", "nuc1", "in", "enumerate", "(", "self", ".", "alphabet", ")", ":", "if", "(", "self", ".", "gap_index", "is", "None", ")", "or", "(", "not", "ignore_gaps", ")", "or", "(", "n1", "!=", "self", ".", "gap_index", ")", ":", "for", "n2", ",", "nuc2", "in", "enumerate", "(", "self", ".", "alphabet", ")", ":", "if", "(", "self", ".", "gap_index", "is", "None", ")", "or", "(", "not", "ignore_gaps", ")", "or", "(", "n2", "!=", "self", ".", "gap_index", ")", ":", "count", "=", "(", "(", "bool_seqs_p", "[", "n1", "]", "&", "bool_seqs_ch", "[", "n2", "]", ")", "*", "pattern_multiplicity", ")", ".", "sum", "(", ")", "if", "count", ":", "pair_count", ".", "append", "(", "(", "(", "n1", ",", "n2", ")", ",", "count", ")", ")", "else", ":", "# enumerate state pairs of the sequence for large alphabets", "num_seqs", "=", "[", "]", "for", "seq", "in", "[", "seq_p", ",", "seq_ch", "]", ":", "# for each sequence (parent and child) construct a numerical sequence [0,5,3,1,2,3...]", "tmp", "=", "np", ".", "ones_like", "(", "seq", ",", "dtype", "=", "int", ")", "for", "ni", ",", "nuc", "in", "enumerate", "(", "self", ".", "alphabet", ")", ":", "tmp", "[", "seq", "==", "nuc", "]", "=", "ni", "# set each position corresponding to a state to the corresponding index", "num_seqs", ".", "append", "(", "tmp", ")", "pair_count", "=", "defaultdict", "(", "int", ")", "if", "ignore_gaps", ":", "# if gaps are ignored skip positions where one or the other sequence is gapped", "for", "i", "in", "range", "(", "len", "(", "seq_p", ")", ")", ":", "if", "self", ".", "gap_index", "!=", "num_seqs", "[", "0", "]", "[", "i", "]", "and", "self", ".", "gap_index", "!=", "num_seqs", "[", "1", "]", "[", "i", "]", ":", "pair_count", "[", "(", "num_seqs", "[", "0", "]", "[", "i", "]", ",", "num_seqs", "[", "1", "]", "[", "i", "]", ")", "]", "+=", "pattern_multiplicity", "[", "i", "]", "else", ":", "# otherwise, just count", "for", "i", "in", "range", "(", "len", "(", "seq_p", ")", ")", ":", "pair_count", "[", "(", "num_seqs", "[", "0", "]", "[", "i", "]", ",", "num_seqs", "[", "1", "]", "[", "i", "]", ")", "]", "+=", "pattern_multiplicity", "[", "i", "]", "pair_count", "=", "pair_count", ".", "items", "(", ")", "return", "(", "np", ".", "array", "(", "[", "x", "[", "0", "]", "for", "x", "in", "pair_count", "]", ",", "dtype", "=", "int", ")", ",", "# [(child_nuc, parent_nuc),()...]", "np", ".", "array", "(", "[", "x", "[", "1", "]", "for", "x", "in", "pair_count", "]", ",", "dtype", "=", "int", ")", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.prob_t_compressed
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), ()..])` as indicies of pairs of aligned positions. (e.g. 'A'==0, 'C'==1 etc). This only lists all occuring parent-child state pairs, order is irrelevant multiplicity : numpy array The number of times a parent-child state pair is observed. This allows compression of the sequence representation t : float Length of the branch separating parent and child return_log : bool Whether or not to exponentiate the result
treetime/gtr.py
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), ()..])` as indicies of pairs of aligned positions. (e.g. 'A'==0, 'C'==1 etc). This only lists all occuring parent-child state pairs, order is irrelevant multiplicity : numpy array The number of times a parent-child state pair is observed. This allows compression of the sequence representation t : float Length of the branch separating parent and child return_log : bool Whether or not to exponentiate the result ''' if t<0: logP = -ttconf.BIG_NUMBER else: tmp_eQT = self.expQt(t) bad_indices=(tmp_eQT==0) logQt = np.log(tmp_eQT + ttconf.TINY_NUMBER*(bad_indices)) logQt[np.isnan(logQt) | np.isinf(logQt) | bad_indices] = -ttconf.BIG_NUMBER logP = np.sum(logQt[seq_pair[:,1], seq_pair[:,0]]*multiplicity) return logP if return_log else np.exp(logP)
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), ()..])` as indicies of pairs of aligned positions. (e.g. 'A'==0, 'C'==1 etc). This only lists all occuring parent-child state pairs, order is irrelevant multiplicity : numpy array The number of times a parent-child state pair is observed. This allows compression of the sequence representation t : float Length of the branch separating parent and child return_log : bool Whether or not to exponentiate the result ''' if t<0: logP = -ttconf.BIG_NUMBER else: tmp_eQT = self.expQt(t) bad_indices=(tmp_eQT==0) logQt = np.log(tmp_eQT + ttconf.TINY_NUMBER*(bad_indices)) logQt[np.isnan(logQt) | np.isinf(logQt) | bad_indices] = -ttconf.BIG_NUMBER logP = np.sum(logQt[seq_pair[:,1], seq_pair[:,0]]*multiplicity) return logP if return_log else np.exp(logP)
[ "Calculate", "the", "probability", "of", "observing", "a", "sequence", "pair", "at", "a", "distance", "t", "for", "compressed", "sequences" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L631-L664
[ "def", "prob_t_compressed", "(", "self", ",", "seq_pair", ",", "multiplicity", ",", "t", ",", "return_log", "=", "False", ")", ":", "if", "t", "<", "0", ":", "logP", "=", "-", "ttconf", ".", "BIG_NUMBER", "else", ":", "tmp_eQT", "=", "self", ".", "expQt", "(", "t", ")", "bad_indices", "=", "(", "tmp_eQT", "==", "0", ")", "logQt", "=", "np", ".", "log", "(", "tmp_eQT", "+", "ttconf", ".", "TINY_NUMBER", "*", "(", "bad_indices", ")", ")", "logQt", "[", "np", ".", "isnan", "(", "logQt", ")", "|", "np", ".", "isinf", "(", "logQt", ")", "|", "bad_indices", "]", "=", "-", "ttconf", ".", "BIG_NUMBER", "logP", "=", "np", ".", "sum", "(", "logQt", "[", "seq_pair", "[", ":", ",", "1", "]", ",", "seq_pair", "[", ":", ",", "0", "]", "]", "*", "multiplicity", ")", "return", "logP", "if", "return_log", "else", "np", ".", "exp", "(", "logP", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.prob_t
Compute the probability to observe seq_ch (child sequence) after time t starting from seq_p (parent sequence). Parameters ---------- seq_p : character array Parent sequence seq_c : character array Child sequence t : double Time (branch len) separating the profiles. pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. return_log : bool It True, return log-probability. Returns ------- prob : np.array Resulting probability
treetime/gtr.py
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 : character array Parent sequence seq_c : character array Child sequence t : double Time (branch len) separating the profiles. pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. return_log : bool It True, return log-probability. Returns ------- prob : np.array Resulting probability """ seq_pair, multiplicity = self.compress_sequence_pair(seq_p, seq_ch, pattern_multiplicity=pattern_multiplicity, ignore_gaps=ignore_gaps) return self.prob_t_compressed(seq_pair, multiplicity, t, return_log=return_log)
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 : character array Parent sequence seq_c : character array Child sequence t : double Time (branch len) separating the profiles. pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. return_log : bool It True, return log-probability. Returns ------- prob : np.array Resulting probability """ seq_pair, multiplicity = self.compress_sequence_pair(seq_p, seq_ch, pattern_multiplicity=pattern_multiplicity, ignore_gaps=ignore_gaps) return self.prob_t_compressed(seq_pair, multiplicity, t, return_log=return_log)
[ "Compute", "the", "probability", "to", "observe", "seq_ch", "(", "child", "sequence", ")", "after", "time", "t", "starting", "from", "seq_p", "(", "parent", "sequence", ")", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L667-L702
[ "def", "prob_t", "(", "self", ",", "seq_p", ",", "seq_ch", ",", "t", ",", "pattern_multiplicity", "=", "None", ",", "return_log", "=", "False", ",", "ignore_gaps", "=", "True", ")", ":", "seq_pair", ",", "multiplicity", "=", "self", ".", "compress_sequence_pair", "(", "seq_p", ",", "seq_ch", ",", "pattern_multiplicity", "=", "pattern_multiplicity", ",", "ignore_gaps", "=", "ignore_gaps", ")", "return", "self", ".", "prob_t_compressed", "(", "seq_pair", ",", "multiplicity", ",", "t", ",", "return_log", "=", "return_log", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.optimal_t
Find the optimal distance between the two sequences Parameters ---------- seq_p : character array Parent sequence seq_c : character array Child sequence pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. ignore_gaps : bool If True, ignore gaps in distance calculations
treetime/gtr.py
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 pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. ignore_gaps : bool If True, ignore gaps in distance calculations ''' seq_pair, multiplicity = self.compress_sequence_pair(seq_p, seq_ch, pattern_multiplicity = pattern_multiplicity, ignore_gaps=ignore_gaps) return self.optimal_t_compressed(seq_pair, multiplicity)
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 pattern_multiplicity : numpy array If sequences are reduced by combining identical alignment patterns, these multplicities need to be accounted for when counting the number of mutations across a branch. If None, all pattern are assumed to occur exactly once. ignore_gaps : bool If True, ignore gaps in distance calculations ''' seq_pair, multiplicity = self.compress_sequence_pair(seq_p, seq_ch, pattern_multiplicity = pattern_multiplicity, ignore_gaps=ignore_gaps) return self.optimal_t_compressed(seq_pair, multiplicity)
[ "Find", "the", "optimal", "distance", "between", "the", "two", "sequences" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L705-L731
[ "def", "optimal_t", "(", "self", ",", "seq_p", ",", "seq_ch", ",", "pattern_multiplicity", "=", "None", ",", "ignore_gaps", "=", "False", ")", ":", "seq_pair", ",", "multiplicity", "=", "self", ".", "compress_sequence_pair", "(", "seq_p", ",", "seq_ch", ",", "pattern_multiplicity", "=", "pattern_multiplicity", ",", "ignore_gaps", "=", "ignore_gaps", ")", "return", "self", ".", "optimal_t_compressed", "(", "seq_pair", ",", "multiplicity", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.optimal_t_compressed
Find the optimal distance between the two sequences, for compressed sequences Parameters ---------- seq_pair : compressed_sequence_pair Compressed representation of sequences along a branch, either as tuple of state pairs or as tuple of profiles. multiplicity : array Number of times each state pair in seq_pair appears (if profile==False) Number of times an alignment pattern is observed (if profiles==True) profiles : bool, default False The standard branch length optimization assumes fixed sequences at either end of the branch. With profiles==True, optimization is performed while summing over all possible states of the nodes at either end of the branch. Note that the meaning/format of seq_pair and multiplicity depend on the value of profiles.
treetime/gtr.py
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 along a branch, either as tuple of state pairs or as tuple of profiles. multiplicity : array Number of times each state pair in seq_pair appears (if profile==False) Number of times an alignment pattern is observed (if profiles==True) profiles : bool, default False The standard branch length optimization assumes fixed sequences at either end of the branch. With profiles==True, optimization is performed while summing over all possible states of the nodes at either end of the branch. Note that the meaning/format of seq_pair and multiplicity depend on the value of profiles. """ def _neg_prob(t, seq_pair, multiplicity): """ Probability to observe a child given the the parent state, transition matrix, and the time of evolution (branch length). Parameters ---------- t : double Branch length (time between sequences) parent : numpy.array Parent sequence child : numpy.array Child sequence tm : GTR Model of evolution Returns ------- prob : double Negative probability of the two given sequences to be separated by the time t. """ if profiles: res = -1.0*self.prob_t_profiles(seq_pair, multiplicity,t**2, return_log=True) return res else: return -1.0*self.prob_t_compressed(seq_pair, multiplicity,t**2, return_log=True) try: from scipy.optimize import minimize_scalar opt = minimize_scalar(_neg_prob, bounds=[-np.sqrt(ttconf.MAX_BRANCH_LENGTH),np.sqrt(ttconf.MAX_BRANCH_LENGTH)], args=(seq_pair, multiplicity), tol=tol) new_len = opt["x"]**2 if 'success' not in opt: opt['success'] = True self.logger("WARNING: the optimization result does not contain a 'success' flag:"+str(opt),4, warn=True) except: import scipy print('legacy scipy', scipy.__version__) from scipy.optimize import fminbound new_len = fminbound(_neg_prob, -np.sqrt(ttconf.MAX_BRANCH_LENGTH),np.sqrt(ttconf.MAX_BRANCH_LENGTH), args=(seq_pair, multiplicity)) new_len = new_len**2 opt={'success':True} if new_len > .9 * ttconf.MAX_BRANCH_LENGTH: self.logger("WARNING: GTR.optimal_t_compressed -- The branch length seems to be very long!", 4, warn=True) if opt["success"] != True: # return hamming distance: number of state pairs where state differs/all pairs new_len = np.sum(multiplicity[seq_pair[:,1]!=seq_pair[:,0]])/np.sum(multiplicity) return new_len
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 along a branch, either as tuple of state pairs or as tuple of profiles. multiplicity : array Number of times each state pair in seq_pair appears (if profile==False) Number of times an alignment pattern is observed (if profiles==True) profiles : bool, default False The standard branch length optimization assumes fixed sequences at either end of the branch. With profiles==True, optimization is performed while summing over all possible states of the nodes at either end of the branch. Note that the meaning/format of seq_pair and multiplicity depend on the value of profiles. """ def _neg_prob(t, seq_pair, multiplicity): """ Probability to observe a child given the the parent state, transition matrix, and the time of evolution (branch length). Parameters ---------- t : double Branch length (time between sequences) parent : numpy.array Parent sequence child : numpy.array Child sequence tm : GTR Model of evolution Returns ------- prob : double Negative probability of the two given sequences to be separated by the time t. """ if profiles: res = -1.0*self.prob_t_profiles(seq_pair, multiplicity,t**2, return_log=True) return res else: return -1.0*self.prob_t_compressed(seq_pair, multiplicity,t**2, return_log=True) try: from scipy.optimize import minimize_scalar opt = minimize_scalar(_neg_prob, bounds=[-np.sqrt(ttconf.MAX_BRANCH_LENGTH),np.sqrt(ttconf.MAX_BRANCH_LENGTH)], args=(seq_pair, multiplicity), tol=tol) new_len = opt["x"]**2 if 'success' not in opt: opt['success'] = True self.logger("WARNING: the optimization result does not contain a 'success' flag:"+str(opt),4, warn=True) except: import scipy print('legacy scipy', scipy.__version__) from scipy.optimize import fminbound new_len = fminbound(_neg_prob, -np.sqrt(ttconf.MAX_BRANCH_LENGTH),np.sqrt(ttconf.MAX_BRANCH_LENGTH), args=(seq_pair, multiplicity)) new_len = new_len**2 opt={'success':True} if new_len > .9 * ttconf.MAX_BRANCH_LENGTH: self.logger("WARNING: GTR.optimal_t_compressed -- The branch length seems to be very long!", 4, warn=True) if opt["success"] != True: # return hamming distance: number of state pairs where state differs/all pairs new_len = np.sum(multiplicity[seq_pair[:,1]!=seq_pair[:,0]])/np.sum(multiplicity) return new_len
[ "Find", "the", "optimal", "distance", "between", "the", "two", "sequences", "for", "compressed", "sequences" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L734-L818
[ "def", "optimal_t_compressed", "(", "self", ",", "seq_pair", ",", "multiplicity", ",", "profiles", "=", "False", ",", "tol", "=", "1e-10", ")", ":", "def", "_neg_prob", "(", "t", ",", "seq_pair", ",", "multiplicity", ")", ":", "\"\"\"\n Probability to observe a child given the the parent state, transition\n matrix, and the time of evolution (branch length).\n\n Parameters\n ----------\n\n t : double\n Branch length (time between sequences)\n\n parent : numpy.array\n Parent sequence\n\n child : numpy.array\n Child sequence\n\n tm : GTR\n Model of evolution\n\n Returns\n -------\n\n prob : double\n Negative probability of the two given sequences\n to be separated by the time t.\n \"\"\"", "if", "profiles", ":", "res", "=", "-", "1.0", "*", "self", ".", "prob_t_profiles", "(", "seq_pair", ",", "multiplicity", ",", "t", "**", "2", ",", "return_log", "=", "True", ")", "return", "res", "else", ":", "return", "-", "1.0", "*", "self", ".", "prob_t_compressed", "(", "seq_pair", ",", "multiplicity", ",", "t", "**", "2", ",", "return_log", "=", "True", ")", "try", ":", "from", "scipy", ".", "optimize", "import", "minimize_scalar", "opt", "=", "minimize_scalar", "(", "_neg_prob", ",", "bounds", "=", "[", "-", "np", ".", "sqrt", "(", "ttconf", ".", "MAX_BRANCH_LENGTH", ")", ",", "np", ".", "sqrt", "(", "ttconf", ".", "MAX_BRANCH_LENGTH", ")", "]", ",", "args", "=", "(", "seq_pair", ",", "multiplicity", ")", ",", "tol", "=", "tol", ")", "new_len", "=", "opt", "[", "\"x\"", "]", "**", "2", "if", "'success'", "not", "in", "opt", ":", "opt", "[", "'success'", "]", "=", "True", "self", ".", "logger", "(", "\"WARNING: the optimization result does not contain a 'success' flag:\"", "+", "str", "(", "opt", ")", ",", "4", ",", "warn", "=", "True", ")", "except", ":", "import", "scipy", "print", "(", "'legacy scipy'", ",", "scipy", ".", "__version__", ")", "from", "scipy", ".", "optimize", "import", "fminbound", "new_len", "=", "fminbound", "(", "_neg_prob", ",", "-", "np", ".", "sqrt", "(", "ttconf", ".", "MAX_BRANCH_LENGTH", ")", ",", "np", ".", "sqrt", "(", "ttconf", ".", "MAX_BRANCH_LENGTH", ")", ",", "args", "=", "(", "seq_pair", ",", "multiplicity", ")", ")", "new_len", "=", "new_len", "**", "2", "opt", "=", "{", "'success'", ":", "True", "}", "if", "new_len", ">", ".9", "*", "ttconf", ".", "MAX_BRANCH_LENGTH", ":", "self", ".", "logger", "(", "\"WARNING: GTR.optimal_t_compressed -- The branch length seems to be very long!\"", ",", "4", ",", "warn", "=", "True", ")", "if", "opt", "[", "\"success\"", "]", "!=", "True", ":", "# return hamming distance: number of state pairs where state differs/all pairs", "new_len", "=", "np", ".", "sum", "(", "multiplicity", "[", "seq_pair", "[", ":", ",", "1", "]", "!=", "seq_pair", "[", ":", ",", "0", "]", "]", ")", "/", "np", ".", "sum", "(", "multiplicity", ")", "return", "new_len" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.prob_t_profiles
Calculate the probability of observing a node pair at a distance t Parameters ---------- profile_pair: numpy arrays Probability distributions of the nucleotides at either end of the branch. pp[0] = parent, pp[1] = child multiplicity : numpy array The number of times an alignment pattern is observed t : float Length of the branch separating parent and child ignore_gaps: bool If True, ignore mutations to and from gaps in distance calculations return_log : bool Whether or not to exponentiate the result
treetime/gtr.py
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 of the nucleotides at either end of the branch. pp[0] = parent, pp[1] = child multiplicity : numpy array The number of times an alignment pattern is observed t : float Length of the branch separating parent and child ignore_gaps: bool If True, ignore mutations to and from gaps in distance calculations return_log : bool Whether or not to exponentiate the result ''' if t<0: logP = -ttconf.BIG_NUMBER else: Qt = self.expQt(t) if len(Qt.shape)==3: res = np.einsum('ai,ija,aj->a', profile_pair[1], Qt, profile_pair[0]) else: res = np.einsum('ai,ij,aj->a', profile_pair[1], Qt, profile_pair[0]) if ignore_gaps and (self.gap_index is not None): # calculate the probability that neither outgroup/node has a gap non_gap_frac = (1-profile_pair[0][:,self.gap_index])*(1-profile_pair[1][:,self.gap_index]) # weigh log LH by the non-gap probability logP = np.sum(multiplicity*np.log(res)*non_gap_frac) else: logP = np.sum(multiplicity*np.log(res)) return logP if return_log else np.exp(logP)
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 of the nucleotides at either end of the branch. pp[0] = parent, pp[1] = child multiplicity : numpy array The number of times an alignment pattern is observed t : float Length of the branch separating parent and child ignore_gaps: bool If True, ignore mutations to and from gaps in distance calculations return_log : bool Whether or not to exponentiate the result ''' if t<0: logP = -ttconf.BIG_NUMBER else: Qt = self.expQt(t) if len(Qt.shape)==3: res = np.einsum('ai,ija,aj->a', profile_pair[1], Qt, profile_pair[0]) else: res = np.einsum('ai,ij,aj->a', profile_pair[1], Qt, profile_pair[0]) if ignore_gaps and (self.gap_index is not None): # calculate the probability that neither outgroup/node has a gap non_gap_frac = (1-profile_pair[0][:,self.gap_index])*(1-profile_pair[1][:,self.gap_index]) # weigh log LH by the non-gap probability logP = np.sum(multiplicity*np.log(res)*non_gap_frac) else: logP = np.sum(multiplicity*np.log(res)) return logP if return_log else np.exp(logP)
[ "Calculate", "the", "probability", "of", "observing", "a", "node", "pair", "at", "a", "distance", "t" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L821-L861
[ "def", "prob_t_profiles", "(", "self", ",", "profile_pair", ",", "multiplicity", ",", "t", ",", "return_log", "=", "False", ",", "ignore_gaps", "=", "True", ")", ":", "if", "t", "<", "0", ":", "logP", "=", "-", "ttconf", ".", "BIG_NUMBER", "else", ":", "Qt", "=", "self", ".", "expQt", "(", "t", ")", "if", "len", "(", "Qt", ".", "shape", ")", "==", "3", ":", "res", "=", "np", ".", "einsum", "(", "'ai,ija,aj->a'", ",", "profile_pair", "[", "1", "]", ",", "Qt", ",", "profile_pair", "[", "0", "]", ")", "else", ":", "res", "=", "np", ".", "einsum", "(", "'ai,ij,aj->a'", ",", "profile_pair", "[", "1", "]", ",", "Qt", ",", "profile_pair", "[", "0", "]", ")", "if", "ignore_gaps", "and", "(", "self", ".", "gap_index", "is", "not", "None", ")", ":", "# calculate the probability that neither outgroup/node has a gap", "non_gap_frac", "=", "(", "1", "-", "profile_pair", "[", "0", "]", "[", ":", ",", "self", ".", "gap_index", "]", ")", "*", "(", "1", "-", "profile_pair", "[", "1", "]", "[", ":", ",", "self", ".", "gap_index", "]", ")", "# weigh log LH by the non-gap probability", "logP", "=", "np", ".", "sum", "(", "multiplicity", "*", "np", ".", "log", "(", "res", ")", "*", "non_gap_frac", ")", "else", ":", "logP", "=", "np", ".", "sum", "(", "multiplicity", "*", "np", ".", "log", "(", "res", ")", ")", "return", "logP", "if", "return_log", "else", "np", ".", "exp", "(", "logP", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.propagate_profile
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 Sequence profile. Shape = (L, a), where L - sequence length, a - alphabet size. t : double Time to propagate return_log: bool If True, return log-probability Returns ------- res : np.array Profile of the sequence after time t in the past. Shape = (L, a), where L - sequence length, a - alphabet size.
treetime/gtr.py
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 Sequence profile. Shape = (L, a), where L - sequence length, a - alphabet size. t : double Time to propagate return_log: bool If True, return log-probability Returns ------- res : np.array Profile of the sequence after time t in the past. Shape = (L, a), where L - sequence length, a - alphabet size. """ Qt = self.expQt(t) res = profile.dot(Qt) return np.log(res) if return_log else res
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 Sequence profile. Shape = (L, a), where L - sequence length, a - alphabet size. t : double Time to propagate return_log: bool If True, return log-probability Returns ------- res : np.array Profile of the sequence after time t in the past. Shape = (L, a), where L - sequence length, a - alphabet size. """ Qt = self.expQt(t) res = profile.dot(Qt) return np.log(res) if return_log else res
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L864-L894
[ "def", "propagate_profile", "(", "self", ",", "profile", ",", "t", ",", "return_log", "=", "False", ")", ":", "Qt", "=", "self", ".", "expQt", "(", "t", ")", "res", "=", "profile", ".", "dot", "(", "Qt", ")", "return", "np", ".", "log", "(", "res", ")", "if", "return_log", "else", "res" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.evolve
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 - sequence length, a - alphabet size. t : double Time to propagate return_log: bool If True, return log-probability Returns ------- res : np.array Profile of the sequence after time t in the future. Shape = (L, a), where L - sequence length, a - alphabet size.
treetime/gtr.py
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 - sequence length, a - alphabet size. t : double Time to propagate return_log: bool If True, return log-probability Returns ------- res : np.array Profile of the sequence after time t in the future. Shape = (L, a), where L - sequence length, a - alphabet size. """ Qt = self.expQt(t).T res = profile.dot(Qt) return np.log(res) if return_log else res
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 - sequence length, a - alphabet size. t : double Time to propagate return_log: bool If True, return log-probability Returns ------- res : np.array Profile of the sequence after time t in the future. Shape = (L, a), where L - sequence length, a - alphabet size. """ Qt = self.expQt(t).T res = profile.dot(Qt) return np.log(res) if return_log else res
[ "Compute", "the", "probability", "of", "the", "sequence", "state", "of", "the", "child", "at", "time", "t", "later", "given", "the", "parent", "profile", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L897-L925
[ "def", "evolve", "(", "self", ",", "profile", ",", "t", ",", "return_log", "=", "False", ")", ":", "Qt", "=", "self", ".", "expQt", "(", "t", ")", ".", "T", "res", "=", "profile", ".", "dot", "(", "Qt", ")", "return", "np", ".", "log", "(", "res", ")", "if", "return_log", "else", "res" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR._exp_lt
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).
treetime/gtr.py
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). """ return np.exp(self.mu * t * self.eigenvals)
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). """ return np.exp(self.mu * t * self.eigenvals)
[ "Parameters", "----------" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L928-L943
[ "def", "_exp_lt", "(", "self", ",", "t", ")", ":", "return", "np", ".", "exp", "(", "self", ".", "mu", "*", "t", "*", "self", ".", "eigenvals", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.expQt
Parameters ---------- t : float Time to propagate Returns -------- expQt : numpy.array Matrix exponential of exo(Qt)
treetime/gtr.py
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.v.dot(eLambdaT.dot(self.v_inv)) # This is P(nuc1 | given nuc_2) return np.maximum(0,Qs)
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.v.dot(eLambdaT.dot(self.v_inv)) # This is P(nuc1 | given nuc_2) return np.maximum(0,Qs)
[ "Parameters", "----------" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L946-L962
[ "def", "expQt", "(", "self", ",", "t", ")", ":", "eLambdaT", "=", "np", ".", "diag", "(", "self", ".", "_exp_lt", "(", "t", ")", ")", "# vector length = a", "Qs", "=", "self", ".", "v", ".", "dot", "(", "eLambdaT", ".", "dot", "(", "self", ".", "v_inv", ")", ")", "# This is P(nuc1 | given nuc_2)", "return", "np", ".", "maximum", "(", "0", ",", "Qs", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.expQsds
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)
treetime/gtr.py
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) # vector length = a Qsds = self.v.dot(lambda_eLambdaT.dot(self.v_inv)) return Qsds
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) # vector length = a Qsds = self.v.dot(lambda_eLambdaT.dot(self.v_inv)) return Qsds
[ "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", ")" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L971-L980
[ "def", "expQsds", "(", "self", ",", "s", ")", ":", "lambda_eLambdaT", "=", "np", ".", "diag", "(", "2.0", "*", "self", ".", "_exp_lt", "(", "s", "**", "2", ")", "*", "self", ".", "eigenvals", "*", "s", ")", "# vector length = a", "Qsds", "=", "self", ".", "v", ".", "dot", "(", "lambda_eLambdaT", ".", "dot", "(", "self", ".", "v_inv", ")", ")", "return", "Qsds" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.expQsdsds
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
treetime/gtr.py
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*(4.0*t*self.eigenvals**2 + 2.0*self.eigenvals)) Qsdsds = self.v.dot(lambda_eLambdaT.dot(self.v_inv)) return Qsdsds
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*(4.0*t*self.eigenvals**2 + 2.0*self.eigenvals)) Qsdsds = self.v.dot(lambda_eLambdaT.dot(self.v_inv)) return Qsdsds
[ "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" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L983-L994
[ "def", "expQsdsds", "(", "self", ",", "s", ")", ":", "t", "=", "s", "**", "2", "elt", "=", "self", ".", "_exp_lt", "(", "t", ")", "lambda_eLambdaT", "=", "np", ".", "diag", "(", "elt", "*", "(", "4.0", "*", "t", "*", "self", ".", "eigenvals", "**", "2", "+", "2.0", "*", "self", ".", "eigenvals", ")", ")", "Qsdsds", "=", "self", ".", "v", ".", "dot", "(", "lambda_eLambdaT", ".", "dot", "(", "self", ".", "v_inv", ")", ")", "return", "Qsdsds" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
GTR.sequence_logLH
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 pattern_multiplicity : numpy_array The number of times each position in sequence is observed in the initial alignment. If None, sequence is assumed to be not compressed
treetime/gtr.py
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 pattern_multiplicity : numpy_array The number of times each position in sequence is observed in the initial alignment. If None, sequence is assumed to be not compressed """ if pattern_multiplicity is None: pattern_multiplicity = np.ones_like(seq, dtype=float) return np.sum([np.sum((seq==state)*pattern_multiplicity*np.log(self.Pi[si])) for si,state in enumerate(self.alphabet)])
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 pattern_multiplicity : numpy_array The number of times each position in sequence is observed in the initial alignment. If None, sequence is assumed to be not compressed """ if pattern_multiplicity is None: pattern_multiplicity = np.ones_like(seq, dtype=float) return np.sum([np.sum((seq==state)*pattern_multiplicity*np.log(self.Pi[si])) for si,state in enumerate(self.alphabet)])
[ "Returns", "the", "log", "-", "likelihood", "of", "sampling", "a", "sequence", "from", "equilibrium", "frequency", ".", "Expects", "a", "sequence", "as", "numpy", "array" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/gtr.py#L997-L1016
[ "def", "sequence_logLH", "(", "self", ",", "seq", ",", "pattern_multiplicity", "=", "None", ")", ":", "if", "pattern_multiplicity", "is", "None", ":", "pattern_multiplicity", "=", "np", ".", "ones_like", "(", "seq", ",", "dtype", "=", "float", ")", "return", "np", ".", "sum", "(", "[", "np", ".", "sum", "(", "(", "seq", "==", "state", ")", "*", "pattern_multiplicity", "*", "np", ".", "log", "(", "self", ".", "Pi", "[", "si", "]", ")", ")", "for", "si", ",", "state", "in", "enumerate", "(", "self", ".", "alphabet", ")", "]", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
plot_vs_years
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 shaded boxes indicating blocks of years. Will be inferred if not specified. To switch off drawing of boxes, set to 0 ax : matplotlib axes Axes to be used to plot, will create new axis if None confidence : tuple, float Draw confidence intervals. This assumes that marginal time tree inference was run. Confidence intervals are either specified as an interval of the posterior distribution like (0.05, 0.95) or as the weight of the maximal posterior region , e.g. 0.9 **kwargs : dict Key word arguments that are passed down to Phylo.draw
treetime/treetime.py
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 shaded boxes indicating blocks of years. Will be inferred if not specified. To switch off drawing of boxes, set to 0 ax : matplotlib axes Axes to be used to plot, will create new axis if None confidence : tuple, float Draw confidence intervals. This assumes that marginal time tree inference was run. Confidence intervals are either specified as an interval of the posterior distribution like (0.05, 0.95) or as the weight of the maximal posterior region , e.g. 0.9 **kwargs : dict Key word arguments that are passed down to Phylo.draw ''' import matplotlib.pyplot as plt tt.branch_length_to_years() nleafs = tt.tree.count_terminals() if ax is None: fig = plt.figure(figsize=(12,10)) ax = plt.subplot(111) else: fig = None # draw tree if "label_func" not in kwargs: kwargs["label_func"] = lambda x:x.name if (x.is_terminal() and nleafs<30) else "" Phylo.draw(tt.tree, axes=ax, **kwargs) offset = tt.tree.root.numdate - tt.tree.root.branch_length date_range = np.max([n.numdate for n in tt.tree.get_terminals()])-offset # estimate year intervals if not explicitly specified if step is None or (step>0 and date_range/step>100): step = 10**np.floor(np.log10(date_range)) if date_range/step<2: step/=5 elif date_range/step<5: step/=2 step = max(1.0/12,step) # set axis labels if step: dtick = step min_tick = step*(offset//step) extra = dtick if dtick<date_range else dtick tick_vals = np.arange(min_tick, min_tick+date_range+extra, dtick) xticks = tick_vals - offset else: xticks = ax.get_xticks() dtick = xticks[1]-xticks[0] shift = offset - dtick*(offset//dtick) xticks -= shift tick_vals = [x+offset-shift for x in xticks] ax.set_xticks(xticks) ax.set_xticklabels(map(str, tick_vals)) ax.set_xlabel('year') ax.set_ylabel('') ax.set_xlim((0,date_range)) # put shaded boxes to delineate years if step: ylim = ax.get_ylim() xlim = ax.get_xlim() from matplotlib.patches import Rectangle for yi,year in enumerate(np.arange(np.floor(tick_vals[0]), tick_vals[-1]+.01, step)): pos = year - offset r = Rectangle((pos, ylim[1]-5), step, ylim[0]-ylim[1]+10, facecolor=[0.7+0.1*(1+yi%2)] * 3, edgecolor=[1,1,1]) ax.add_patch(r) if year in tick_vals and pos>=xlim[0] and pos<=xlim[1] and ticks: label_str = str(step*(year//step)) if step<1 else str(int(year)) ax.text(pos,ylim[0]-0.04*(ylim[1]-ylim[0]), label_str, horizontalalignment='center') ax.set_axis_off() # add confidence intervals to the tree graph -- grey bars if confidence: tree_layout(tt.tree) if not hasattr(tt.tree.root, "marginal_inverse_cdf"): print("marginal time tree reconstruction required for confidence intervals") return ttconf.ERROR elif type(confidence) is float: cfunc = tt.get_max_posterior_region elif len(confidence)==2: cfunc = tt.get_confidence_interval else: print("confidence needs to be either a float (for max posterior region) or a two numbers specifying lower and upper bounds") return ttconf.ERROR for n in tt.tree.find_clades(): pos = cfunc(n, confidence) ax.plot(pos-offset, np.ones(len(pos))*n.ypos, lw=3, c=(0.5,0.5,0.5)) return fig, ax
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 shaded boxes indicating blocks of years. Will be inferred if not specified. To switch off drawing of boxes, set to 0 ax : matplotlib axes Axes to be used to plot, will create new axis if None confidence : tuple, float Draw confidence intervals. This assumes that marginal time tree inference was run. Confidence intervals are either specified as an interval of the posterior distribution like (0.05, 0.95) or as the weight of the maximal posterior region , e.g. 0.9 **kwargs : dict Key word arguments that are passed down to Phylo.draw ''' import matplotlib.pyplot as plt tt.branch_length_to_years() nleafs = tt.tree.count_terminals() if ax is None: fig = plt.figure(figsize=(12,10)) ax = plt.subplot(111) else: fig = None # draw tree if "label_func" not in kwargs: kwargs["label_func"] = lambda x:x.name if (x.is_terminal() and nleafs<30) else "" Phylo.draw(tt.tree, axes=ax, **kwargs) offset = tt.tree.root.numdate - tt.tree.root.branch_length date_range = np.max([n.numdate for n in tt.tree.get_terminals()])-offset # estimate year intervals if not explicitly specified if step is None or (step>0 and date_range/step>100): step = 10**np.floor(np.log10(date_range)) if date_range/step<2: step/=5 elif date_range/step<5: step/=2 step = max(1.0/12,step) # set axis labels if step: dtick = step min_tick = step*(offset//step) extra = dtick if dtick<date_range else dtick tick_vals = np.arange(min_tick, min_tick+date_range+extra, dtick) xticks = tick_vals - offset else: xticks = ax.get_xticks() dtick = xticks[1]-xticks[0] shift = offset - dtick*(offset//dtick) xticks -= shift tick_vals = [x+offset-shift for x in xticks] ax.set_xticks(xticks) ax.set_xticklabels(map(str, tick_vals)) ax.set_xlabel('year') ax.set_ylabel('') ax.set_xlim((0,date_range)) # put shaded boxes to delineate years if step: ylim = ax.get_ylim() xlim = ax.get_xlim() from matplotlib.patches import Rectangle for yi,year in enumerate(np.arange(np.floor(tick_vals[0]), tick_vals[-1]+.01, step)): pos = year - offset r = Rectangle((pos, ylim[1]-5), step, ylim[0]-ylim[1]+10, facecolor=[0.7+0.1*(1+yi%2)] * 3, edgecolor=[1,1,1]) ax.add_patch(r) if year in tick_vals and pos>=xlim[0] and pos<=xlim[1] and ticks: label_str = str(step*(year//step)) if step<1 else str(int(year)) ax.text(pos,ylim[0]-0.04*(ylim[1]-ylim[0]), label_str, horizontalalignment='center') ax.set_axis_off() # add confidence intervals to the tree graph -- grey bars if confidence: tree_layout(tt.tree) if not hasattr(tt.tree.root, "marginal_inverse_cdf"): print("marginal time tree reconstruction required for confidence intervals") return ttconf.ERROR elif type(confidence) is float: cfunc = tt.get_max_posterior_region elif len(confidence)==2: cfunc = tt.get_confidence_interval else: print("confidence needs to be either a float (for max posterior region) or a two numbers specifying lower and upper bounds") return ttconf.ERROR for n in tt.tree.find_clades(): pos = cfunc(n, confidence) ax.plot(pos-offset, np.ones(len(pos))*n.ypos, lw=3, c=(0.5,0.5,0.5)) return fig, ax
[ "Converts", "branch", "length", "to", "years", "and", "plots", "the", "time", "tree", "on", "a", "time", "axis", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L798-L904
[ "def", "plot_vs_years", "(", "tt", ",", "step", "=", "None", ",", "ax", "=", "None", ",", "confidence", "=", "None", ",", "ticks", "=", "True", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "tt", ".", "branch_length_to_years", "(", ")", "nleafs", "=", "tt", ".", "tree", ".", "count_terminals", "(", ")", "if", "ax", "is", "None", ":", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "(", "12", ",", "10", ")", ")", "ax", "=", "plt", ".", "subplot", "(", "111", ")", "else", ":", "fig", "=", "None", "# draw tree", "if", "\"label_func\"", "not", "in", "kwargs", ":", "kwargs", "[", "\"label_func\"", "]", "=", "lambda", "x", ":", "x", ".", "name", "if", "(", "x", ".", "is_terminal", "(", ")", "and", "nleafs", "<", "30", ")", "else", "\"\"", "Phylo", ".", "draw", "(", "tt", ".", "tree", ",", "axes", "=", "ax", ",", "*", "*", "kwargs", ")", "offset", "=", "tt", ".", "tree", ".", "root", ".", "numdate", "-", "tt", ".", "tree", ".", "root", ".", "branch_length", "date_range", "=", "np", ".", "max", "(", "[", "n", ".", "numdate", "for", "n", "in", "tt", ".", "tree", ".", "get_terminals", "(", ")", "]", ")", "-", "offset", "# estimate year intervals if not explicitly specified", "if", "step", "is", "None", "or", "(", "step", ">", "0", "and", "date_range", "/", "step", ">", "100", ")", ":", "step", "=", "10", "**", "np", ".", "floor", "(", "np", ".", "log10", "(", "date_range", ")", ")", "if", "date_range", "/", "step", "<", "2", ":", "step", "/=", "5", "elif", "date_range", "/", "step", "<", "5", ":", "step", "/=", "2", "step", "=", "max", "(", "1.0", "/", "12", ",", "step", ")", "# set axis labels", "if", "step", ":", "dtick", "=", "step", "min_tick", "=", "step", "*", "(", "offset", "//", "step", ")", "extra", "=", "dtick", "if", "dtick", "<", "date_range", "else", "dtick", "tick_vals", "=", "np", ".", "arange", "(", "min_tick", ",", "min_tick", "+", "date_range", "+", "extra", ",", "dtick", ")", "xticks", "=", "tick_vals", "-", "offset", "else", ":", "xticks", "=", "ax", ".", "get_xticks", "(", ")", "dtick", "=", "xticks", "[", "1", "]", "-", "xticks", "[", "0", "]", "shift", "=", "offset", "-", "dtick", "*", "(", "offset", "//", "dtick", ")", "xticks", "-=", "shift", "tick_vals", "=", "[", "x", "+", "offset", "-", "shift", "for", "x", "in", "xticks", "]", "ax", ".", "set_xticks", "(", "xticks", ")", "ax", ".", "set_xticklabels", "(", "map", "(", "str", ",", "tick_vals", ")", ")", "ax", ".", "set_xlabel", "(", "'year'", ")", "ax", ".", "set_ylabel", "(", "''", ")", "ax", ".", "set_xlim", "(", "(", "0", ",", "date_range", ")", ")", "# put shaded boxes to delineate years", "if", "step", ":", "ylim", "=", "ax", ".", "get_ylim", "(", ")", "xlim", "=", "ax", ".", "get_xlim", "(", ")", "from", "matplotlib", ".", "patches", "import", "Rectangle", "for", "yi", ",", "year", "in", "enumerate", "(", "np", ".", "arange", "(", "np", ".", "floor", "(", "tick_vals", "[", "0", "]", ")", ",", "tick_vals", "[", "-", "1", "]", "+", ".01", ",", "step", ")", ")", ":", "pos", "=", "year", "-", "offset", "r", "=", "Rectangle", "(", "(", "pos", ",", "ylim", "[", "1", "]", "-", "5", ")", ",", "step", ",", "ylim", "[", "0", "]", "-", "ylim", "[", "1", "]", "+", "10", ",", "facecolor", "=", "[", "0.7", "+", "0.1", "*", "(", "1", "+", "yi", "%", "2", ")", "]", "*", "3", ",", "edgecolor", "=", "[", "1", ",", "1", ",", "1", "]", ")", "ax", ".", "add_patch", "(", "r", ")", "if", "year", "in", "tick_vals", "and", "pos", ">=", "xlim", "[", "0", "]", "and", "pos", "<=", "xlim", "[", "1", "]", "and", "ticks", ":", "label_str", "=", "str", "(", "step", "*", "(", "year", "//", "step", ")", ")", "if", "step", "<", "1", "else", "str", "(", "int", "(", "year", ")", ")", "ax", ".", "text", "(", "pos", ",", "ylim", "[", "0", "]", "-", "0.04", "*", "(", "ylim", "[", "1", "]", "-", "ylim", "[", "0", "]", ")", ",", "label_str", ",", "horizontalalignment", "=", "'center'", ")", "ax", ".", "set_axis_off", "(", ")", "# add confidence intervals to the tree graph -- grey bars", "if", "confidence", ":", "tree_layout", "(", "tt", ".", "tree", ")", "if", "not", "hasattr", "(", "tt", ".", "tree", ".", "root", ",", "\"marginal_inverse_cdf\"", ")", ":", "print", "(", "\"marginal time tree reconstruction required for confidence intervals\"", ")", "return", "ttconf", ".", "ERROR", "elif", "type", "(", "confidence", ")", "is", "float", ":", "cfunc", "=", "tt", ".", "get_max_posterior_region", "elif", "len", "(", "confidence", ")", "==", "2", ":", "cfunc", "=", "tt", ".", "get_confidence_interval", "else", ":", "print", "(", "\"confidence needs to be either a float (for max posterior region) or a two numbers specifying lower and upper bounds\"", ")", "return", "ttconf", ".", "ERROR", "for", "n", "in", "tt", ".", "tree", ".", "find_clades", "(", ")", ":", "pos", "=", "cfunc", "(", "n", ",", "confidence", ")", "ax", ".", "plot", "(", "pos", "-", "offset", ",", "np", ".", "ones", "(", "len", "(", "pos", ")", ")", "*", "n", ".", "ypos", ",", "lw", "=", "3", ",", "c", "=", "(", "0.5", ",", "0.5", ",", "0.5", ")", ")", "return", "fig", ",", "ax" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime.run
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. Parameters ---------- root : str Try to find better root position on a given tree. If string is passed, the root will be searched according to the specified method. If none, use tree as-is. See :py:meth:`treetime.TreeTime.reroot` for available rooting methods. infer_gtr : bool If True, infer GTR model relaxed_clock : dic If not None, use autocorrelated molecular clock model. Specify the clock parameters as :code:`{slack:<slack>, coupling:<coupling>}` dictionary. n_iqd : int If not None, filter tree nodes which do not obey the molecular clock for the particular tree. The nodes, which deviate more than :code:`n_iqd` interquantile intervals from the molecular clock regression will be marked as 'BAD' and not used in the TreeTime analysis resolve_polytomies : bool If True, attempt to resolve multiple mergers max_iter : int Maximum number of iterations to optimize the tree Tc : float, str If not None, use coalescent model to correct the branch lengths by introducing merger costs. If Tc is float, it is interpreted as the coalescence time scale If Tc is str, it should be one of (:code:`opt`, :code:`const`, :code:`skyline`) fixed_clock_rate : float Fixed clock rate to be used. If None, infer clock rate from the molecular clock. time_marginal : bool If True, perform a final round of marginal reconstruction of the node's positions. sequence_marginal : bool, optional use marginal reconstruction for ancestral sequences branch_length_mode : str Should be one of: :code:`joint`, :code:`marginal`, :code:`input`. If 'input', rely on the branch lengths in the input tree and skip directly to the maximum-likelihood ancestral sequence reconstruction. Otherwise, perform preliminary sequence reconstruction using parsimony algorithm and do branch length optimization vary_rate : bool or float, optional redo the time tree estimation for rates +/- one standard deviation. if a float is passed, it is interpreted as standard deviation, otherwise this standard deviation is estimated from the root-to-tip regression use_covariation : bool, optional default False, if False, rate estimates will be performed using simple regression ignoring phylogenetic covaration between nodes. **kwargs Keyword arguments needed by the downstream functions Returns ------- TreeTime error/succces code : str return value depending on success or error
treetime/treetime.py
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): """ 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. Parameters ---------- root : str Try to find better root position on a given tree. If string is passed, the root will be searched according to the specified method. If none, use tree as-is. See :py:meth:`treetime.TreeTime.reroot` for available rooting methods. infer_gtr : bool If True, infer GTR model relaxed_clock : dic If not None, use autocorrelated molecular clock model. Specify the clock parameters as :code:`{slack:<slack>, coupling:<coupling>}` dictionary. n_iqd : int If not None, filter tree nodes which do not obey the molecular clock for the particular tree. The nodes, which deviate more than :code:`n_iqd` interquantile intervals from the molecular clock regression will be marked as 'BAD' and not used in the TreeTime analysis resolve_polytomies : bool If True, attempt to resolve multiple mergers max_iter : int Maximum number of iterations to optimize the tree Tc : float, str If not None, use coalescent model to correct the branch lengths by introducing merger costs. If Tc is float, it is interpreted as the coalescence time scale If Tc is str, it should be one of (:code:`opt`, :code:`const`, :code:`skyline`) fixed_clock_rate : float Fixed clock rate to be used. If None, infer clock rate from the molecular clock. time_marginal : bool If True, perform a final round of marginal reconstruction of the node's positions. sequence_marginal : bool, optional use marginal reconstruction for ancestral sequences branch_length_mode : str Should be one of: :code:`joint`, :code:`marginal`, :code:`input`. If 'input', rely on the branch lengths in the input tree and skip directly to the maximum-likelihood ancestral sequence reconstruction. Otherwise, perform preliminary sequence reconstruction using parsimony algorithm and do branch length optimization vary_rate : bool or float, optional redo the time tree estimation for rates +/- one standard deviation. if a float is passed, it is interpreted as standard deviation, otherwise this standard deviation is estimated from the root-to-tip regression use_covariation : bool, optional default False, if False, rate estimates will be performed using simple regression ignoring phylogenetic covaration between nodes. **kwargs Keyword arguments needed by the downstream functions Returns ------- TreeTime error/succces code : str return value depending on success or error """ # register the specified covaration mode self.use_covariation = use_covariation if (self.tree is None) or (self.aln is None and self.seq_len is None): self.logger("TreeTime.run: ERROR, alignment or tree are missing", 0) return ttconf.ERROR if (self.aln is None): branch_length_mode='input' self._set_branch_length_mode(branch_length_mode) # determine how to reconstruct and sample sequences seq_kwargs = {"marginal_sequences":sequence_marginal or (self.branch_length_mode=='marginal'), "sample_from_profile":"root"} tt_kwargs = {'clock_rate':fixed_clock_rate, 'time_marginal':False} tt_kwargs.update(kwargs) seq_LH = 0 if "fixed_pi" in kwargs: seq_kwargs["fixed_pi"] = kwargs["fixed_pi"] if "do_marginal" in kwargs: time_marginal=kwargs["do_marginal"] # initially, infer ancestral sequences and infer gtr model if desired if self.branch_length_mode=='input': if self.aln: self.infer_ancestral_sequences(infer_gtr=infer_gtr, **seq_kwargs) self.prune_short_branches() else: self.optimize_sequences_and_branch_length(infer_gtr=infer_gtr, max_iter=1, prune_short=True, **seq_kwargs) avg_root_to_tip = np.mean([x.dist2root for x in self.tree.get_terminals()]) # optionally reroot the tree either by oldest, best regression or with a specific leaf if n_iqd or root=='clock_filter': if "plot_rtt" in kwargs and kwargs["plot_rtt"]: plot_rtt=True else: plot_rtt=False reroot_mechanism = 'least-squares' if root=='clock_filter' else root if self.clock_filter(reroot=reroot_mechanism, n_iqd=n_iqd, plot=plot_rtt)==ttconf.ERROR: return ttconf.ERROR elif root is not None: if self.reroot(root=root)==ttconf.ERROR: return ttconf.ERROR if self.branch_length_mode=='input': if self.aln: self.infer_ancestral_sequences(**seq_kwargs) else: self.optimize_sequences_and_branch_length(max_iter=1, prune_short=False, **seq_kwargs) # infer time tree and optionally resolve polytomies self.logger("###TreeTime.run: INITIAL ROUND",0) self.make_time_tree(**tt_kwargs) if self.aln: seq_LH = self.tree.sequence_marginal_LH if seq_kwargs['marginal_sequences'] else self.tree.sequence_joint_LH self.LH =[[seq_LH, self.tree.positional_joint_LH, 0]] if root is not None and max_iter: if self.reroot(root='least-squares' if root=='clock_filter' else root)==ttconf.ERROR: return ttconf.ERROR # iteratively reconstruct ancestral sequences and re-infer # time tree to ensure convergence. niter = 0 ndiff = 0 need_new_time_tree=False while niter < max_iter: self.logger("###TreeTime.run: ITERATION %d out of %d iterations"%(niter+1,max_iter),0) # add coalescent prior if Tc: if Tc=='skyline' and niter<max_iter-1: tmpTc='const' else: tmpTc=Tc self.add_coalescent_model(tmpTc, **kwargs) need_new_time_tree = True # estimate a relaxed molecular clock if relaxed_clock: print("relaxed_clock", relaxed_clock) self.relaxed_clock(**relaxed_clock) need_new_time_tree = True n_resolved=0 if resolve_polytomies: # if polytomies are found, rerun the entire procedure n_resolved = self.resolve_polytomies() if n_resolved: self.prepare_tree() if self.branch_length_mode!='input': # otherwise reoptimize branch length while preserving branches without mutations self.optimize_sequences_and_branch_length(prune_short=False, max_iter=0, **seq_kwargs) need_new_time_tree = True if need_new_time_tree: self.make_time_tree(**tt_kwargs) if self.aln: ndiff = self.infer_ancestral_sequences('ml',**seq_kwargs) else: # no refinements, just iterate if self.aln: ndiff = self.infer_ancestral_sequences('ml',**seq_kwargs) self.make_time_tree(**tt_kwargs) self.tree.coalescent_joint_LH = self.merger_model.total_LH() if Tc else 0.0 if self.aln: seq_LH = self.tree.sequence_marginal_LH if seq_kwargs['marginal_sequences'] else self.tree.sequence_joint_LH self.LH.append([seq_LH, self.tree.positional_joint_LH, self.tree.coalescent_joint_LH]) niter+=1 if ndiff==0 and n_resolved==0 and Tc!='skyline': self.logger("###TreeTime.run: CONVERGED",0) break # if the rate is too be varied and the rate estimate has a valid confidence interval # rerun the estimation for variations of the rate if vary_rate: if type(vary_rate)==float: res = self.calc_rate_susceptibility(rate_std=vary_rate, params=tt_kwargs) elif self.clock_model['valid_confidence']: res = self.calc_rate_susceptibility(params=tt_kwargs) else: res = ttconf.ERROR if res==ttconf.ERROR: self.logger("TreeTime.run: rate variation failed and can't be used for confidence estimation", 1, warn=True) # if marginal reconstruction requested, make one more round with marginal=True # this will set marginal_pos_LH, which to be used as error bar estimations if time_marginal: self.logger("###TreeTime.run: FINAL ROUND - confidence estimation via marginal reconstruction", 0) tt_kwargs['time_marginal']=time_marginal self.make_time_tree(**tt_kwargs) # explicitly print out which branches are bad and whose dates don't correspond to the input dates bad_branches =[n for n in self.tree.get_terminals() if n.bad_branch and n.raw_date_constraint] if bad_branches: self.logger("TreeTime: The following tips don't fit the clock model, " "please remove them from the tree. Their dates have been reset:",0,warn=True) for n in bad_branches: self.logger("%s, input date: %s, apparent date: %1.2f"%(n.name, str(n.raw_date_constraint), n.numdate),0,warn=True) return ttconf.SUCCESS
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): """ 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. Parameters ---------- root : str Try to find better root position on a given tree. If string is passed, the root will be searched according to the specified method. If none, use tree as-is. See :py:meth:`treetime.TreeTime.reroot` for available rooting methods. infer_gtr : bool If True, infer GTR model relaxed_clock : dic If not None, use autocorrelated molecular clock model. Specify the clock parameters as :code:`{slack:<slack>, coupling:<coupling>}` dictionary. n_iqd : int If not None, filter tree nodes which do not obey the molecular clock for the particular tree. The nodes, which deviate more than :code:`n_iqd` interquantile intervals from the molecular clock regression will be marked as 'BAD' and not used in the TreeTime analysis resolve_polytomies : bool If True, attempt to resolve multiple mergers max_iter : int Maximum number of iterations to optimize the tree Tc : float, str If not None, use coalescent model to correct the branch lengths by introducing merger costs. If Tc is float, it is interpreted as the coalescence time scale If Tc is str, it should be one of (:code:`opt`, :code:`const`, :code:`skyline`) fixed_clock_rate : float Fixed clock rate to be used. If None, infer clock rate from the molecular clock. time_marginal : bool If True, perform a final round of marginal reconstruction of the node's positions. sequence_marginal : bool, optional use marginal reconstruction for ancestral sequences branch_length_mode : str Should be one of: :code:`joint`, :code:`marginal`, :code:`input`. If 'input', rely on the branch lengths in the input tree and skip directly to the maximum-likelihood ancestral sequence reconstruction. Otherwise, perform preliminary sequence reconstruction using parsimony algorithm and do branch length optimization vary_rate : bool or float, optional redo the time tree estimation for rates +/- one standard deviation. if a float is passed, it is interpreted as standard deviation, otherwise this standard deviation is estimated from the root-to-tip regression use_covariation : bool, optional default False, if False, rate estimates will be performed using simple regression ignoring phylogenetic covaration between nodes. **kwargs Keyword arguments needed by the downstream functions Returns ------- TreeTime error/succces code : str return value depending on success or error """ # register the specified covaration mode self.use_covariation = use_covariation if (self.tree is None) or (self.aln is None and self.seq_len is None): self.logger("TreeTime.run: ERROR, alignment or tree are missing", 0) return ttconf.ERROR if (self.aln is None): branch_length_mode='input' self._set_branch_length_mode(branch_length_mode) # determine how to reconstruct and sample sequences seq_kwargs = {"marginal_sequences":sequence_marginal or (self.branch_length_mode=='marginal'), "sample_from_profile":"root"} tt_kwargs = {'clock_rate':fixed_clock_rate, 'time_marginal':False} tt_kwargs.update(kwargs) seq_LH = 0 if "fixed_pi" in kwargs: seq_kwargs["fixed_pi"] = kwargs["fixed_pi"] if "do_marginal" in kwargs: time_marginal=kwargs["do_marginal"] # initially, infer ancestral sequences and infer gtr model if desired if self.branch_length_mode=='input': if self.aln: self.infer_ancestral_sequences(infer_gtr=infer_gtr, **seq_kwargs) self.prune_short_branches() else: self.optimize_sequences_and_branch_length(infer_gtr=infer_gtr, max_iter=1, prune_short=True, **seq_kwargs) avg_root_to_tip = np.mean([x.dist2root for x in self.tree.get_terminals()]) # optionally reroot the tree either by oldest, best regression or with a specific leaf if n_iqd or root=='clock_filter': if "plot_rtt" in kwargs and kwargs["plot_rtt"]: plot_rtt=True else: plot_rtt=False reroot_mechanism = 'least-squares' if root=='clock_filter' else root if self.clock_filter(reroot=reroot_mechanism, n_iqd=n_iqd, plot=plot_rtt)==ttconf.ERROR: return ttconf.ERROR elif root is not None: if self.reroot(root=root)==ttconf.ERROR: return ttconf.ERROR if self.branch_length_mode=='input': if self.aln: self.infer_ancestral_sequences(**seq_kwargs) else: self.optimize_sequences_and_branch_length(max_iter=1, prune_short=False, **seq_kwargs) # infer time tree and optionally resolve polytomies self.logger("###TreeTime.run: INITIAL ROUND",0) self.make_time_tree(**tt_kwargs) if self.aln: seq_LH = self.tree.sequence_marginal_LH if seq_kwargs['marginal_sequences'] else self.tree.sequence_joint_LH self.LH =[[seq_LH, self.tree.positional_joint_LH, 0]] if root is not None and max_iter: if self.reroot(root='least-squares' if root=='clock_filter' else root)==ttconf.ERROR: return ttconf.ERROR # iteratively reconstruct ancestral sequences and re-infer # time tree to ensure convergence. niter = 0 ndiff = 0 need_new_time_tree=False while niter < max_iter: self.logger("###TreeTime.run: ITERATION %d out of %d iterations"%(niter+1,max_iter),0) # add coalescent prior if Tc: if Tc=='skyline' and niter<max_iter-1: tmpTc='const' else: tmpTc=Tc self.add_coalescent_model(tmpTc, **kwargs) need_new_time_tree = True # estimate a relaxed molecular clock if relaxed_clock: print("relaxed_clock", relaxed_clock) self.relaxed_clock(**relaxed_clock) need_new_time_tree = True n_resolved=0 if resolve_polytomies: # if polytomies are found, rerun the entire procedure n_resolved = self.resolve_polytomies() if n_resolved: self.prepare_tree() if self.branch_length_mode!='input': # otherwise reoptimize branch length while preserving branches without mutations self.optimize_sequences_and_branch_length(prune_short=False, max_iter=0, **seq_kwargs) need_new_time_tree = True if need_new_time_tree: self.make_time_tree(**tt_kwargs) if self.aln: ndiff = self.infer_ancestral_sequences('ml',**seq_kwargs) else: # no refinements, just iterate if self.aln: ndiff = self.infer_ancestral_sequences('ml',**seq_kwargs) self.make_time_tree(**tt_kwargs) self.tree.coalescent_joint_LH = self.merger_model.total_LH() if Tc else 0.0 if self.aln: seq_LH = self.tree.sequence_marginal_LH if seq_kwargs['marginal_sequences'] else self.tree.sequence_joint_LH self.LH.append([seq_LH, self.tree.positional_joint_LH, self.tree.coalescent_joint_LH]) niter+=1 if ndiff==0 and n_resolved==0 and Tc!='skyline': self.logger("###TreeTime.run: CONVERGED",0) break # if the rate is too be varied and the rate estimate has a valid confidence interval # rerun the estimation for variations of the rate if vary_rate: if type(vary_rate)==float: res = self.calc_rate_susceptibility(rate_std=vary_rate, params=tt_kwargs) elif self.clock_model['valid_confidence']: res = self.calc_rate_susceptibility(params=tt_kwargs) else: res = ttconf.ERROR if res==ttconf.ERROR: self.logger("TreeTime.run: rate variation failed and can't be used for confidence estimation", 1, warn=True) # if marginal reconstruction requested, make one more round with marginal=True # this will set marginal_pos_LH, which to be used as error bar estimations if time_marginal: self.logger("###TreeTime.run: FINAL ROUND - confidence estimation via marginal reconstruction", 0) tt_kwargs['time_marginal']=time_marginal self.make_time_tree(**tt_kwargs) # explicitly print out which branches are bad and whose dates don't correspond to the input dates bad_branches =[n for n in self.tree.get_terminals() if n.bad_branch and n.raw_date_constraint] if bad_branches: self.logger("TreeTime: The following tips don't fit the clock model, " "please remove them from the tree. Their dates have been reset:",0,warn=True) for n in bad_branches: self.logger("%s, input date: %s, apparent date: %1.2f"%(n.name, str(n.raw_date_constraint), n.numdate),0,warn=True) return ttconf.SUCCESS
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L36-L271
[ "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", ")", ":", "# register the specified covaration mode", "self", ".", "use_covariation", "=", "use_covariation", "if", "(", "self", ".", "tree", "is", "None", ")", "or", "(", "self", ".", "aln", "is", "None", "and", "self", ".", "seq_len", "is", "None", ")", ":", "self", ".", "logger", "(", "\"TreeTime.run: ERROR, alignment or tree are missing\"", ",", "0", ")", "return", "ttconf", ".", "ERROR", "if", "(", "self", ".", "aln", "is", "None", ")", ":", "branch_length_mode", "=", "'input'", "self", ".", "_set_branch_length_mode", "(", "branch_length_mode", ")", "# determine how to reconstruct and sample sequences", "seq_kwargs", "=", "{", "\"marginal_sequences\"", ":", "sequence_marginal", "or", "(", "self", ".", "branch_length_mode", "==", "'marginal'", ")", ",", "\"sample_from_profile\"", ":", "\"root\"", "}", "tt_kwargs", "=", "{", "'clock_rate'", ":", "fixed_clock_rate", ",", "'time_marginal'", ":", "False", "}", "tt_kwargs", ".", "update", "(", "kwargs", ")", "seq_LH", "=", "0", "if", "\"fixed_pi\"", "in", "kwargs", ":", "seq_kwargs", "[", "\"fixed_pi\"", "]", "=", "kwargs", "[", "\"fixed_pi\"", "]", "if", "\"do_marginal\"", "in", "kwargs", ":", "time_marginal", "=", "kwargs", "[", "\"do_marginal\"", "]", "# initially, infer ancestral sequences and infer gtr model if desired", "if", "self", ".", "branch_length_mode", "==", "'input'", ":", "if", "self", ".", "aln", ":", "self", ".", "infer_ancestral_sequences", "(", "infer_gtr", "=", "infer_gtr", ",", "*", "*", "seq_kwargs", ")", "self", ".", "prune_short_branches", "(", ")", "else", ":", "self", ".", "optimize_sequences_and_branch_length", "(", "infer_gtr", "=", "infer_gtr", ",", "max_iter", "=", "1", ",", "prune_short", "=", "True", ",", "*", "*", "seq_kwargs", ")", "avg_root_to_tip", "=", "np", ".", "mean", "(", "[", "x", ".", "dist2root", "for", "x", "in", "self", ".", "tree", ".", "get_terminals", "(", ")", "]", ")", "# optionally reroot the tree either by oldest, best regression or with a specific leaf", "if", "n_iqd", "or", "root", "==", "'clock_filter'", ":", "if", "\"plot_rtt\"", "in", "kwargs", "and", "kwargs", "[", "\"plot_rtt\"", "]", ":", "plot_rtt", "=", "True", "else", ":", "plot_rtt", "=", "False", "reroot_mechanism", "=", "'least-squares'", "if", "root", "==", "'clock_filter'", "else", "root", "if", "self", ".", "clock_filter", "(", "reroot", "=", "reroot_mechanism", ",", "n_iqd", "=", "n_iqd", ",", "plot", "=", "plot_rtt", ")", "==", "ttconf", ".", "ERROR", ":", "return", "ttconf", ".", "ERROR", "elif", "root", "is", "not", "None", ":", "if", "self", ".", "reroot", "(", "root", "=", "root", ")", "==", "ttconf", ".", "ERROR", ":", "return", "ttconf", ".", "ERROR", "if", "self", ".", "branch_length_mode", "==", "'input'", ":", "if", "self", ".", "aln", ":", "self", ".", "infer_ancestral_sequences", "(", "*", "*", "seq_kwargs", ")", "else", ":", "self", ".", "optimize_sequences_and_branch_length", "(", "max_iter", "=", "1", ",", "prune_short", "=", "False", ",", "*", "*", "seq_kwargs", ")", "# infer time tree and optionally resolve polytomies", "self", ".", "logger", "(", "\"###TreeTime.run: INITIAL ROUND\"", ",", "0", ")", "self", ".", "make_time_tree", "(", "*", "*", "tt_kwargs", ")", "if", "self", ".", "aln", ":", "seq_LH", "=", "self", ".", "tree", ".", "sequence_marginal_LH", "if", "seq_kwargs", "[", "'marginal_sequences'", "]", "else", "self", ".", "tree", ".", "sequence_joint_LH", "self", ".", "LH", "=", "[", "[", "seq_LH", ",", "self", ".", "tree", ".", "positional_joint_LH", ",", "0", "]", "]", "if", "root", "is", "not", "None", "and", "max_iter", ":", "if", "self", ".", "reroot", "(", "root", "=", "'least-squares'", "if", "root", "==", "'clock_filter'", "else", "root", ")", "==", "ttconf", ".", "ERROR", ":", "return", "ttconf", ".", "ERROR", "# iteratively reconstruct ancestral sequences and re-infer", "# time tree to ensure convergence.", "niter", "=", "0", "ndiff", "=", "0", "need_new_time_tree", "=", "False", "while", "niter", "<", "max_iter", ":", "self", ".", "logger", "(", "\"###TreeTime.run: ITERATION %d out of %d iterations\"", "%", "(", "niter", "+", "1", ",", "max_iter", ")", ",", "0", ")", "# add coalescent prior", "if", "Tc", ":", "if", "Tc", "==", "'skyline'", "and", "niter", "<", "max_iter", "-", "1", ":", "tmpTc", "=", "'const'", "else", ":", "tmpTc", "=", "Tc", "self", ".", "add_coalescent_model", "(", "tmpTc", ",", "*", "*", "kwargs", ")", "need_new_time_tree", "=", "True", "# estimate a relaxed molecular clock", "if", "relaxed_clock", ":", "print", "(", "\"relaxed_clock\"", ",", "relaxed_clock", ")", "self", ".", "relaxed_clock", "(", "*", "*", "relaxed_clock", ")", "need_new_time_tree", "=", "True", "n_resolved", "=", "0", "if", "resolve_polytomies", ":", "# if polytomies are found, rerun the entire procedure", "n_resolved", "=", "self", ".", "resolve_polytomies", "(", ")", "if", "n_resolved", ":", "self", ".", "prepare_tree", "(", ")", "if", "self", ".", "branch_length_mode", "!=", "'input'", ":", "# otherwise reoptimize branch length while preserving branches without mutations", "self", ".", "optimize_sequences_and_branch_length", "(", "prune_short", "=", "False", ",", "max_iter", "=", "0", ",", "*", "*", "seq_kwargs", ")", "need_new_time_tree", "=", "True", "if", "need_new_time_tree", ":", "self", ".", "make_time_tree", "(", "*", "*", "tt_kwargs", ")", "if", "self", ".", "aln", ":", "ndiff", "=", "self", ".", "infer_ancestral_sequences", "(", "'ml'", ",", "*", "*", "seq_kwargs", ")", "else", ":", "# no refinements, just iterate", "if", "self", ".", "aln", ":", "ndiff", "=", "self", ".", "infer_ancestral_sequences", "(", "'ml'", ",", "*", "*", "seq_kwargs", ")", "self", ".", "make_time_tree", "(", "*", "*", "tt_kwargs", ")", "self", ".", "tree", ".", "coalescent_joint_LH", "=", "self", ".", "merger_model", ".", "total_LH", "(", ")", "if", "Tc", "else", "0.0", "if", "self", ".", "aln", ":", "seq_LH", "=", "self", ".", "tree", ".", "sequence_marginal_LH", "if", "seq_kwargs", "[", "'marginal_sequences'", "]", "else", "self", ".", "tree", ".", "sequence_joint_LH", "self", ".", "LH", ".", "append", "(", "[", "seq_LH", ",", "self", ".", "tree", ".", "positional_joint_LH", ",", "self", ".", "tree", ".", "coalescent_joint_LH", "]", ")", "niter", "+=", "1", "if", "ndiff", "==", "0", "and", "n_resolved", "==", "0", "and", "Tc", "!=", "'skyline'", ":", "self", ".", "logger", "(", "\"###TreeTime.run: CONVERGED\"", ",", "0", ")", "break", "# if the rate is too be varied and the rate estimate has a valid confidence interval", "# rerun the estimation for variations of the rate", "if", "vary_rate", ":", "if", "type", "(", "vary_rate", ")", "==", "float", ":", "res", "=", "self", ".", "calc_rate_susceptibility", "(", "rate_std", "=", "vary_rate", ",", "params", "=", "tt_kwargs", ")", "elif", "self", ".", "clock_model", "[", "'valid_confidence'", "]", ":", "res", "=", "self", ".", "calc_rate_susceptibility", "(", "params", "=", "tt_kwargs", ")", "else", ":", "res", "=", "ttconf", ".", "ERROR", "if", "res", "==", "ttconf", ".", "ERROR", ":", "self", ".", "logger", "(", "\"TreeTime.run: rate variation failed and can't be used for confidence estimation\"", ",", "1", ",", "warn", "=", "True", ")", "# if marginal reconstruction requested, make one more round with marginal=True", "# this will set marginal_pos_LH, which to be used as error bar estimations", "if", "time_marginal", ":", "self", ".", "logger", "(", "\"###TreeTime.run: FINAL ROUND - confidence estimation via marginal reconstruction\"", ",", "0", ")", "tt_kwargs", "[", "'time_marginal'", "]", "=", "time_marginal", "self", ".", "make_time_tree", "(", "*", "*", "tt_kwargs", ")", "# explicitly print out which branches are bad and whose dates don't correspond to the input dates", "bad_branches", "=", "[", "n", "for", "n", "in", "self", ".", "tree", ".", "get_terminals", "(", ")", "if", "n", ".", "bad_branch", "and", "n", ".", "raw_date_constraint", "]", "if", "bad_branches", ":", "self", ".", "logger", "(", "\"TreeTime: The following tips don't fit the clock model, \"", "\"please remove them from the tree. Their dates have been reset:\"", ",", "0", ",", "warn", "=", "True", ")", "for", "n", "in", "bad_branches", ":", "self", ".", "logger", "(", "\"%s, input date: %s, apparent date: %1.2f\"", "%", "(", "n", ".", "name", ",", "str", "(", "n", ".", "raw_date_constraint", ")", ",", "n", ".", "numdate", ")", ",", "0", ",", "warn", "=", "True", ")", "return", "ttconf", ".", "SUCCESS" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime._set_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 maximal branch length in the tree is longer than 0.05, this will default to 'input'. Otherwise set to 'joint'
treetime/treetime.py
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 maximal branch length in the tree is longer than 0.05, this will default to 'input'. Otherwise set to 'joint' ''' if branch_length_mode in ['joint', 'marginal', 'input']: self.branch_length_mode = branch_length_mode elif self.aln: bl_dis = [n.branch_length for n in self.tree.find_clades() if n.up] max_bl = np.max(bl_dis) if max_bl>0.1: bl_mode = 'input' else: bl_mode = 'joint' self.logger("TreeTime._set_branch_length_mode: maximum branch length is %1.3e, using branch length mode %s"%(max_bl, bl_mode),1) self.branch_length_mode = bl_mode else: self.branch_length_mode = 'input'
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 maximal branch length in the tree is longer than 0.05, this will default to 'input'. Otherwise set to 'joint' ''' if branch_length_mode in ['joint', 'marginal', 'input']: self.branch_length_mode = branch_length_mode elif self.aln: bl_dis = [n.branch_length for n in self.tree.find_clades() if n.up] max_bl = np.max(bl_dis) if max_bl>0.1: bl_mode = 'input' else: bl_mode = 'joint' self.logger("TreeTime._set_branch_length_mode: maximum branch length is %1.3e, using branch length mode %s"%(max_bl, bl_mode),1) self.branch_length_mode = bl_mode else: self.branch_length_mode = 'input'
[ "if", "branch_length", "mode", "is", "not", "explicitly", "set", "set", "according", "to", "empirical", "branch", "length", "distribution", "in", "input", "tree" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L274-L298
[ "def", "_set_branch_length_mode", "(", "self", ",", "branch_length_mode", ")", ":", "if", "branch_length_mode", "in", "[", "'joint'", ",", "'marginal'", ",", "'input'", "]", ":", "self", ".", "branch_length_mode", "=", "branch_length_mode", "elif", "self", ".", "aln", ":", "bl_dis", "=", "[", "n", ".", "branch_length", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", "if", "n", ".", "up", "]", "max_bl", "=", "np", ".", "max", "(", "bl_dis", ")", "if", "max_bl", ">", "0.1", ":", "bl_mode", "=", "'input'", "else", ":", "bl_mode", "=", "'joint'", "self", ".", "logger", "(", "\"TreeTime._set_branch_length_mode: maximum branch length is %1.3e, using branch length mode %s\"", "%", "(", "max_bl", ",", "bl_mode", ")", ",", "1", ")", "self", ".", "branch_length_mode", "=", "bl_mode", "else", ":", "self", ".", "branch_length_mode", "=", "'input'" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime.clock_filter
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 ---------- reroot : str Method to find the best root in the tree (see :py:meth:`treetime.TreeTime.reroot` for options) n_iqd : int Number of iqd intervals. The outlier nodes are those which do not fall into :math:`IQD\cdot n_iqd` interval (:math:`IQD` is the interval between 75\ :sup:`th` and 25\ :sup:`th` percentiles) If None, the default (3) assumed plot : bool If True, plot the results
treetime/treetime.py
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 ---------- reroot : str Method to find the best root in the tree (see :py:meth:`treetime.TreeTime.reroot` for options) n_iqd : int Number of iqd intervals. The outlier nodes are those which do not fall into :math:`IQD\cdot n_iqd` interval (:math:`IQD` is the interval between 75\ :sup:`th` and 25\ :sup:`th` percentiles) If None, the default (3) assumed plot : bool If True, plot the results ''' if n_iqd is None: n_iqd = ttconf.NIQD if type(reroot) is list and len(reroot)==1: reroot=str(reroot[0]) terminals = self.tree.get_terminals() if reroot: if self.reroot(root='least-squares' if reroot=='best' else reroot, covariation=False)==ttconf.ERROR: return ttconf.ERROR else: self.get_clock_model(covariation=False) clock_rate = self.clock_model['slope'] icpt = self.clock_model['intercept'] res = {} for node in terminals: if hasattr(node, 'raw_date_constraint') and (node.raw_date_constraint is not None): res[node] = node.dist2root - clock_rate*np.mean(node.raw_date_constraint) - icpt residuals = np.array(list(res.values())) iqd = np.percentile(residuals,75) - np.percentile(residuals,25) for node,r in res.items(): if abs(r)>n_iqd*iqd and node.up.up is not None: self.logger('TreeTime.ClockFilter: marking %s as outlier, residual %f interquartile distances'%(node.name,r/iqd), 3, warn=True) node.bad_branch=True else: node.bad_branch=False # redo root estimation after outlier removal if reroot and self.reroot(root=reroot)==ttconf.ERROR: return ttconf.ERROR if plot: self.plot_root_to_tip() return ttconf.SUCCESS
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 ---------- reroot : str Method to find the best root in the tree (see :py:meth:`treetime.TreeTime.reroot` for options) n_iqd : int Number of iqd intervals. The outlier nodes are those which do not fall into :math:`IQD\cdot n_iqd` interval (:math:`IQD` is the interval between 75\ :sup:`th` and 25\ :sup:`th` percentiles) If None, the default (3) assumed plot : bool If True, plot the results ''' if n_iqd is None: n_iqd = ttconf.NIQD if type(reroot) is list and len(reroot)==1: reroot=str(reroot[0]) terminals = self.tree.get_terminals() if reroot: if self.reroot(root='least-squares' if reroot=='best' else reroot, covariation=False)==ttconf.ERROR: return ttconf.ERROR else: self.get_clock_model(covariation=False) clock_rate = self.clock_model['slope'] icpt = self.clock_model['intercept'] res = {} for node in terminals: if hasattr(node, 'raw_date_constraint') and (node.raw_date_constraint is not None): res[node] = node.dist2root - clock_rate*np.mean(node.raw_date_constraint) - icpt residuals = np.array(list(res.values())) iqd = np.percentile(residuals,75) - np.percentile(residuals,25) for node,r in res.items(): if abs(r)>n_iqd*iqd and node.up.up is not None: self.logger('TreeTime.ClockFilter: marking %s as outlier, residual %f interquartile distances'%(node.name,r/iqd), 3, warn=True) node.bad_branch=True else: node.bad_branch=False # redo root estimation after outlier removal if reroot and self.reroot(root=reroot)==ttconf.ERROR: return ttconf.ERROR if plot: self.plot_root_to_tip() return ttconf.SUCCESS
[ "Labels", "outlier", "branches", "that", "don", "t", "seem", "to", "follow", "a", "molecular", "clock", "and", "excludes", "them", "from", "subsequent", "molecular", "clock", "estimation", "and", "the", "timetree", "propagation", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L301-L358
[ "def", "clock_filter", "(", "self", ",", "reroot", "=", "'least-squares'", ",", "n_iqd", "=", "None", ",", "plot", "=", "False", ")", ":", "if", "n_iqd", "is", "None", ":", "n_iqd", "=", "ttconf", ".", "NIQD", "if", "type", "(", "reroot", ")", "is", "list", "and", "len", "(", "reroot", ")", "==", "1", ":", "reroot", "=", "str", "(", "reroot", "[", "0", "]", ")", "terminals", "=", "self", ".", "tree", ".", "get_terminals", "(", ")", "if", "reroot", ":", "if", "self", ".", "reroot", "(", "root", "=", "'least-squares'", "if", "reroot", "==", "'best'", "else", "reroot", ",", "covariation", "=", "False", ")", "==", "ttconf", ".", "ERROR", ":", "return", "ttconf", ".", "ERROR", "else", ":", "self", ".", "get_clock_model", "(", "covariation", "=", "False", ")", "clock_rate", "=", "self", ".", "clock_model", "[", "'slope'", "]", "icpt", "=", "self", ".", "clock_model", "[", "'intercept'", "]", "res", "=", "{", "}", "for", "node", "in", "terminals", ":", "if", "hasattr", "(", "node", ",", "'raw_date_constraint'", ")", "and", "(", "node", ".", "raw_date_constraint", "is", "not", "None", ")", ":", "res", "[", "node", "]", "=", "node", ".", "dist2root", "-", "clock_rate", "*", "np", ".", "mean", "(", "node", ".", "raw_date_constraint", ")", "-", "icpt", "residuals", "=", "np", ".", "array", "(", "list", "(", "res", ".", "values", "(", ")", ")", ")", "iqd", "=", "np", ".", "percentile", "(", "residuals", ",", "75", ")", "-", "np", ".", "percentile", "(", "residuals", ",", "25", ")", "for", "node", ",", "r", "in", "res", ".", "items", "(", ")", ":", "if", "abs", "(", "r", ")", ">", "n_iqd", "*", "iqd", "and", "node", ".", "up", ".", "up", "is", "not", "None", ":", "self", ".", "logger", "(", "'TreeTime.ClockFilter: marking %s as outlier, residual %f interquartile distances'", "%", "(", "node", ".", "name", ",", "r", "/", "iqd", ")", ",", "3", ",", "warn", "=", "True", ")", "node", ".", "bad_branch", "=", "True", "else", ":", "node", ".", "bad_branch", "=", "False", "# redo root estimation after outlier removal", "if", "reroot", "and", "self", ".", "reroot", "(", "root", "=", "reroot", ")", "==", "ttconf", ".", "ERROR", ":", "return", "ttconf", ".", "ERROR", "if", "plot", ":", "self", ".", "plot_root_to_tip", "(", ")", "return", "ttconf", ".", "SUCCESS" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime.plot_root_to_tip
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 axes If not None, use the provided matplotlib axes to plot the results
treetime/treetime.py
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 axes If not None, use the provided matplotlib axes to plot the results """ Treg = self.setup_TreeRegression() if self.clock_model and 'cov' in self.clock_model: cf = self.clock_model['valid_confidence'] else: cf = False Treg.clock_plot(ax=ax, add_internal=add_internal, confidence=cf, n_sigma=2, regression=self.clock_model)
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 axes If not None, use the provided matplotlib axes to plot the results """ Treg = self.setup_TreeRegression() if self.clock_model and 'cov' in self.clock_model: cf = self.clock_model['valid_confidence'] else: cf = False Treg.clock_plot(ax=ax, add_internal=add_internal, confidence=cf, n_sigma=2, regression=self.clock_model)
[ "Plot", "root", "-", "to", "-", "tip", "regression" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L361-L382
[ "def", "plot_root_to_tip", "(", "self", ",", "add_internal", "=", "False", ",", "label", "=", "True", ",", "ax", "=", "None", ")", ":", "Treg", "=", "self", ".", "setup_TreeRegression", "(", ")", "if", "self", ".", "clock_model", "and", "'cov'", "in", "self", ".", "clock_model", ":", "cf", "=", "self", ".", "clock_model", "[", "'valid_confidence'", "]", "else", ":", "cf", "=", "False", "Treg", ".", "clock_plot", "(", "ax", "=", "ax", ",", "add_internal", "=", "add_internal", ",", "confidence", "=", "cf", ",", "n_sigma", "=", "2", ",", "regression", "=", "self", ".", "clock_model", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime.reroot
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:`best`, `least-squares` - minimize squared residual or likelihood of root-to-tip regression :code:`min_dev` - minimize variation of root-to-tip distance :code:`oldest` - reroot on the oldest node :code:`<node_name>` - reroot to the node with name :code:`<node_name>` :code:`[<node_name1>, <node_name2>, ...]` - reroot to the MRCA of these nodes force_positive : bool only consider positive rates when searching for the optimal root covariation : bool account for covariation in root-to-tip regression
treetime/treetime.py
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:`best`, `least-squares` - minimize squared residual or likelihood of root-to-tip regression :code:`min_dev` - minimize variation of root-to-tip distance :code:`oldest` - reroot on the oldest node :code:`<node_name>` - reroot to the node with name :code:`<node_name>` :code:`[<node_name1>, <node_name2>, ...]` - reroot to the MRCA of these nodes force_positive : bool only consider positive rates when searching for the optimal root covariation : bool account for covariation in root-to-tip regression """ if type(root) is list and len(root)==1: root=str(root[0]) if root=='best': root='least-squares' use_cov = self.use_covariation if covariation is None else covariation self.logger("TreeTime.reroot: with method or node: %s"%root,0) for n in self.tree.find_clades(): n.branch_length=n.mutation_length if (type(root) is str) and \ (root in rerooting_mechanisms or root in deprecated_rerooting_mechanisms): if root in deprecated_rerooting_mechanisms: if "ML" in root: use_cov=True self.logger('TreeTime.reroot: rerooting mechanisms %s has been renamed to %s' %(root, deprecated_rerooting_mechanisms[root]), 1, warn=True) root = deprecated_rerooting_mechanisms[root] self.logger("TreeTime.reroot: rerooting will %s covariance and shared ancestry."%("account for" if use_cov else "ignore"),0) new_root = self._find_best_root(covariation=use_cov, slope = 0.0 if root.startswith('min_dev') else None, force_positive=force_positive and (not root.startswith('min_dev'))) else: if isinstance(root,Phylo.BaseTree.Clade): new_root = root elif isinstance(root, list): new_root = self.tree.common_ancestor(*root) elif root in self._leaves_lookup: new_root = self._leaves_lookup[root] elif root=='oldest': new_root = sorted([n for n in self.tree.get_terminals() if n.raw_date_constraint is not None], key=lambda x:np.mean(x.raw_date_constraint))[0] else: self.logger('TreeTime.reroot -- ERROR: unsupported rooting mechanisms or root not found',0,warn=True) return ttconf.ERROR #this forces a bifurcating root, as we want. Branch lengths will be reoptimized anyway. #(Without outgroup_branch_length, gives a trifurcating root, but this will mean #mutations may have to occur multiple times.) self.tree.root_with_outgroup(new_root, outgroup_branch_length=new_root.branch_length/2) self.get_clock_model(covariation=use_cov) if new_root == ttconf.ERROR: return ttconf.ERROR self.logger("TreeTime.reroot: Tree was re-rooted to node " +('new_node' if new_root.name is None else new_root.name), 2) self.tree.root.branch_length = self.one_mutation self.tree.root.clock_length = self.one_mutation self.tree.root.raw_date_constraint = None if hasattr(new_root, 'time_before_present'): self.tree.root.time_before_present = new_root.time_before_present if hasattr(new_root, 'numdate'): self.tree.root.numdate = new_root.numdate # set root.gamma bc root doesn't have a branch_length_interpolator but gamma is needed if not hasattr(self.tree.root, 'gamma'): self.tree.root.gamma = 1.0 for n in self.tree.find_clades(): n.mutation_length = n.branch_length if not hasattr(n, 'clock_length'): n.clock_length = n.branch_length self.prepare_tree() self.get_clock_model(covariation=self.use_covariation) return ttconf.SUCCESS
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:`best`, `least-squares` - minimize squared residual or likelihood of root-to-tip regression :code:`min_dev` - minimize variation of root-to-tip distance :code:`oldest` - reroot on the oldest node :code:`<node_name>` - reroot to the node with name :code:`<node_name>` :code:`[<node_name1>, <node_name2>, ...]` - reroot to the MRCA of these nodes force_positive : bool only consider positive rates when searching for the optimal root covariation : bool account for covariation in root-to-tip regression """ if type(root) is list and len(root)==1: root=str(root[0]) if root=='best': root='least-squares' use_cov = self.use_covariation if covariation is None else covariation self.logger("TreeTime.reroot: with method or node: %s"%root,0) for n in self.tree.find_clades(): n.branch_length=n.mutation_length if (type(root) is str) and \ (root in rerooting_mechanisms or root in deprecated_rerooting_mechanisms): if root in deprecated_rerooting_mechanisms: if "ML" in root: use_cov=True self.logger('TreeTime.reroot: rerooting mechanisms %s has been renamed to %s' %(root, deprecated_rerooting_mechanisms[root]), 1, warn=True) root = deprecated_rerooting_mechanisms[root] self.logger("TreeTime.reroot: rerooting will %s covariance and shared ancestry."%("account for" if use_cov else "ignore"),0) new_root = self._find_best_root(covariation=use_cov, slope = 0.0 if root.startswith('min_dev') else None, force_positive=force_positive and (not root.startswith('min_dev'))) else: if isinstance(root,Phylo.BaseTree.Clade): new_root = root elif isinstance(root, list): new_root = self.tree.common_ancestor(*root) elif root in self._leaves_lookup: new_root = self._leaves_lookup[root] elif root=='oldest': new_root = sorted([n for n in self.tree.get_terminals() if n.raw_date_constraint is not None], key=lambda x:np.mean(x.raw_date_constraint))[0] else: self.logger('TreeTime.reroot -- ERROR: unsupported rooting mechanisms or root not found',0,warn=True) return ttconf.ERROR #this forces a bifurcating root, as we want. Branch lengths will be reoptimized anyway. #(Without outgroup_branch_length, gives a trifurcating root, but this will mean #mutations may have to occur multiple times.) self.tree.root_with_outgroup(new_root, outgroup_branch_length=new_root.branch_length/2) self.get_clock_model(covariation=use_cov) if new_root == ttconf.ERROR: return ttconf.ERROR self.logger("TreeTime.reroot: Tree was re-rooted to node " +('new_node' if new_root.name is None else new_root.name), 2) self.tree.root.branch_length = self.one_mutation self.tree.root.clock_length = self.one_mutation self.tree.root.raw_date_constraint = None if hasattr(new_root, 'time_before_present'): self.tree.root.time_before_present = new_root.time_before_present if hasattr(new_root, 'numdate'): self.tree.root.numdate = new_root.numdate # set root.gamma bc root doesn't have a branch_length_interpolator but gamma is needed if not hasattr(self.tree.root, 'gamma'): self.tree.root.gamma = 1.0 for n in self.tree.find_clades(): n.mutation_length = n.branch_length if not hasattr(n, 'clock_length'): n.clock_length = n.branch_length self.prepare_tree() self.get_clock_model(covariation=self.use_covariation) return ttconf.SUCCESS
[ "Find", "best", "root", "and", "re", "-", "root", "the", "tree", "to", "the", "new", "root" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L385-L482
[ "def", "reroot", "(", "self", ",", "root", "=", "'least-squares'", ",", "force_positive", "=", "True", ",", "covariation", "=", "None", ")", ":", "if", "type", "(", "root", ")", "is", "list", "and", "len", "(", "root", ")", "==", "1", ":", "root", "=", "str", "(", "root", "[", "0", "]", ")", "if", "root", "==", "'best'", ":", "root", "=", "'least-squares'", "use_cov", "=", "self", ".", "use_covariation", "if", "covariation", "is", "None", "else", "covariation", "self", ".", "logger", "(", "\"TreeTime.reroot: with method or node: %s\"", "%", "root", ",", "0", ")", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "n", ".", "branch_length", "=", "n", ".", "mutation_length", "if", "(", "type", "(", "root", ")", "is", "str", ")", "and", "(", "root", "in", "rerooting_mechanisms", "or", "root", "in", "deprecated_rerooting_mechanisms", ")", ":", "if", "root", "in", "deprecated_rerooting_mechanisms", ":", "if", "\"ML\"", "in", "root", ":", "use_cov", "=", "True", "self", ".", "logger", "(", "'TreeTime.reroot: rerooting mechanisms %s has been renamed to %s'", "%", "(", "root", ",", "deprecated_rerooting_mechanisms", "[", "root", "]", ")", ",", "1", ",", "warn", "=", "True", ")", "root", "=", "deprecated_rerooting_mechanisms", "[", "root", "]", "self", ".", "logger", "(", "\"TreeTime.reroot: rerooting will %s covariance and shared ancestry.\"", "%", "(", "\"account for\"", "if", "use_cov", "else", "\"ignore\"", ")", ",", "0", ")", "new_root", "=", "self", ".", "_find_best_root", "(", "covariation", "=", "use_cov", ",", "slope", "=", "0.0", "if", "root", ".", "startswith", "(", "'min_dev'", ")", "else", "None", ",", "force_positive", "=", "force_positive", "and", "(", "not", "root", ".", "startswith", "(", "'min_dev'", ")", ")", ")", "else", ":", "if", "isinstance", "(", "root", ",", "Phylo", ".", "BaseTree", ".", "Clade", ")", ":", "new_root", "=", "root", "elif", "isinstance", "(", "root", ",", "list", ")", ":", "new_root", "=", "self", ".", "tree", ".", "common_ancestor", "(", "*", "root", ")", "elif", "root", "in", "self", ".", "_leaves_lookup", ":", "new_root", "=", "self", ".", "_leaves_lookup", "[", "root", "]", "elif", "root", "==", "'oldest'", ":", "new_root", "=", "sorted", "(", "[", "n", "for", "n", "in", "self", ".", "tree", ".", "get_terminals", "(", ")", "if", "n", ".", "raw_date_constraint", "is", "not", "None", "]", ",", "key", "=", "lambda", "x", ":", "np", ".", "mean", "(", "x", ".", "raw_date_constraint", ")", ")", "[", "0", "]", "else", ":", "self", ".", "logger", "(", "'TreeTime.reroot -- ERROR: unsupported rooting mechanisms or root not found'", ",", "0", ",", "warn", "=", "True", ")", "return", "ttconf", ".", "ERROR", "#this forces a bifurcating root, as we want. Branch lengths will be reoptimized anyway.", "#(Without outgroup_branch_length, gives a trifurcating root, but this will mean", "#mutations may have to occur multiple times.)", "self", ".", "tree", ".", "root_with_outgroup", "(", "new_root", ",", "outgroup_branch_length", "=", "new_root", ".", "branch_length", "/", "2", ")", "self", ".", "get_clock_model", "(", "covariation", "=", "use_cov", ")", "if", "new_root", "==", "ttconf", ".", "ERROR", ":", "return", "ttconf", ".", "ERROR", "self", ".", "logger", "(", "\"TreeTime.reroot: Tree was re-rooted to node \"", "+", "(", "'new_node'", "if", "new_root", ".", "name", "is", "None", "else", "new_root", ".", "name", ")", ",", "2", ")", "self", ".", "tree", ".", "root", ".", "branch_length", "=", "self", ".", "one_mutation", "self", ".", "tree", ".", "root", ".", "clock_length", "=", "self", ".", "one_mutation", "self", ".", "tree", ".", "root", ".", "raw_date_constraint", "=", "None", "if", "hasattr", "(", "new_root", ",", "'time_before_present'", ")", ":", "self", ".", "tree", ".", "root", ".", "time_before_present", "=", "new_root", ".", "time_before_present", "if", "hasattr", "(", "new_root", ",", "'numdate'", ")", ":", "self", ".", "tree", ".", "root", ".", "numdate", "=", "new_root", ".", "numdate", "# set root.gamma bc root doesn't have a branch_length_interpolator but gamma is needed", "if", "not", "hasattr", "(", "self", ".", "tree", ".", "root", ",", "'gamma'", ")", ":", "self", ".", "tree", ".", "root", ".", "gamma", "=", "1.0", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "n", ".", "mutation_length", "=", "n", ".", "branch_length", "if", "not", "hasattr", "(", "n", ",", "'clock_length'", ")", ":", "n", ".", "clock_length", "=", "n", ".", "branch_length", "self", ".", "prepare_tree", "(", ")", "self", ".", "get_clock_model", "(", "covariation", "=", "self", ".", "use_covariation", ")", "return", "ttconf", ".", "SUCCESS" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime.resolve_polytomies
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 likelihood. Sometimes, stretching two or more branches that carry several mutations is less costly than an additional branch with zero mutations (long branches are not stiff, short branches are). Parameters ---------- merge_compressed : bool If True, keep compressed branches as polytomies. If False, return a strictly binary tree. Returns -------- poly_found : int The number of polytomies found
treetime/treetime.py
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 likelihood. Sometimes, stretching two or more branches that carry several mutations is less costly than an additional branch with zero mutations (long branches are not stiff, short branches are). Parameters ---------- merge_compressed : bool If True, keep compressed branches as polytomies. If False, return a strictly binary tree. Returns -------- poly_found : int The number of polytomies found """ self.logger("TreeTime.resolve_polytomies: resolving multiple mergers...",1) poly_found=0 for n in self.tree.find_clades(): if len(n.clades) > 2: prior_n_clades = len(n.clades) self._poly(n, merge_compressed) poly_found+=prior_n_clades - len(n.clades) obsolete_nodes = [n for n in self.tree.find_clades() if len(n.clades)==1 and n.up is not None] for node in obsolete_nodes: self.logger('TreeTime.resolve_polytomies: remove obsolete node '+node.name,4) if node.up is not None: self.tree.collapse(node) if poly_found: self.logger('TreeTime.resolve_polytomies: introduces %d new nodes'%poly_found,3) else: self.logger('TreeTime.resolve_polytomies: No more polytomies to resolve',3) return poly_found
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 likelihood. Sometimes, stretching two or more branches that carry several mutations is less costly than an additional branch with zero mutations (long branches are not stiff, short branches are). Parameters ---------- merge_compressed : bool If True, keep compressed branches as polytomies. If False, return a strictly binary tree. Returns -------- poly_found : int The number of polytomies found """ self.logger("TreeTime.resolve_polytomies: resolving multiple mergers...",1) poly_found=0 for n in self.tree.find_clades(): if len(n.clades) > 2: prior_n_clades = len(n.clades) self._poly(n, merge_compressed) poly_found+=prior_n_clades - len(n.clades) obsolete_nodes = [n for n in self.tree.find_clades() if len(n.clades)==1 and n.up is not None] for node in obsolete_nodes: self.logger('TreeTime.resolve_polytomies: remove obsolete node '+node.name,4) if node.up is not None: self.tree.collapse(node) if poly_found: self.logger('TreeTime.resolve_polytomies: introduces %d new nodes'%poly_found,3) else: self.logger('TreeTime.resolve_polytomies: No more polytomies to resolve',3) return poly_found
[ "Resolve", "the", "polytomies", "on", "the", "tree", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L485-L527
[ "def", "resolve_polytomies", "(", "self", ",", "merge_compressed", "=", "False", ")", ":", "self", ".", "logger", "(", "\"TreeTime.resolve_polytomies: resolving multiple mergers...\"", ",", "1", ")", "poly_found", "=", "0", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "len", "(", "n", ".", "clades", ")", ">", "2", ":", "prior_n_clades", "=", "len", "(", "n", ".", "clades", ")", "self", ".", "_poly", "(", "n", ",", "merge_compressed", ")", "poly_found", "+=", "prior_n_clades", "-", "len", "(", "n", ".", "clades", ")", "obsolete_nodes", "=", "[", "n", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", "if", "len", "(", "n", ".", "clades", ")", "==", "1", "and", "n", ".", "up", "is", "not", "None", "]", "for", "node", "in", "obsolete_nodes", ":", "self", ".", "logger", "(", "'TreeTime.resolve_polytomies: remove obsolete node '", "+", "node", ".", "name", ",", "4", ")", "if", "node", ".", "up", "is", "not", "None", ":", "self", ".", "tree", ".", "collapse", "(", "node", ")", "if", "poly_found", ":", "self", ".", "logger", "(", "'TreeTime.resolve_polytomies: introduces %d new nodes'", "%", "poly_found", ",", "3", ")", "else", ":", "self", ".", "logger", "(", "'TreeTime.resolve_polytomies: No more polytomies to resolve'", ",", "3", ")", "return", "poly_found" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime._poly
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 gain of the LH due to the changing the branch lenghts towards the optimal values and the decrease due to the introduction of the new branch with zero optimal length.
treetime/treetime.py
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 gained by merging the two nodes. The increase in the LH is basically the tradeoff between the gain of the LH due to the changing the branch lenghts towards the optimal values and the decrease due to the introduction of the new branch with zero optimal length. """ from .branch_len_interpolator import BranchLenInterpolator zero_branch_slope = self.gtr.mu*self.seq_len def _c_gain(t, n1, n2, parent): """ cost gain if nodes n1, n2 are joined and their parent is placed at time t cost gain = (LH loss now) - (LH loss when placed at time t) """ cg2 = n2.branch_length_interpolator(parent.time_before_present - n2.time_before_present) - n2.branch_length_interpolator(t - n2.time_before_present) cg1 = n1.branch_length_interpolator(parent.time_before_present - n1.time_before_present) - n1.branch_length_interpolator(t - n1.time_before_present) cg_new = - zero_branch_slope * (parent.time_before_present - t) # loss in LH due to the new branch return -(cg2+cg1+cg_new) def cost_gain(n1, n2, parent): """ cost gained if the two nodes would have been connected. """ try: cg = sciopt.minimize_scalar(_c_gain, bounds=[max(n1.time_before_present,n2.time_before_present), parent.time_before_present], method='Bounded',args=(n1,n2, parent)) return cg['x'], - cg['fun'] except: self.logger("TreeTime._poly.cost_gain: optimization of gain failed", 3, warn=True) return parent.time_before_present, 0.0 def merge_nodes(source_arr, isall=False): mergers = np.array([[cost_gain(n1,n2, clade) if i1<i2 else (0.0,-1.0) for i1,n1 in enumerate(source_arr)] for i2, n2 in enumerate(source_arr)]) LH = 0 while len(source_arr) > 1 + int(isall): # max possible gains of the cost when connecting the nodes: # this is only a rough approximation because it assumes the new node positions # to be optimal new_positions = mergers[:,:,0] cost_gains = mergers[:,:,1] # set zero to large negative value and find optimal pair np.fill_diagonal(cost_gains, -1e11) idxs = np.unravel_index(cost_gains.argmax(),cost_gains.shape) if (idxs[0] == idxs[1]) or cost_gains.max()<0: self.logger("TreeTime._poly.merge_nodes: node is not fully resolved "+clade.name,4) return LH n1, n2 = source_arr[idxs[0]], source_arr[idxs[1]] LH += cost_gains[idxs] new_node = Phylo.BaseTree.Clade() # fix positions and branch lengths new_node.time_before_present = new_positions[idxs] new_node.branch_length = clade.time_before_present - new_node.time_before_present new_node.clades = [n1,n2] n1.branch_length = new_node.time_before_present - n1.time_before_present n2.branch_length = new_node.time_before_present - n2.time_before_present # set parameters for the new node new_node.up = clade n1.up = new_node n2.up = new_node if hasattr(clade, "cseq"): new_node.cseq = clade.cseq self._store_compressed_sequence_to_node(new_node) new_node.mutations = [] new_node.mutation_length = 0.0 new_node.branch_length_interpolator = BranchLenInterpolator(new_node, self.gtr, one_mutation=self.one_mutation, branch_length_mode = self.branch_length_mode) clade.clades.remove(n1) clade.clades.remove(n2) clade.clades.append(new_node) self.logger('TreeTime._poly.merge_nodes: creating new node as child of '+clade.name,3) self.logger("TreeTime._poly.merge_nodes: Delta-LH = " + str(cost_gains[idxs].round(3)), 3) # and modify source_arr array for the next loop if len(source_arr)>2: # if more than 3 nodes in polytomy, replace row/column for ii in np.sort(idxs)[::-1]: tmp_ind = np.arange(mergers.shape[0])!=ii mergers = mergers[tmp_ind].swapaxes(0,1) mergers = mergers[tmp_ind].swapaxes(0,1) source_arr.remove(n1) source_arr.remove(n2) new_gains = np.array([[cost_gain(n1,new_node, clade) for n1 in source_arr]]) mergers = np.vstack((mergers, new_gains)).swapaxes(0,1) source_arr.append(new_node) new_gains = np.array([[cost_gain(n1,new_node, clade) for n1 in source_arr]]) mergers = np.vstack((mergers, new_gains)).swapaxes(0,1) else: # otherwise just recalculate matrix source_arr.remove(n1) source_arr.remove(n2) source_arr.append(new_node) mergers = np.array([[cost_gain(n1,n2, clade) for n1 in source_arr] for n2 in source_arr]) return LH stretched = [c for c in clade.clades if c.mutation_length < c.clock_length] compressed = [c for c in clade.clades if c not in stretched] if len(stretched)==1 and merge_compressed is False: return 0.0 LH = merge_nodes(stretched, isall=len(stretched)==len(clade.clades)) if merge_compressed and len(compressed)>1: LH += merge_nodes(compressed, isall=len(compressed)==len(clade.clades)) return LH
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 gained by merging the two nodes. The increase in the LH is basically the tradeoff between the gain of the LH due to the changing the branch lenghts towards the optimal values and the decrease due to the introduction of the new branch with zero optimal length. """ from .branch_len_interpolator import BranchLenInterpolator zero_branch_slope = self.gtr.mu*self.seq_len def _c_gain(t, n1, n2, parent): """ cost gain if nodes n1, n2 are joined and their parent is placed at time t cost gain = (LH loss now) - (LH loss when placed at time t) """ cg2 = n2.branch_length_interpolator(parent.time_before_present - n2.time_before_present) - n2.branch_length_interpolator(t - n2.time_before_present) cg1 = n1.branch_length_interpolator(parent.time_before_present - n1.time_before_present) - n1.branch_length_interpolator(t - n1.time_before_present) cg_new = - zero_branch_slope * (parent.time_before_present - t) # loss in LH due to the new branch return -(cg2+cg1+cg_new) def cost_gain(n1, n2, parent): """ cost gained if the two nodes would have been connected. """ try: cg = sciopt.minimize_scalar(_c_gain, bounds=[max(n1.time_before_present,n2.time_before_present), parent.time_before_present], method='Bounded',args=(n1,n2, parent)) return cg['x'], - cg['fun'] except: self.logger("TreeTime._poly.cost_gain: optimization of gain failed", 3, warn=True) return parent.time_before_present, 0.0 def merge_nodes(source_arr, isall=False): mergers = np.array([[cost_gain(n1,n2, clade) if i1<i2 else (0.0,-1.0) for i1,n1 in enumerate(source_arr)] for i2, n2 in enumerate(source_arr)]) LH = 0 while len(source_arr) > 1 + int(isall): # max possible gains of the cost when connecting the nodes: # this is only a rough approximation because it assumes the new node positions # to be optimal new_positions = mergers[:,:,0] cost_gains = mergers[:,:,1] # set zero to large negative value and find optimal pair np.fill_diagonal(cost_gains, -1e11) idxs = np.unravel_index(cost_gains.argmax(),cost_gains.shape) if (idxs[0] == idxs[1]) or cost_gains.max()<0: self.logger("TreeTime._poly.merge_nodes: node is not fully resolved "+clade.name,4) return LH n1, n2 = source_arr[idxs[0]], source_arr[idxs[1]] LH += cost_gains[idxs] new_node = Phylo.BaseTree.Clade() # fix positions and branch lengths new_node.time_before_present = new_positions[idxs] new_node.branch_length = clade.time_before_present - new_node.time_before_present new_node.clades = [n1,n2] n1.branch_length = new_node.time_before_present - n1.time_before_present n2.branch_length = new_node.time_before_present - n2.time_before_present # set parameters for the new node new_node.up = clade n1.up = new_node n2.up = new_node if hasattr(clade, "cseq"): new_node.cseq = clade.cseq self._store_compressed_sequence_to_node(new_node) new_node.mutations = [] new_node.mutation_length = 0.0 new_node.branch_length_interpolator = BranchLenInterpolator(new_node, self.gtr, one_mutation=self.one_mutation, branch_length_mode = self.branch_length_mode) clade.clades.remove(n1) clade.clades.remove(n2) clade.clades.append(new_node) self.logger('TreeTime._poly.merge_nodes: creating new node as child of '+clade.name,3) self.logger("TreeTime._poly.merge_nodes: Delta-LH = " + str(cost_gains[idxs].round(3)), 3) # and modify source_arr array for the next loop if len(source_arr)>2: # if more than 3 nodes in polytomy, replace row/column for ii in np.sort(idxs)[::-1]: tmp_ind = np.arange(mergers.shape[0])!=ii mergers = mergers[tmp_ind].swapaxes(0,1) mergers = mergers[tmp_ind].swapaxes(0,1) source_arr.remove(n1) source_arr.remove(n2) new_gains = np.array([[cost_gain(n1,new_node, clade) for n1 in source_arr]]) mergers = np.vstack((mergers, new_gains)).swapaxes(0,1) source_arr.append(new_node) new_gains = np.array([[cost_gain(n1,new_node, clade) for n1 in source_arr]]) mergers = np.vstack((mergers, new_gains)).swapaxes(0,1) else: # otherwise just recalculate matrix source_arr.remove(n1) source_arr.remove(n2) source_arr.append(new_node) mergers = np.array([[cost_gain(n1,n2, clade) for n1 in source_arr] for n2 in source_arr]) return LH stretched = [c for c in clade.clades if c.mutation_length < c.clock_length] compressed = [c for c in clade.clades if c not in stretched] if len(stretched)==1 and merge_compressed is False: return 0.0 LH = merge_nodes(stretched, isall=len(stretched)==len(clade.clades)) if merge_compressed and len(compressed)>1: LH += merge_nodes(compressed, isall=len(compressed)==len(clade.clades)) return LH
[ "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", "gain", "of", "the", "LH", "due", "to", "the", "changing", "the", "branch", "lenghts", "towards", "the", "optimal", "values", "and", "the", "decrease", "due", "to", "the", "introduction", "of", "the", "new", "branch", "with", "zero", "optimal", "length", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L530-L652
[ "def", "_poly", "(", "self", ",", "clade", ",", "merge_compressed", ")", ":", "from", ".", "branch_len_interpolator", "import", "BranchLenInterpolator", "zero_branch_slope", "=", "self", ".", "gtr", ".", "mu", "*", "self", ".", "seq_len", "def", "_c_gain", "(", "t", ",", "n1", ",", "n2", ",", "parent", ")", ":", "\"\"\"\n cost gain if nodes n1, n2 are joined and their parent is placed at time t\n cost gain = (LH loss now) - (LH loss when placed at time t)\n \"\"\"", "cg2", "=", "n2", ".", "branch_length_interpolator", "(", "parent", ".", "time_before_present", "-", "n2", ".", "time_before_present", ")", "-", "n2", ".", "branch_length_interpolator", "(", "t", "-", "n2", ".", "time_before_present", ")", "cg1", "=", "n1", ".", "branch_length_interpolator", "(", "parent", ".", "time_before_present", "-", "n1", ".", "time_before_present", ")", "-", "n1", ".", "branch_length_interpolator", "(", "t", "-", "n1", ".", "time_before_present", ")", "cg_new", "=", "-", "zero_branch_slope", "*", "(", "parent", ".", "time_before_present", "-", "t", ")", "# loss in LH due to the new branch", "return", "-", "(", "cg2", "+", "cg1", "+", "cg_new", ")", "def", "cost_gain", "(", "n1", ",", "n2", ",", "parent", ")", ":", "\"\"\"\n cost gained if the two nodes would have been connected.\n \"\"\"", "try", ":", "cg", "=", "sciopt", ".", "minimize_scalar", "(", "_c_gain", ",", "bounds", "=", "[", "max", "(", "n1", ".", "time_before_present", ",", "n2", ".", "time_before_present", ")", ",", "parent", ".", "time_before_present", "]", ",", "method", "=", "'Bounded'", ",", "args", "=", "(", "n1", ",", "n2", ",", "parent", ")", ")", "return", "cg", "[", "'x'", "]", ",", "-", "cg", "[", "'fun'", "]", "except", ":", "self", ".", "logger", "(", "\"TreeTime._poly.cost_gain: optimization of gain failed\"", ",", "3", ",", "warn", "=", "True", ")", "return", "parent", ".", "time_before_present", ",", "0.0", "def", "merge_nodes", "(", "source_arr", ",", "isall", "=", "False", ")", ":", "mergers", "=", "np", ".", "array", "(", "[", "[", "cost_gain", "(", "n1", ",", "n2", ",", "clade", ")", "if", "i1", "<", "i2", "else", "(", "0.0", ",", "-", "1.0", ")", "for", "i1", ",", "n1", "in", "enumerate", "(", "source_arr", ")", "]", "for", "i2", ",", "n2", "in", "enumerate", "(", "source_arr", ")", "]", ")", "LH", "=", "0", "while", "len", "(", "source_arr", ")", ">", "1", "+", "int", "(", "isall", ")", ":", "# max possible gains of the cost when connecting the nodes:", "# this is only a rough approximation because it assumes the new node positions", "# to be optimal", "new_positions", "=", "mergers", "[", ":", ",", ":", ",", "0", "]", "cost_gains", "=", "mergers", "[", ":", ",", ":", ",", "1", "]", "# set zero to large negative value and find optimal pair", "np", ".", "fill_diagonal", "(", "cost_gains", ",", "-", "1e11", ")", "idxs", "=", "np", ".", "unravel_index", "(", "cost_gains", ".", "argmax", "(", ")", ",", "cost_gains", ".", "shape", ")", "if", "(", "idxs", "[", "0", "]", "==", "idxs", "[", "1", "]", ")", "or", "cost_gains", ".", "max", "(", ")", "<", "0", ":", "self", ".", "logger", "(", "\"TreeTime._poly.merge_nodes: node is not fully resolved \"", "+", "clade", ".", "name", ",", "4", ")", "return", "LH", "n1", ",", "n2", "=", "source_arr", "[", "idxs", "[", "0", "]", "]", ",", "source_arr", "[", "idxs", "[", "1", "]", "]", "LH", "+=", "cost_gains", "[", "idxs", "]", "new_node", "=", "Phylo", ".", "BaseTree", ".", "Clade", "(", ")", "# fix positions and branch lengths", "new_node", ".", "time_before_present", "=", "new_positions", "[", "idxs", "]", "new_node", ".", "branch_length", "=", "clade", ".", "time_before_present", "-", "new_node", ".", "time_before_present", "new_node", ".", "clades", "=", "[", "n1", ",", "n2", "]", "n1", ".", "branch_length", "=", "new_node", ".", "time_before_present", "-", "n1", ".", "time_before_present", "n2", ".", "branch_length", "=", "new_node", ".", "time_before_present", "-", "n2", ".", "time_before_present", "# set parameters for the new node", "new_node", ".", "up", "=", "clade", "n1", ".", "up", "=", "new_node", "n2", ".", "up", "=", "new_node", "if", "hasattr", "(", "clade", ",", "\"cseq\"", ")", ":", "new_node", ".", "cseq", "=", "clade", ".", "cseq", "self", ".", "_store_compressed_sequence_to_node", "(", "new_node", ")", "new_node", ".", "mutations", "=", "[", "]", "new_node", ".", "mutation_length", "=", "0.0", "new_node", ".", "branch_length_interpolator", "=", "BranchLenInterpolator", "(", "new_node", ",", "self", ".", "gtr", ",", "one_mutation", "=", "self", ".", "one_mutation", ",", "branch_length_mode", "=", "self", ".", "branch_length_mode", ")", "clade", ".", "clades", ".", "remove", "(", "n1", ")", "clade", ".", "clades", ".", "remove", "(", "n2", ")", "clade", ".", "clades", ".", "append", "(", "new_node", ")", "self", ".", "logger", "(", "'TreeTime._poly.merge_nodes: creating new node as child of '", "+", "clade", ".", "name", ",", "3", ")", "self", ".", "logger", "(", "\"TreeTime._poly.merge_nodes: Delta-LH = \"", "+", "str", "(", "cost_gains", "[", "idxs", "]", ".", "round", "(", "3", ")", ")", ",", "3", ")", "# and modify source_arr array for the next loop", "if", "len", "(", "source_arr", ")", ">", "2", ":", "# if more than 3 nodes in polytomy, replace row/column", "for", "ii", "in", "np", ".", "sort", "(", "idxs", ")", "[", ":", ":", "-", "1", "]", ":", "tmp_ind", "=", "np", ".", "arange", "(", "mergers", ".", "shape", "[", "0", "]", ")", "!=", "ii", "mergers", "=", "mergers", "[", "tmp_ind", "]", ".", "swapaxes", "(", "0", ",", "1", ")", "mergers", "=", "mergers", "[", "tmp_ind", "]", ".", "swapaxes", "(", "0", ",", "1", ")", "source_arr", ".", "remove", "(", "n1", ")", "source_arr", ".", "remove", "(", "n2", ")", "new_gains", "=", "np", ".", "array", "(", "[", "[", "cost_gain", "(", "n1", ",", "new_node", ",", "clade", ")", "for", "n1", "in", "source_arr", "]", "]", ")", "mergers", "=", "np", ".", "vstack", "(", "(", "mergers", ",", "new_gains", ")", ")", ".", "swapaxes", "(", "0", ",", "1", ")", "source_arr", ".", "append", "(", "new_node", ")", "new_gains", "=", "np", ".", "array", "(", "[", "[", "cost_gain", "(", "n1", ",", "new_node", ",", "clade", ")", "for", "n1", "in", "source_arr", "]", "]", ")", "mergers", "=", "np", ".", "vstack", "(", "(", "mergers", ",", "new_gains", ")", ")", ".", "swapaxes", "(", "0", ",", "1", ")", "else", ":", "# otherwise just recalculate matrix", "source_arr", ".", "remove", "(", "n1", ")", "source_arr", ".", "remove", "(", "n2", ")", "source_arr", ".", "append", "(", "new_node", ")", "mergers", "=", "np", ".", "array", "(", "[", "[", "cost_gain", "(", "n1", ",", "n2", ",", "clade", ")", "for", "n1", "in", "source_arr", "]", "for", "n2", "in", "source_arr", "]", ")", "return", "LH", "stretched", "=", "[", "c", "for", "c", "in", "clade", ".", "clades", "if", "c", ".", "mutation_length", "<", "c", ".", "clock_length", "]", "compressed", "=", "[", "c", "for", "c", "in", "clade", ".", "clades", "if", "c", "not", "in", "stretched", "]", "if", "len", "(", "stretched", ")", "==", "1", "and", "merge_compressed", "is", "False", ":", "return", "0.0", "LH", "=", "merge_nodes", "(", "stretched", ",", "isall", "=", "len", "(", "stretched", ")", "==", "len", "(", "clade", ".", "clades", ")", ")", "if", "merge_compressed", "and", "len", "(", "compressed", ")", ">", "1", ":", "LH", "+=", "merge_nodes", "(", "compressed", ",", "isall", "=", "len", "(", "compressed", ")", "==", "len", "(", "clade", ".", "clades", ")", ")", "return", "LH" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime.print_lh
Print the total likelihood of the tree given the constrained leaves Parameters ---------- joint : bool If true, print joint LH, else print marginal LH
treetime/treetime.py
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_LH if joint: s_lh = self.tree.sequence_joint_LH t_lh = self.tree.positional_joint_LH c_lh = self.tree.coalescent_joint_LH else: s_lh = self.tree.sequence_marginal_LH t_lh = self.tree.positional_marginal_LH c_lh = 0 print ("### Tree Log-Likelihood ###\n" " Sequence log-LH without constraints: \t%1.3f\n" " Sequence log-LH with constraints: \t%1.3f\n" " TreeTime sequence log-LH: \t%1.3f\n" " Coalescent log-LH: \t%1.3f\n" "#########################"%(u_lh, s_lh,t_lh, c_lh)) except: print("ERROR. Did you run the corresponding inference (joint/marginal)?")
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_LH if joint: s_lh = self.tree.sequence_joint_LH t_lh = self.tree.positional_joint_LH c_lh = self.tree.coalescent_joint_LH else: s_lh = self.tree.sequence_marginal_LH t_lh = self.tree.positional_marginal_LH c_lh = 0 print ("### Tree Log-Likelihood ###\n" " Sequence log-LH without constraints: \t%1.3f\n" " Sequence log-LH with constraints: \t%1.3f\n" " TreeTime sequence log-LH: \t%1.3f\n" " Coalescent log-LH: \t%1.3f\n" "#########################"%(u_lh, s_lh,t_lh, c_lh)) except: print("ERROR. Did you run the corresponding inference (joint/marginal)?")
[ "Print", "the", "total", "likelihood", "of", "the", "tree", "given", "the", "constrained", "leaves" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L655-L684
[ "def", "print_lh", "(", "self", ",", "joint", "=", "True", ")", ":", "try", ":", "u_lh", "=", "self", ".", "tree", ".", "unconstrained_sequence_LH", "if", "joint", ":", "s_lh", "=", "self", ".", "tree", ".", "sequence_joint_LH", "t_lh", "=", "self", ".", "tree", ".", "positional_joint_LH", "c_lh", "=", "self", ".", "tree", ".", "coalescent_joint_LH", "else", ":", "s_lh", "=", "self", ".", "tree", ".", "sequence_marginal_LH", "t_lh", "=", "self", ".", "tree", ".", "positional_marginal_LH", "c_lh", "=", "0", "print", "(", "\"### Tree Log-Likelihood ###\\n\"", "\" Sequence log-LH without constraints: \\t%1.3f\\n\"", "\" Sequence log-LH with constraints: \\t%1.3f\\n\"", "\" TreeTime sequence log-LH: \\t%1.3f\\n\"", "\" Coalescent log-LH: \\t%1.3f\\n\"", "\"#########################\"", "%", "(", "u_lh", ",", "s_lh", ",", "t_lh", ",", "c_lh", ")", ")", "except", ":", "print", "(", "\"ERROR. Did you run the corresponding inference (joint/marginal)?\"", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime.add_coalescent_model
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
treetime/treetime.py
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 """ from .merger_models import Coalescent self.logger('TreeTime.run: adding coalescent prior with Tc='+str(Tc),1) self.merger_model = Coalescent(self.tree, date2dist=self.date2dist, logger=self.logger) if Tc=='skyline': # restrict skyline model optimization to last iteration self.merger_model.optimize_skyline(**kwargs) self.logger("optimized a skyline ", 2) else: if Tc in ['opt', 'const']: self.merger_model.optimize_Tc() self.logger("optimized Tc to %f"%self.merger_model.Tc.y[0], 2) else: try: self.merger_model.set_Tc(Tc) except: self.logger("setting of coalescent time scale failed", 1, warn=True) self.merger_model.attach_to_tree()
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 """ from .merger_models import Coalescent self.logger('TreeTime.run: adding coalescent prior with Tc='+str(Tc),1) self.merger_model = Coalescent(self.tree, date2dist=self.date2dist, logger=self.logger) if Tc=='skyline': # restrict skyline model optimization to last iteration self.merger_model.optimize_skyline(**kwargs) self.logger("optimized a skyline ", 2) else: if Tc in ['opt', 'const']: self.merger_model.optimize_Tc() self.logger("optimized Tc to %f"%self.merger_model.Tc.y[0], 2) else: try: self.merger_model.set_Tc(Tc) except: self.logger("setting of coalescent time scale failed", 1, warn=True) self.merger_model.attach_to_tree()
[ "Add", "a", "coalescent", "model", "to", "the", "tree", "and", "optionally", "optimze" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L687-L714
[ "def", "add_coalescent_model", "(", "self", ",", "Tc", ",", "*", "*", "kwargs", ")", ":", "from", ".", "merger_models", "import", "Coalescent", "self", ".", "logger", "(", "'TreeTime.run: adding coalescent prior with Tc='", "+", "str", "(", "Tc", ")", ",", "1", ")", "self", ".", "merger_model", "=", "Coalescent", "(", "self", ".", "tree", ",", "date2dist", "=", "self", ".", "date2dist", ",", "logger", "=", "self", ".", "logger", ")", "if", "Tc", "==", "'skyline'", ":", "# restrict skyline model optimization to last iteration", "self", ".", "merger_model", ".", "optimize_skyline", "(", "*", "*", "kwargs", ")", "self", ".", "logger", "(", "\"optimized a skyline \"", ",", "2", ")", "else", ":", "if", "Tc", "in", "[", "'opt'", ",", "'const'", "]", ":", "self", ".", "merger_model", ".", "optimize_Tc", "(", ")", "self", ".", "logger", "(", "\"optimized Tc to %f\"", "%", "self", ".", "merger_model", ".", "Tc", ".", "y", "[", "0", "]", ",", "2", ")", "else", ":", "try", ":", "self", ".", "merger_model", ".", "set_Tc", "(", "Tc", ")", "except", ":", "self", ".", "logger", "(", "\"setting of coalescent time scale failed\"", ",", "1", ",", "warn", "=", "True", ")", "self", ".", "merger_model", ".", "attach_to_tree", "(", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime.relaxed_clock
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. Parameters ---------- slack : float Maximum change in substitution rate between parent and child nodes coupling : float Maximum difference in substitution rates in sibling nodes
treetime/treetime.py
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 penalized. Parameters ---------- slack : float Maximum change in substitution rate between parent and child nodes coupling : float Maximum difference in substitution rates in sibling nodes """ if slack is None: slack=ttconf.MU_ALPHA if coupling is None: coupling=ttconf.MU_BETA self.logger("TreeTime.relaxed_clock: slack=%f, coupling=%f"%(slack, coupling),2) c=1.0/self.one_mutation for node in self.tree.find_clades(order='postorder'): opt_len = node.mutation_length act_len = node.clock_length if hasattr(node, 'clock_length') else node.branch_length # opt_len \approx 1.0*len(node.mutations)/node.profile.shape[0] but calculated via gtr model # stiffness is the expectation of the inverse variance of branch length (one_mutation/opt_len) # contact term: stiffness*(g*bl - bl_opt)^2 + slack(g-1)^2 = # (slack+bl^2) g^2 - 2 (bl*bl_opt+1) g + C= k2 g^2 + k1 g + C node._k2 = slack + c*act_len**2/(opt_len+self.one_mutation) node._k1 = -2*(c*act_len*opt_len/(opt_len+self.one_mutation) + slack) # coupling term: \sum_c coupling*(g-g_c)^2 + Cost_c(g_c|g) # given g, g_c needs to be optimal-> 2*coupling*(g-g_c) = 2*child.k2 g_c + child.k1 # hence g_c = (coupling*g - 0.5*child.k1)/(coupling+child.k2) # substituting yields for child in node.clades: denom = coupling+child._k2 node._k2 += coupling*(1.0-coupling/denom)**2 + child._k2*coupling**2/denom**2 node._k1 += (coupling*(1.0-coupling/denom)*child._k1/denom \ - coupling*child._k1*child._k2/denom**2 \ + coupling*child._k1/denom) for node in self.tree.find_clades(order='preorder'): if node.up is None: node.gamma = max(0.1, -0.5*node._k1/node._k2) else: if node.up.up is None: g_up = node.up.gamma else: g_up = node.up.branch_length_interpolator.gamma node.branch_length_interpolator.gamma = max(0.1,(coupling*g_up - 0.5*node._k1)/(coupling+node._k2))
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 penalized. Parameters ---------- slack : float Maximum change in substitution rate between parent and child nodes coupling : float Maximum difference in substitution rates in sibling nodes """ if slack is None: slack=ttconf.MU_ALPHA if coupling is None: coupling=ttconf.MU_BETA self.logger("TreeTime.relaxed_clock: slack=%f, coupling=%f"%(slack, coupling),2) c=1.0/self.one_mutation for node in self.tree.find_clades(order='postorder'): opt_len = node.mutation_length act_len = node.clock_length if hasattr(node, 'clock_length') else node.branch_length # opt_len \approx 1.0*len(node.mutations)/node.profile.shape[0] but calculated via gtr model # stiffness is the expectation of the inverse variance of branch length (one_mutation/opt_len) # contact term: stiffness*(g*bl - bl_opt)^2 + slack(g-1)^2 = # (slack+bl^2) g^2 - 2 (bl*bl_opt+1) g + C= k2 g^2 + k1 g + C node._k2 = slack + c*act_len**2/(opt_len+self.one_mutation) node._k1 = -2*(c*act_len*opt_len/(opt_len+self.one_mutation) + slack) # coupling term: \sum_c coupling*(g-g_c)^2 + Cost_c(g_c|g) # given g, g_c needs to be optimal-> 2*coupling*(g-g_c) = 2*child.k2 g_c + child.k1 # hence g_c = (coupling*g - 0.5*child.k1)/(coupling+child.k2) # substituting yields for child in node.clades: denom = coupling+child._k2 node._k2 += coupling*(1.0-coupling/denom)**2 + child._k2*coupling**2/denom**2 node._k1 += (coupling*(1.0-coupling/denom)*child._k1/denom \ - coupling*child._k1*child._k2/denom**2 \ + coupling*child._k1/denom) for node in self.tree.find_clades(order='preorder'): if node.up is None: node.gamma = max(0.1, -0.5*node._k1/node._k2) else: if node.up.up is None: g_up = node.up.gamma else: g_up = node.up.branch_length_interpolator.gamma node.branch_length_interpolator.gamma = max(0.1,(coupling*g_up - 0.5*node._k1)/(coupling+node._k2))
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L717-L767
[ "def", "relaxed_clock", "(", "self", ",", "slack", "=", "None", ",", "coupling", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "slack", "is", "None", ":", "slack", "=", "ttconf", ".", "MU_ALPHA", "if", "coupling", "is", "None", ":", "coupling", "=", "ttconf", ".", "MU_BETA", "self", ".", "logger", "(", "\"TreeTime.relaxed_clock: slack=%f, coupling=%f\"", "%", "(", "slack", ",", "coupling", ")", ",", "2", ")", "c", "=", "1.0", "/", "self", ".", "one_mutation", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'postorder'", ")", ":", "opt_len", "=", "node", ".", "mutation_length", "act_len", "=", "node", ".", "clock_length", "if", "hasattr", "(", "node", ",", "'clock_length'", ")", "else", "node", ".", "branch_length", "# opt_len \\approx 1.0*len(node.mutations)/node.profile.shape[0] but calculated via gtr model", "# stiffness is the expectation of the inverse variance of branch length (one_mutation/opt_len)", "# contact term: stiffness*(g*bl - bl_opt)^2 + slack(g-1)^2 =", "# (slack+bl^2) g^2 - 2 (bl*bl_opt+1) g + C= k2 g^2 + k1 g + C", "node", ".", "_k2", "=", "slack", "+", "c", "*", "act_len", "**", "2", "/", "(", "opt_len", "+", "self", ".", "one_mutation", ")", "node", ".", "_k1", "=", "-", "2", "*", "(", "c", "*", "act_len", "*", "opt_len", "/", "(", "opt_len", "+", "self", ".", "one_mutation", ")", "+", "slack", ")", "# coupling term: \\sum_c coupling*(g-g_c)^2 + Cost_c(g_c|g)", "# given g, g_c needs to be optimal-> 2*coupling*(g-g_c) = 2*child.k2 g_c + child.k1", "# hence g_c = (coupling*g - 0.5*child.k1)/(coupling+child.k2)", "# substituting yields", "for", "child", "in", "node", ".", "clades", ":", "denom", "=", "coupling", "+", "child", ".", "_k2", "node", ".", "_k2", "+=", "coupling", "*", "(", "1.0", "-", "coupling", "/", "denom", ")", "**", "2", "+", "child", ".", "_k2", "*", "coupling", "**", "2", "/", "denom", "**", "2", "node", ".", "_k1", "+=", "(", "coupling", "*", "(", "1.0", "-", "coupling", "/", "denom", ")", "*", "child", ".", "_k1", "/", "denom", "-", "coupling", "*", "child", ".", "_k1", "*", "child", ".", "_k2", "/", "denom", "**", "2", "+", "coupling", "*", "child", ".", "_k1", "/", "denom", ")", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'preorder'", ")", ":", "if", "node", ".", "up", "is", "None", ":", "node", ".", "gamma", "=", "max", "(", "0.1", ",", "-", "0.5", "*", "node", ".", "_k1", "/", "node", ".", "_k2", ")", "else", ":", "if", "node", ".", "up", ".", "up", "is", "None", ":", "g_up", "=", "node", ".", "up", ".", "gamma", "else", ":", "g_up", "=", "node", ".", "up", ".", "branch_length_interpolator", ".", "gamma", "node", ".", "branch_length_interpolator", ".", "gamma", "=", "max", "(", "0.1", ",", "(", "coupling", "*", "g_up", "-", "0.5", "*", "node", ".", "_k1", ")", "/", "(", "coupling", "+", "node", ".", "_k2", ")", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
TreeTime._find_best_root
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 : bool If True, infer new GTR model after re-root covariation : bool account for covariation structure when rerooting the tree force_positive : bool only accept positive evolutionary rate estimates when rerooting the tree
treetime/treetime.py
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 : bool If True, infer new GTR model after re-root covariation : bool account for covariation structure when rerooting the tree force_positive : bool only accept positive evolutionary rate estimates when rerooting the tree ''' for n in self.tree.find_clades(): n.branch_length=n.mutation_length self.logger("TreeTime._find_best_root: searching for the best root position...",2) Treg = self.setup_TreeRegression(covariation=covariation) return Treg.optimal_reroot(force_positive=force_positive, slope=slope)['node']
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 : bool If True, infer new GTR model after re-root covariation : bool account for covariation structure when rerooting the tree force_positive : bool only accept positive evolutionary rate estimates when rerooting the tree ''' for n in self.tree.find_clades(): n.branch_length=n.mutation_length self.logger("TreeTime._find_best_root: searching for the best root position...",2) Treg = self.setup_TreeRegression(covariation=covariation) return Treg.optimal_reroot(force_positive=force_positive, slope=slope)['node']
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/treetime.py#L773-L795
[ "def", "_find_best_root", "(", "self", ",", "covariation", "=", "True", ",", "force_positive", "=", "True", ",", "slope", "=", "0", ",", "*", "*", "kwarks", ")", ":", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "n", ".", "branch_length", "=", "n", ".", "mutation_length", "self", ".", "logger", "(", "\"TreeTime._find_best_root: searching for the best root position...\"", ",", "2", ")", "Treg", "=", "self", ".", "setup_TreeRegression", "(", "covariation", "=", "covariation", ")", "return", "Treg", ".", "optimal_reroot", "(", "force_positive", "=", "force_positive", ",", "slope", "=", "slope", ")", "[", "'node'", "]" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
assure_tree
Function that attempts to load a tree and build it from the alignment if no tree is provided.
treetime/wrappers.py
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_inference(params.aln, params.tree, tmp_dir = tmp_dir) if os.path.isdir(tmp_dir): shutil.rmtree(tmp_dir) try: tt = TreeAnc(params.tree) except: print("Tree loading/building failed.") return 1 return 0
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_inference(params.aln, params.tree, tmp_dir = tmp_dir) if os.path.isdir(tmp_dir): shutil.rmtree(tmp_dir) try: tt = TreeAnc(params.tree) except: print("Tree loading/building failed.") return 1 return 0
[ "Function", "that", "attempts", "to", "load", "a", "tree", "and", "build", "it", "from", "the", "alignment", "if", "no", "tree", "is", "provided", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/wrappers.py#L16-L34
[ "def", "assure_tree", "(", "params", ",", "tmp_dir", "=", "'treetime_tmp'", ")", ":", "if", "params", ".", "tree", "is", "None", ":", "params", ".", "tree", "=", "os", ".", "path", ".", "basename", "(", "params", ".", "aln", ")", "+", "'.nwk'", "print", "(", "\"No tree given: inferring tree\"", ")", "utils", ".", "tree_inference", "(", "params", ".", "aln", ",", "params", ".", "tree", ",", "tmp_dir", "=", "tmp_dir", ")", "if", "os", ".", "path", ".", "isdir", "(", "tmp_dir", ")", ":", "shutil", ".", "rmtree", "(", "tmp_dir", ")", "try", ":", "tt", "=", "TreeAnc", "(", "params", ".", "tree", ")", "except", ":", "print", "(", "\"Tree loading/building failed.\"", ")", "return", "1", "return", "0" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
create_gtr
parse the arguments referring to the GTR model and return a GTR structure
treetime/wrappers.py
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 = {} if gtr_params is not None: for param in gtr_params: keyval = param.split('=') if len(keyval)!=2: continue if keyval[0] in ['pis', 'pi', 'Pi', 'Pis']: keyval[0] = 'pi' keyval[1] = list(map(float, keyval[1].split(','))) elif keyval[0] not in ['alphabet']: keyval[1] = float(keyval[1]) kwargs[keyval[0]] = keyval[1] else: print ("GTR params are not specified. Creating GTR model with default parameters") gtr = GTR.standard(model, **kwargs) infer_gtr = False except: print ("Could not create GTR model from input arguments. Using default (Jukes-Cantor 1969)") gtr = GTR.standard('jc', alphabet='aa' if params.aa else 'nuc') infer_gtr = False return gtr
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 = {} if gtr_params is not None: for param in gtr_params: keyval = param.split('=') if len(keyval)!=2: continue if keyval[0] in ['pis', 'pi', 'Pi', 'Pis']: keyval[0] = 'pi' keyval[1] = list(map(float, keyval[1].split(','))) elif keyval[0] not in ['alphabet']: keyval[1] = float(keyval[1]) kwargs[keyval[0]] = keyval[1] else: print ("GTR params are not specified. Creating GTR model with default parameters") gtr = GTR.standard(model, **kwargs) infer_gtr = False except: print ("Could not create GTR model from input arguments. Using default (Jukes-Cantor 1969)") gtr = GTR.standard('jc', alphabet='aa' if params.aa else 'nuc') infer_gtr = False return gtr
[ "parse", "the", "arguments", "referring", "to", "the", "GTR", "model", "and", "return", "a", "GTR", "structure" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/wrappers.py#L36-L66
[ "def", "create_gtr", "(", "params", ")", ":", "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", "=", "{", "}", "if", "gtr_params", "is", "not", "None", ":", "for", "param", "in", "gtr_params", ":", "keyval", "=", "param", ".", "split", "(", "'='", ")", "if", "len", "(", "keyval", ")", "!=", "2", ":", "continue", "if", "keyval", "[", "0", "]", "in", "[", "'pis'", ",", "'pi'", ",", "'Pi'", ",", "'Pis'", "]", ":", "keyval", "[", "0", "]", "=", "'pi'", "keyval", "[", "1", "]", "=", "list", "(", "map", "(", "float", ",", "keyval", "[", "1", "]", ".", "split", "(", "','", ")", ")", ")", "elif", "keyval", "[", "0", "]", "not", "in", "[", "'alphabet'", "]", ":", "keyval", "[", "1", "]", "=", "float", "(", "keyval", "[", "1", "]", ")", "kwargs", "[", "keyval", "[", "0", "]", "]", "=", "keyval", "[", "1", "]", "else", ":", "print", "(", "\"GTR params are not specified. Creating GTR model with default parameters\"", ")", "gtr", "=", "GTR", ".", "standard", "(", "model", ",", "*", "*", "kwargs", ")", "infer_gtr", "=", "False", "except", ":", "print", "(", "\"Could not create GTR model from input arguments. Using default (Jukes-Cantor 1969)\"", ")", "gtr", "=", "GTR", ".", "standard", "(", "'jc'", ",", "alphabet", "=", "'aa'", "if", "params", ".", "aa", "else", "'nuc'", ")", "infer_gtr", "=", "False", "return", "gtr" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
read_if_vcf
Checks if input is VCF and reads in appropriately if it is
treetime/wrappers.py
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 params.vcf_reference: print("ERROR: a reference Fasta is required with VCF-format alignments") return -1 compress_seq = read_vcf(params.aln, params.vcf_reference) sequences = compress_seq['sequences'] ref = compress_seq['reference'] aln = sequences if not hasattr(params, 'gtr') or params.gtr=="infer": #if not specified, set it: alpha = alphabets['aa'] if params.aa else alphabets['nuc'] fixed_pi = [ref.count(base)/len(ref) for base in alpha] if fixed_pi[-1] == 0: fixed_pi[-1] = 0.05 fixed_pi = [v-0.01 for v in fixed_pi] return aln, ref, fixed_pi
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 params.vcf_reference: print("ERROR: a reference Fasta is required with VCF-format alignments") return -1 compress_seq = read_vcf(params.aln, params.vcf_reference) sequences = compress_seq['sequences'] ref = compress_seq['reference'] aln = sequences if not hasattr(params, 'gtr') or params.gtr=="infer": #if not specified, set it: alpha = alphabets['aa'] if params.aa else alphabets['nuc'] fixed_pi = [ref.count(base)/len(ref) for base in alpha] if fixed_pi[-1] == 0: fixed_pi[-1] = 0.05 fixed_pi = [v-0.01 for v in fixed_pi] return aln, ref, fixed_pi
[ "Checks", "if", "input", "is", "VCF", "and", "reads", "in", "appropriately", "if", "it", "is" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/wrappers.py#L124-L148
[ "def", "read_if_vcf", "(", "params", ")", ":", "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", "params", ".", "vcf_reference", ":", "print", "(", "\"ERROR: a reference Fasta is required with VCF-format alignments\"", ")", "return", "-", "1", "compress_seq", "=", "read_vcf", "(", "params", ".", "aln", ",", "params", ".", "vcf_reference", ")", "sequences", "=", "compress_seq", "[", "'sequences'", "]", "ref", "=", "compress_seq", "[", "'reference'", "]", "aln", "=", "sequences", "if", "not", "hasattr", "(", "params", ",", "'gtr'", ")", "or", "params", ".", "gtr", "==", "\"infer\"", ":", "#if not specified, set it:", "alpha", "=", "alphabets", "[", "'aa'", "]", "if", "params", ".", "aa", "else", "alphabets", "[", "'nuc'", "]", "fixed_pi", "=", "[", "ref", ".", "count", "(", "base", ")", "/", "len", "(", "ref", ")", "for", "base", "in", "alpha", "]", "if", "fixed_pi", "[", "-", "1", "]", "==", "0", ":", "fixed_pi", "[", "-", "1", "]", "=", "0.05", "fixed_pi", "=", "[", "v", "-", "0.01", "for", "v", "in", "fixed_pi", "]", "return", "aln", ",", "ref", ",", "fixed_pi" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
scan_homoplasies
the function implementing treetime homoplasies
treetime/wrappers.py
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 ########################################################################### #sets ref and fixed_pi to None if not VCF aln, ref, fixed_pi = read_if_vcf(params) is_vcf = True if ref is not None else False ########################################################################### ### ANCESTRAL RECONSTRUCTION ########################################################################### treeanc = TreeAnc(params.tree, aln=aln, ref=ref, gtr=gtr, verbose=1, fill_overhangs=True) if treeanc.aln is None: # if alignment didn't load, exit return 1 if is_vcf: L = len(ref) + params.const else: L = treeanc.aln.get_alignment_length() + params.const N_seq = len(treeanc.aln) N_tree = treeanc.tree.count_terminals() if params.rescale!=1.0: for n in treeanc.tree.find_clades(): n.branch_length *= params.rescale n.mutation_length = n.branch_length print("read alignment from file %s with %d sequences of length %d"%(params.aln,N_seq,L)) print("read tree from file %s with %d leaves"%(params.tree,N_tree)) print("\ninferring ancestral sequences...") ndiff = treeanc.infer_ancestral_sequences('ml', infer_gtr=params.gtr=='infer', marginal=False, fixed_pi=fixed_pi) print("...done.") if ndiff==ttconf.ERROR: # if reconstruction failed, exit print("Something went wrong during ancestral reconstruction, please check your input files.", file=sys.stderr) return 1 else: print("...done.") if is_vcf: treeanc.recover_var_ambigs() ########################################################################### ### analysis of reconstruction ########################################################################### from collections import defaultdict from scipy.stats import poisson offset = 0 if params.zero_based else 1 if params.drms: DRM_info = read_in_DRMs(params.drms, offset) drms = DRM_info['DRMs'] # construct dictionaries gathering mutations and positions mutations = defaultdict(list) positions = defaultdict(list) terminal_mutations = defaultdict(list) for n in treeanc.tree.find_clades(): if n.up is None: continue if len(n.mutations): for (a,pos, d) in n.mutations: if '-' not in [a,d] and 'N' not in [a,d]: mutations[(a,pos+offset,d)].append(n) positions[pos+offset].append(n) if n.is_terminal(): for (a,pos, d) in n.mutations: if '-' not in [a,d] and 'N' not in [a,d]: terminal_mutations[(a,pos+offset,d)].append(n) # gather homoplasic mutations by strain mutation_by_strain = defaultdict(list) for n in treeanc.tree.get_terminals(): for a,pos,d in n.mutations: if pos+offset in positions and len(positions[pos+offset])>1: if '-' not in [a,d] and 'N' not in [a,d]: mutation_by_strain[n.name].append([(a,pos+offset,d), len(positions[pos])]) # total_branch_length is the expected number of substitutions # corrected_branch_length is the expected number of observable substitutions # (probability of an odd number of substitutions at a particular site) total_branch_length = treeanc.tree.total_branch_length() corrected_branch_length = np.sum([np.exp(-x.branch_length)*np.sinh(x.branch_length) for x in treeanc.tree.find_clades()]) corrected_terminal_branch_length = np.sum([np.exp(-x.branch_length)*np.sinh(x.branch_length) for x in treeanc.tree.get_terminals()]) expected_mutations = L*corrected_branch_length expected_terminal_mutations = L*corrected_terminal_branch_length # make histograms and sum mutations in different categories multiplicities = np.bincount([len(x) for x in mutations.values()]) total_mutations = np.sum([len(x) for x in mutations.values()]) multiplicities_terminal = np.bincount([len(x) for x in terminal_mutations.values()]) terminal_mutation_count = np.sum([len(x) for x in terminal_mutations.values()]) multiplicities_positions = np.bincount([len(x) for x in positions.values()]) multiplicities_positions[0] = L - np.sum(multiplicities_positions) ########################################################################### ### Output the distribution of times particular mutations are observed ########################################################################### print("\nThe TOTAL tree length is %1.3e and %d mutations were observed." %(total_branch_length,total_mutations)) print("Of these %d mutations,"%total_mutations +"".join(['\n\t - %d occur %d times'%(n,mi) for mi,n in enumerate(multiplicities) if n])) # additional optional output this for terminal mutations only if params.detailed: print("\nThe TERMINAL branch length is %1.3e and %d mutations were observed." %(corrected_terminal_branch_length,terminal_mutation_count)) print("Of these %d mutations,"%terminal_mutation_count +"".join(['\n\t - %d occur %d times'%(n,mi) for mi,n in enumerate(multiplicities_terminal) if n])) ########################################################################### ### Output the distribution of times mutations at particular positions are observed ########################################################################### print("\nOf the %d positions in the genome,"%L +"".join(['\n\t - %d were hit %d times (expected %1.2f)'%(n,mi,L*poisson.pmf(mi,1.0*total_mutations/L)) for mi,n in enumerate(multiplicities_positions) if n])) # compare that distribution to a Poisson distribution with the same mean p = poisson.pmf(np.arange(10*multiplicities_positions.max()),1.0*total_mutations/L) print("\nlog-likelihood difference to Poisson distribution with same mean: %1.3e"%( - L*np.sum(p*np.log(p+1e-100)) + np.sum(multiplicities_positions*np.log(p[:len(multiplicities_positions)]+1e-100)))) ########################################################################### ### Output the mutations that are observed most often ########################################################################### if params.drms: print("\n\nThe ten most homoplasic mutations are:\n\tmut\tmultiplicity\tDRM details (gene drug AAmut)") mutations_sorted = sorted(mutations.items(), key=lambda x:len(x[1])-0.1*x[0][1]/L, reverse=True) for mut, val in mutations_sorted[:params.n]: if len(val)>1: print("\t%s%d%s\t%d\t%s"%(mut[0], mut[1], mut[2], len(val), " ".join([drms[mut[1]]['gene'], drms[mut[1]]['drug'], drms[mut[1]]['alt_base'][mut[2]]]) if mut[1] in drms else "")) else: break else: print("\n\nThe ten most homoplasic mutations are:\n\tmut\tmultiplicity") mutations_sorted = sorted(mutations.items(), key=lambda x:len(x[1])-0.1*x[0][1]/L, reverse=True) for mut, val in mutations_sorted[:params.n]: if len(val)>1: print("\t%s%d%s\t%d"%(mut[0], mut[1], mut[2], len(val))) else: break # optional output specifically for mutations on terminal branches if params.detailed: if params.drms: print("\n\nThe ten most homoplasic mutation on terminal branches are:\n\tmut\tmultiplicity\tDRM details (gene drug AAmut)") terminal_mutations_sorted = sorted(terminal_mutations.items(), key=lambda x:len(x[1])-0.1*x[0][1]/L, reverse=True) for mut, val in terminal_mutations_sorted[:params.n]: if len(val)>1: print("\t%s%d%s\t%d\t%s"%(mut[0], mut[1], mut[2], len(val), " ".join([drms[mut[1]]['gene'], drms[mut[1]]['drug'], drms[mut[1]]['alt_base'][mut[2]]]) if mut[1] in drms else "")) else: break else: print("\n\nThe ten most homoplasic mutation on terminal branches are:\n\tmut\tmultiplicity") terminal_mutations_sorted = sorted(terminal_mutations.items(), key=lambda x:len(x[1])-0.1*x[0][1]/L, reverse=True) for mut, val in terminal_mutations_sorted[:params.n]: if len(val)>1: print("\t%s%d%s\t%d"%(mut[0], mut[1], mut[2], len(val))) else: break ########################################################################### ### Output strains that have many homoplasic mutations ########################################################################### # TODO: add statistical criterion if params.detailed: if params.drms: print("\n\nTaxons that carry positions that mutated elsewhere in the tree:\n\ttaxon name\t#of homoplasic mutations\t# DRM") mutation_by_strain_sorted = sorted(mutation_by_strain.items(), key=lambda x:len(x[1]), reverse=True) for name, val in mutation_by_strain_sorted[:params.n]: if len(val): print("\t%s\t%d\t%d"%(name, len(val), len([mut for mut,l in val if mut[1] in drms]))) else: print("\n\nTaxons that carry positions that mutated elsewhere in the tree:\n\ttaxon name\t#of homoplasic mutations") mutation_by_strain_sorted = sorted(mutation_by_strain.items(), key=lambda x:len(x[1]), reverse=True) for name, val in mutation_by_strain_sorted[:params.n]: if len(val): print("\t%s\t%d"%(name, len(val))) return 0
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 ########################################################################### #sets ref and fixed_pi to None if not VCF aln, ref, fixed_pi = read_if_vcf(params) is_vcf = True if ref is not None else False ########################################################################### ### ANCESTRAL RECONSTRUCTION ########################################################################### treeanc = TreeAnc(params.tree, aln=aln, ref=ref, gtr=gtr, verbose=1, fill_overhangs=True) if treeanc.aln is None: # if alignment didn't load, exit return 1 if is_vcf: L = len(ref) + params.const else: L = treeanc.aln.get_alignment_length() + params.const N_seq = len(treeanc.aln) N_tree = treeanc.tree.count_terminals() if params.rescale!=1.0: for n in treeanc.tree.find_clades(): n.branch_length *= params.rescale n.mutation_length = n.branch_length print("read alignment from file %s with %d sequences of length %d"%(params.aln,N_seq,L)) print("read tree from file %s with %d leaves"%(params.tree,N_tree)) print("\ninferring ancestral sequences...") ndiff = treeanc.infer_ancestral_sequences('ml', infer_gtr=params.gtr=='infer', marginal=False, fixed_pi=fixed_pi) print("...done.") if ndiff==ttconf.ERROR: # if reconstruction failed, exit print("Something went wrong during ancestral reconstruction, please check your input files.", file=sys.stderr) return 1 else: print("...done.") if is_vcf: treeanc.recover_var_ambigs() ########################################################################### ### analysis of reconstruction ########################################################################### from collections import defaultdict from scipy.stats import poisson offset = 0 if params.zero_based else 1 if params.drms: DRM_info = read_in_DRMs(params.drms, offset) drms = DRM_info['DRMs'] # construct dictionaries gathering mutations and positions mutations = defaultdict(list) positions = defaultdict(list) terminal_mutations = defaultdict(list) for n in treeanc.tree.find_clades(): if n.up is None: continue if len(n.mutations): for (a,pos, d) in n.mutations: if '-' not in [a,d] and 'N' not in [a,d]: mutations[(a,pos+offset,d)].append(n) positions[pos+offset].append(n) if n.is_terminal(): for (a,pos, d) in n.mutations: if '-' not in [a,d] and 'N' not in [a,d]: terminal_mutations[(a,pos+offset,d)].append(n) # gather homoplasic mutations by strain mutation_by_strain = defaultdict(list) for n in treeanc.tree.get_terminals(): for a,pos,d in n.mutations: if pos+offset in positions and len(positions[pos+offset])>1: if '-' not in [a,d] and 'N' not in [a,d]: mutation_by_strain[n.name].append([(a,pos+offset,d), len(positions[pos])]) # total_branch_length is the expected number of substitutions # corrected_branch_length is the expected number of observable substitutions # (probability of an odd number of substitutions at a particular site) total_branch_length = treeanc.tree.total_branch_length() corrected_branch_length = np.sum([np.exp(-x.branch_length)*np.sinh(x.branch_length) for x in treeanc.tree.find_clades()]) corrected_terminal_branch_length = np.sum([np.exp(-x.branch_length)*np.sinh(x.branch_length) for x in treeanc.tree.get_terminals()]) expected_mutations = L*corrected_branch_length expected_terminal_mutations = L*corrected_terminal_branch_length # make histograms and sum mutations in different categories multiplicities = np.bincount([len(x) for x in mutations.values()]) total_mutations = np.sum([len(x) for x in mutations.values()]) multiplicities_terminal = np.bincount([len(x) for x in terminal_mutations.values()]) terminal_mutation_count = np.sum([len(x) for x in terminal_mutations.values()]) multiplicities_positions = np.bincount([len(x) for x in positions.values()]) multiplicities_positions[0] = L - np.sum(multiplicities_positions) ########################################################################### ### Output the distribution of times particular mutations are observed ########################################################################### print("\nThe TOTAL tree length is %1.3e and %d mutations were observed." %(total_branch_length,total_mutations)) print("Of these %d mutations,"%total_mutations +"".join(['\n\t - %d occur %d times'%(n,mi) for mi,n in enumerate(multiplicities) if n])) # additional optional output this for terminal mutations only if params.detailed: print("\nThe TERMINAL branch length is %1.3e and %d mutations were observed." %(corrected_terminal_branch_length,terminal_mutation_count)) print("Of these %d mutations,"%terminal_mutation_count +"".join(['\n\t - %d occur %d times'%(n,mi) for mi,n in enumerate(multiplicities_terminal) if n])) ########################################################################### ### Output the distribution of times mutations at particular positions are observed ########################################################################### print("\nOf the %d positions in the genome,"%L +"".join(['\n\t - %d were hit %d times (expected %1.2f)'%(n,mi,L*poisson.pmf(mi,1.0*total_mutations/L)) for mi,n in enumerate(multiplicities_positions) if n])) # compare that distribution to a Poisson distribution with the same mean p = poisson.pmf(np.arange(10*multiplicities_positions.max()),1.0*total_mutations/L) print("\nlog-likelihood difference to Poisson distribution with same mean: %1.3e"%( - L*np.sum(p*np.log(p+1e-100)) + np.sum(multiplicities_positions*np.log(p[:len(multiplicities_positions)]+1e-100)))) ########################################################################### ### Output the mutations that are observed most often ########################################################################### if params.drms: print("\n\nThe ten most homoplasic mutations are:\n\tmut\tmultiplicity\tDRM details (gene drug AAmut)") mutations_sorted = sorted(mutations.items(), key=lambda x:len(x[1])-0.1*x[0][1]/L, reverse=True) for mut, val in mutations_sorted[:params.n]: if len(val)>1: print("\t%s%d%s\t%d\t%s"%(mut[0], mut[1], mut[2], len(val), " ".join([drms[mut[1]]['gene'], drms[mut[1]]['drug'], drms[mut[1]]['alt_base'][mut[2]]]) if mut[1] in drms else "")) else: break else: print("\n\nThe ten most homoplasic mutations are:\n\tmut\tmultiplicity") mutations_sorted = sorted(mutations.items(), key=lambda x:len(x[1])-0.1*x[0][1]/L, reverse=True) for mut, val in mutations_sorted[:params.n]: if len(val)>1: print("\t%s%d%s\t%d"%(mut[0], mut[1], mut[2], len(val))) else: break # optional output specifically for mutations on terminal branches if params.detailed: if params.drms: print("\n\nThe ten most homoplasic mutation on terminal branches are:\n\tmut\tmultiplicity\tDRM details (gene drug AAmut)") terminal_mutations_sorted = sorted(terminal_mutations.items(), key=lambda x:len(x[1])-0.1*x[0][1]/L, reverse=True) for mut, val in terminal_mutations_sorted[:params.n]: if len(val)>1: print("\t%s%d%s\t%d\t%s"%(mut[0], mut[1], mut[2], len(val), " ".join([drms[mut[1]]['gene'], drms[mut[1]]['drug'], drms[mut[1]]['alt_base'][mut[2]]]) if mut[1] in drms else "")) else: break else: print("\n\nThe ten most homoplasic mutation on terminal branches are:\n\tmut\tmultiplicity") terminal_mutations_sorted = sorted(terminal_mutations.items(), key=lambda x:len(x[1])-0.1*x[0][1]/L, reverse=True) for mut, val in terminal_mutations_sorted[:params.n]: if len(val)>1: print("\t%s%d%s\t%d"%(mut[0], mut[1], mut[2], len(val))) else: break ########################################################################### ### Output strains that have many homoplasic mutations ########################################################################### # TODO: add statistical criterion if params.detailed: if params.drms: print("\n\nTaxons that carry positions that mutated elsewhere in the tree:\n\ttaxon name\t#of homoplasic mutations\t# DRM") mutation_by_strain_sorted = sorted(mutation_by_strain.items(), key=lambda x:len(x[1]), reverse=True) for name, val in mutation_by_strain_sorted[:params.n]: if len(val): print("\t%s\t%d\t%d"%(name, len(val), len([mut for mut,l in val if mut[1] in drms]))) else: print("\n\nTaxons that carry positions that mutated elsewhere in the tree:\n\ttaxon name\t#of homoplasic mutations") mutation_by_strain_sorted = sorted(mutation_by_strain.items(), key=lambda x:len(x[1]), reverse=True) for name, val in mutation_by_strain_sorted[:params.n]: if len(val): print("\t%s\t%d"%(name, len(val))) return 0
[ "the", "function", "implementing", "treetime", "homoplasies" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/wrappers.py#L254-L458
[ "def", "scan_homoplasies", "(", "params", ")", ":", "if", "assure_tree", "(", "params", ",", "tmp_dir", "=", "'homoplasy_tmp'", ")", ":", "return", "1", "gtr", "=", "create_gtr", "(", "params", ")", "###########################################################################", "### READ IN VCF", "###########################################################################", "#sets ref and fixed_pi to None if not VCF", "aln", ",", "ref", ",", "fixed_pi", "=", "read_if_vcf", "(", "params", ")", "is_vcf", "=", "True", "if", "ref", "is", "not", "None", "else", "False", "###########################################################################", "### ANCESTRAL RECONSTRUCTION", "###########################################################################", "treeanc", "=", "TreeAnc", "(", "params", ".", "tree", ",", "aln", "=", "aln", ",", "ref", "=", "ref", ",", "gtr", "=", "gtr", ",", "verbose", "=", "1", ",", "fill_overhangs", "=", "True", ")", "if", "treeanc", ".", "aln", "is", "None", ":", "# if alignment didn't load, exit", "return", "1", "if", "is_vcf", ":", "L", "=", "len", "(", "ref", ")", "+", "params", ".", "const", "else", ":", "L", "=", "treeanc", ".", "aln", ".", "get_alignment_length", "(", ")", "+", "params", ".", "const", "N_seq", "=", "len", "(", "treeanc", ".", "aln", ")", "N_tree", "=", "treeanc", ".", "tree", ".", "count_terminals", "(", ")", "if", "params", ".", "rescale", "!=", "1.0", ":", "for", "n", "in", "treeanc", ".", "tree", ".", "find_clades", "(", ")", ":", "n", ".", "branch_length", "*=", "params", ".", "rescale", "n", ".", "mutation_length", "=", "n", ".", "branch_length", "print", "(", "\"read alignment from file %s with %d sequences of length %d\"", "%", "(", "params", ".", "aln", ",", "N_seq", ",", "L", ")", ")", "print", "(", "\"read tree from file %s with %d leaves\"", "%", "(", "params", ".", "tree", ",", "N_tree", ")", ")", "print", "(", "\"\\ninferring ancestral sequences...\"", ")", "ndiff", "=", "treeanc", ".", "infer_ancestral_sequences", "(", "'ml'", ",", "infer_gtr", "=", "params", ".", "gtr", "==", "'infer'", ",", "marginal", "=", "False", ",", "fixed_pi", "=", "fixed_pi", ")", "print", "(", "\"...done.\"", ")", "if", "ndiff", "==", "ttconf", ".", "ERROR", ":", "# if reconstruction failed, exit", "print", "(", "\"Something went wrong during ancestral reconstruction, please check your input files.\"", ",", "file", "=", "sys", ".", "stderr", ")", "return", "1", "else", ":", "print", "(", "\"...done.\"", ")", "if", "is_vcf", ":", "treeanc", ".", "recover_var_ambigs", "(", ")", "###########################################################################", "### analysis of reconstruction", "###########################################################################", "from", "collections", "import", "defaultdict", "from", "scipy", ".", "stats", "import", "poisson", "offset", "=", "0", "if", "params", ".", "zero_based", "else", "1", "if", "params", ".", "drms", ":", "DRM_info", "=", "read_in_DRMs", "(", "params", ".", "drms", ",", "offset", ")", "drms", "=", "DRM_info", "[", "'DRMs'", "]", "# construct dictionaries gathering mutations and positions", "mutations", "=", "defaultdict", "(", "list", ")", "positions", "=", "defaultdict", "(", "list", ")", "terminal_mutations", "=", "defaultdict", "(", "list", ")", "for", "n", "in", "treeanc", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "n", ".", "up", "is", "None", ":", "continue", "if", "len", "(", "n", ".", "mutations", ")", ":", "for", "(", "a", ",", "pos", ",", "d", ")", "in", "n", ".", "mutations", ":", "if", "'-'", "not", "in", "[", "a", ",", "d", "]", "and", "'N'", "not", "in", "[", "a", ",", "d", "]", ":", "mutations", "[", "(", "a", ",", "pos", "+", "offset", ",", "d", ")", "]", ".", "append", "(", "n", ")", "positions", "[", "pos", "+", "offset", "]", ".", "append", "(", "n", ")", "if", "n", ".", "is_terminal", "(", ")", ":", "for", "(", "a", ",", "pos", ",", "d", ")", "in", "n", ".", "mutations", ":", "if", "'-'", "not", "in", "[", "a", ",", "d", "]", "and", "'N'", "not", "in", "[", "a", ",", "d", "]", ":", "terminal_mutations", "[", "(", "a", ",", "pos", "+", "offset", ",", "d", ")", "]", ".", "append", "(", "n", ")", "# gather homoplasic mutations by strain", "mutation_by_strain", "=", "defaultdict", "(", "list", ")", "for", "n", "in", "treeanc", ".", "tree", ".", "get_terminals", "(", ")", ":", "for", "a", ",", "pos", ",", "d", "in", "n", ".", "mutations", ":", "if", "pos", "+", "offset", "in", "positions", "and", "len", "(", "positions", "[", "pos", "+", "offset", "]", ")", ">", "1", ":", "if", "'-'", "not", "in", "[", "a", ",", "d", "]", "and", "'N'", "not", "in", "[", "a", ",", "d", "]", ":", "mutation_by_strain", "[", "n", ".", "name", "]", ".", "append", "(", "[", "(", "a", ",", "pos", "+", "offset", ",", "d", ")", ",", "len", "(", "positions", "[", "pos", "]", ")", "]", ")", "# total_branch_length is the expected number of substitutions", "# corrected_branch_length is the expected number of observable substitutions", "# (probability of an odd number of substitutions at a particular site)", "total_branch_length", "=", "treeanc", ".", "tree", ".", "total_branch_length", "(", ")", "corrected_branch_length", "=", "np", ".", "sum", "(", "[", "np", ".", "exp", "(", "-", "x", ".", "branch_length", ")", "*", "np", ".", "sinh", "(", "x", ".", "branch_length", ")", "for", "x", "in", "treeanc", ".", "tree", ".", "find_clades", "(", ")", "]", ")", "corrected_terminal_branch_length", "=", "np", ".", "sum", "(", "[", "np", ".", "exp", "(", "-", "x", ".", "branch_length", ")", "*", "np", ".", "sinh", "(", "x", ".", "branch_length", ")", "for", "x", "in", "treeanc", ".", "tree", ".", "get_terminals", "(", ")", "]", ")", "expected_mutations", "=", "L", "*", "corrected_branch_length", "expected_terminal_mutations", "=", "L", "*", "corrected_terminal_branch_length", "# make histograms and sum mutations in different categories", "multiplicities", "=", "np", ".", "bincount", "(", "[", "len", "(", "x", ")", "for", "x", "in", "mutations", ".", "values", "(", ")", "]", ")", "total_mutations", "=", "np", ".", "sum", "(", "[", "len", "(", "x", ")", "for", "x", "in", "mutations", ".", "values", "(", ")", "]", ")", "multiplicities_terminal", "=", "np", ".", "bincount", "(", "[", "len", "(", "x", ")", "for", "x", "in", "terminal_mutations", ".", "values", "(", ")", "]", ")", "terminal_mutation_count", "=", "np", ".", "sum", "(", "[", "len", "(", "x", ")", "for", "x", "in", "terminal_mutations", ".", "values", "(", ")", "]", ")", "multiplicities_positions", "=", "np", ".", "bincount", "(", "[", "len", "(", "x", ")", "for", "x", "in", "positions", ".", "values", "(", ")", "]", ")", "multiplicities_positions", "[", "0", "]", "=", "L", "-", "np", ".", "sum", "(", "multiplicities_positions", ")", "###########################################################################", "### Output the distribution of times particular mutations are observed", "###########################################################################", "print", "(", "\"\\nThe TOTAL tree length is %1.3e and %d mutations were observed.\"", "%", "(", "total_branch_length", ",", "total_mutations", ")", ")", "print", "(", "\"Of these %d mutations,\"", "%", "total_mutations", "+", "\"\"", ".", "join", "(", "[", "'\\n\\t - %d occur %d times'", "%", "(", "n", ",", "mi", ")", "for", "mi", ",", "n", "in", "enumerate", "(", "multiplicities", ")", "if", "n", "]", ")", ")", "# additional optional output this for terminal mutations only", "if", "params", ".", "detailed", ":", "print", "(", "\"\\nThe TERMINAL branch length is %1.3e and %d mutations were observed.\"", "%", "(", "corrected_terminal_branch_length", ",", "terminal_mutation_count", ")", ")", "print", "(", "\"Of these %d mutations,\"", "%", "terminal_mutation_count", "+", "\"\"", ".", "join", "(", "[", "'\\n\\t - %d occur %d times'", "%", "(", "n", ",", "mi", ")", "for", "mi", ",", "n", "in", "enumerate", "(", "multiplicities_terminal", ")", "if", "n", "]", ")", ")", "###########################################################################", "### Output the distribution of times mutations at particular positions are observed", "###########################################################################", "print", "(", "\"\\nOf the %d positions in the genome,\"", "%", "L", "+", "\"\"", ".", "join", "(", "[", "'\\n\\t - %d were hit %d times (expected %1.2f)'", "%", "(", "n", ",", "mi", ",", "L", "*", "poisson", ".", "pmf", "(", "mi", ",", "1.0", "*", "total_mutations", "/", "L", ")", ")", "for", "mi", ",", "n", "in", "enumerate", "(", "multiplicities_positions", ")", "if", "n", "]", ")", ")", "# compare that distribution to a Poisson distribution with the same mean", "p", "=", "poisson", ".", "pmf", "(", "np", ".", "arange", "(", "10", "*", "multiplicities_positions", ".", "max", "(", ")", ")", ",", "1.0", "*", "total_mutations", "/", "L", ")", "print", "(", "\"\\nlog-likelihood difference to Poisson distribution with same mean: %1.3e\"", "%", "(", "-", "L", "*", "np", ".", "sum", "(", "p", "*", "np", ".", "log", "(", "p", "+", "1e-100", ")", ")", "+", "np", ".", "sum", "(", "multiplicities_positions", "*", "np", ".", "log", "(", "p", "[", ":", "len", "(", "multiplicities_positions", ")", "]", "+", "1e-100", ")", ")", ")", ")", "###########################################################################", "### Output the mutations that are observed most often", "###########################################################################", "if", "params", ".", "drms", ":", "print", "(", "\"\\n\\nThe ten most homoplasic mutations are:\\n\\tmut\\tmultiplicity\\tDRM details (gene drug AAmut)\"", ")", "mutations_sorted", "=", "sorted", "(", "mutations", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "len", "(", "x", "[", "1", "]", ")", "-", "0.1", "*", "x", "[", "0", "]", "[", "1", "]", "/", "L", ",", "reverse", "=", "True", ")", "for", "mut", ",", "val", "in", "mutations_sorted", "[", ":", "params", ".", "n", "]", ":", "if", "len", "(", "val", ")", ">", "1", ":", "print", "(", "\"\\t%s%d%s\\t%d\\t%s\"", "%", "(", "mut", "[", "0", "]", ",", "mut", "[", "1", "]", ",", "mut", "[", "2", "]", ",", "len", "(", "val", ")", ",", "\" \"", ".", "join", "(", "[", "drms", "[", "mut", "[", "1", "]", "]", "[", "'gene'", "]", ",", "drms", "[", "mut", "[", "1", "]", "]", "[", "'drug'", "]", ",", "drms", "[", "mut", "[", "1", "]", "]", "[", "'alt_base'", "]", "[", "mut", "[", "2", "]", "]", "]", ")", "if", "mut", "[", "1", "]", "in", "drms", "else", "\"\"", ")", ")", "else", ":", "break", "else", ":", "print", "(", "\"\\n\\nThe ten most homoplasic mutations are:\\n\\tmut\\tmultiplicity\"", ")", "mutations_sorted", "=", "sorted", "(", "mutations", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "len", "(", "x", "[", "1", "]", ")", "-", "0.1", "*", "x", "[", "0", "]", "[", "1", "]", "/", "L", ",", "reverse", "=", "True", ")", "for", "mut", ",", "val", "in", "mutations_sorted", "[", ":", "params", ".", "n", "]", ":", "if", "len", "(", "val", ")", ">", "1", ":", "print", "(", "\"\\t%s%d%s\\t%d\"", "%", "(", "mut", "[", "0", "]", ",", "mut", "[", "1", "]", ",", "mut", "[", "2", "]", ",", "len", "(", "val", ")", ")", ")", "else", ":", "break", "# optional output specifically for mutations on terminal branches", "if", "params", ".", "detailed", ":", "if", "params", ".", "drms", ":", "print", "(", "\"\\n\\nThe ten most homoplasic mutation on terminal branches are:\\n\\tmut\\tmultiplicity\\tDRM details (gene drug AAmut)\"", ")", "terminal_mutations_sorted", "=", "sorted", "(", "terminal_mutations", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "len", "(", "x", "[", "1", "]", ")", "-", "0.1", "*", "x", "[", "0", "]", "[", "1", "]", "/", "L", ",", "reverse", "=", "True", ")", "for", "mut", ",", "val", "in", "terminal_mutations_sorted", "[", ":", "params", ".", "n", "]", ":", "if", "len", "(", "val", ")", ">", "1", ":", "print", "(", "\"\\t%s%d%s\\t%d\\t%s\"", "%", "(", "mut", "[", "0", "]", ",", "mut", "[", "1", "]", ",", "mut", "[", "2", "]", ",", "len", "(", "val", ")", ",", "\" \"", ".", "join", "(", "[", "drms", "[", "mut", "[", "1", "]", "]", "[", "'gene'", "]", ",", "drms", "[", "mut", "[", "1", "]", "]", "[", "'drug'", "]", ",", "drms", "[", "mut", "[", "1", "]", "]", "[", "'alt_base'", "]", "[", "mut", "[", "2", "]", "]", "]", ")", "if", "mut", "[", "1", "]", "in", "drms", "else", "\"\"", ")", ")", "else", ":", "break", "else", ":", "print", "(", "\"\\n\\nThe ten most homoplasic mutation on terminal branches are:\\n\\tmut\\tmultiplicity\"", ")", "terminal_mutations_sorted", "=", "sorted", "(", "terminal_mutations", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "len", "(", "x", "[", "1", "]", ")", "-", "0.1", "*", "x", "[", "0", "]", "[", "1", "]", "/", "L", ",", "reverse", "=", "True", ")", "for", "mut", ",", "val", "in", "terminal_mutations_sorted", "[", ":", "params", ".", "n", "]", ":", "if", "len", "(", "val", ")", ">", "1", ":", "print", "(", "\"\\t%s%d%s\\t%d\"", "%", "(", "mut", "[", "0", "]", ",", "mut", "[", "1", "]", ",", "mut", "[", "2", "]", ",", "len", "(", "val", ")", ")", ")", "else", ":", "break", "###########################################################################", "### Output strains that have many homoplasic mutations", "###########################################################################", "# TODO: add statistical criterion", "if", "params", ".", "detailed", ":", "if", "params", ".", "drms", ":", "print", "(", "\"\\n\\nTaxons that carry positions that mutated elsewhere in the tree:\\n\\ttaxon name\\t#of homoplasic mutations\\t# DRM\"", ")", "mutation_by_strain_sorted", "=", "sorted", "(", "mutation_by_strain", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "len", "(", "x", "[", "1", "]", ")", ",", "reverse", "=", "True", ")", "for", "name", ",", "val", "in", "mutation_by_strain_sorted", "[", ":", "params", ".", "n", "]", ":", "if", "len", "(", "val", ")", ":", "print", "(", "\"\\t%s\\t%d\\t%d\"", "%", "(", "name", ",", "len", "(", "val", ")", ",", "len", "(", "[", "mut", "for", "mut", ",", "l", "in", "val", "if", "mut", "[", "1", "]", "in", "drms", "]", ")", ")", ")", "else", ":", "print", "(", "\"\\n\\nTaxons that carry positions that mutated elsewhere in the tree:\\n\\ttaxon name\\t#of homoplasic mutations\"", ")", "mutation_by_strain_sorted", "=", "sorted", "(", "mutation_by_strain", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "len", "(", "x", "[", "1", "]", ")", ",", "reverse", "=", "True", ")", "for", "name", ",", "val", "in", "mutation_by_strain_sorted", "[", ":", "params", ".", "n", "]", ":", "if", "len", "(", "val", ")", ":", "print", "(", "\"\\t%s\\t%d\"", "%", "(", "name", ",", "len", "(", "val", ")", ")", ")", "return", "0" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
timetree
implementeing treetime tree
treetime/wrappers.py
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]} dates = utils.parse_dates(params.dates) if len(dates)==0: print("No valid dates -- exiting.") return 1 if assure_tree(params, tmp_dir='timetree_tmp'): print("No tree -- exiting.") return 1 outdir = get_outdir(params, '_treetime') gtr = create_gtr(params) infer_gtr = params.gtr=='infer' ########################################################################### ### READ IN VCF ########################################################################### #sets ref and fixed_pi to None if not VCF aln, ref, fixed_pi = read_if_vcf(params) is_vcf = True if ref is not None else False branch_length_mode = params.branch_length_mode #variable-site-only trees can have big branch lengths, the auto setting won't work. if is_vcf or (params.aln and params.sequence_length): if branch_length_mode == 'auto': branch_length_mode = 'joint' ########################################################################### ### SET-UP and RUN ########################################################################### if params.aln is None and params.sequence_length is None: print("one of arguments '--aln' and '--sequence-length' is required.", file=sys.stderr) return 1 myTree = TreeTime(dates=dates, tree=params.tree, ref=ref, aln=aln, gtr=gtr, seq_len=params.sequence_length, verbose=params.verbose) myTree.tip_slack=params.tip_slack if not myTree.one_mutation: print("TreeTime setup failed, exiting") return 1 # coalescent model options try: coalescent = float(params.coalescent) if coalescent<10*myTree.one_mutation: coalescent = None except: if params.coalescent in ['opt', 'const', 'skyline']: coalescent = params.coalescent else: print("unknown coalescent model specification, has to be either " "a float, 'opt', 'const' or 'skyline' -- exiting") return 1 # determine whether confidence intervals are to be computed and how the # uncertainty in the rate estimate should be treated calc_confidence = params.confidence if params.clock_std_dev: vary_rate = params.clock_std_dev if calc_confidence else False elif params.confidence and params.covariation: vary_rate = True elif params.confidence: print("\nOutside of covariance aware mode TreeTime cannot estimate confidence intervals " "without specified standard deviation of the clock rate Please specify '--clock-std-dev' " "or rerun with '--covariance'. Will proceed without confidence estimation") vary_rate = False calc_confidence = False else: vary_rate = False # RUN root = None if params.keep_root else params.reroot success = myTree.run(root=root, relaxed_clock=relaxed_clock_params, resolve_polytomies=(not params.keep_polytomies), Tc=coalescent, max_iter=params.max_iter, fixed_clock_rate=params.clock_rate, n_iqd=params.clock_filter, time_marginal="assign" if calc_confidence else False, vary_rate = vary_rate, branch_length_mode = branch_length_mode, fixed_pi=fixed_pi, use_covariation = params.covariation) if success==ttconf.ERROR: # if TreeTime.run failed, exit print("\nTreeTime run FAILED: please check above for errors and/or rerun with --verbose 4.\n") return 1 ########################################################################### ### OUTPUT and saving of results ########################################################################### if infer_gtr: print('\nInferred GTR model:') print(myTree.gtr) print(myTree.date2dist) basename = get_basename(params, outdir) if coalescent in ['skyline', 'opt', 'const']: print("Inferred coalescent model") if coalescent=='skyline': print_save_plot_skyline(myTree, plot=basename+'skyline.pdf', save=basename+'skyline.tsv', screen=True) else: Tc = myTree.merger_model.Tc.y[0] print(" --T_c: \t %1.2e \toptimized inverse merger rate in units of substitutions"%Tc) print(" --T_c: \t %1.2e \toptimized inverse merger rate in years"%(Tc/myTree.date2dist.clock_rate)) print(" --N_e: \t %1.2e \tcorresponding 'effective population size' assuming 50 gen/year\n"%(Tc/myTree.date2dist.clock_rate*50)) # plot import matplotlib.pyplot as plt from .treetime import plot_vs_years leaf_count = myTree.tree.count_terminals() label_func = lambda x: (x.name if x.is_terminal() and ((leaf_count<30 and (not params.no_tip_labels)) or params.tip_labels) else '') plot_vs_years(myTree, show_confidence=False, label_func=label_func, confidence=0.9 if params.confidence else None) tree_fname = (outdir + params.plot_tree) plt.savefig(tree_fname) print("--- saved tree as \n\t %s\n"%tree_fname) plot_rtt(myTree, outdir + params.plot_rtt) if params.relax: fname = outdir+'substitution_rates.tsv' print("--- wrote branch specific rates to\n\t %s\n"%fname) with open(fname, 'w') as fh: fh.write("#node\tclock_length\tmutation_length\trate\tfold_change\n") for n in myTree.tree.find_clades(order="preorder"): if n==myTree.tree.root: continue g = n.branch_length_interpolator.gamma fh.write("%s\t%1.3e\t%1.3e\t%1.3e\t%1.2f\n"%(n.name, n.clock_length, n.mutation_length, myTree.date2dist.clock_rate*g, g)) export_sequences_and_tree(myTree, basename, is_vcf, params.zero_based, timetree=True, confidence=calc_confidence) return 0
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]} dates = utils.parse_dates(params.dates) if len(dates)==0: print("No valid dates -- exiting.") return 1 if assure_tree(params, tmp_dir='timetree_tmp'): print("No tree -- exiting.") return 1 outdir = get_outdir(params, '_treetime') gtr = create_gtr(params) infer_gtr = params.gtr=='infer' ########################################################################### ### READ IN VCF ########################################################################### #sets ref and fixed_pi to None if not VCF aln, ref, fixed_pi = read_if_vcf(params) is_vcf = True if ref is not None else False branch_length_mode = params.branch_length_mode #variable-site-only trees can have big branch lengths, the auto setting won't work. if is_vcf or (params.aln and params.sequence_length): if branch_length_mode == 'auto': branch_length_mode = 'joint' ########################################################################### ### SET-UP and RUN ########################################################################### if params.aln is None and params.sequence_length is None: print("one of arguments '--aln' and '--sequence-length' is required.", file=sys.stderr) return 1 myTree = TreeTime(dates=dates, tree=params.tree, ref=ref, aln=aln, gtr=gtr, seq_len=params.sequence_length, verbose=params.verbose) myTree.tip_slack=params.tip_slack if not myTree.one_mutation: print("TreeTime setup failed, exiting") return 1 # coalescent model options try: coalescent = float(params.coalescent) if coalescent<10*myTree.one_mutation: coalescent = None except: if params.coalescent in ['opt', 'const', 'skyline']: coalescent = params.coalescent else: print("unknown coalescent model specification, has to be either " "a float, 'opt', 'const' or 'skyline' -- exiting") return 1 # determine whether confidence intervals are to be computed and how the # uncertainty in the rate estimate should be treated calc_confidence = params.confidence if params.clock_std_dev: vary_rate = params.clock_std_dev if calc_confidence else False elif params.confidence and params.covariation: vary_rate = True elif params.confidence: print("\nOutside of covariance aware mode TreeTime cannot estimate confidence intervals " "without specified standard deviation of the clock rate Please specify '--clock-std-dev' " "or rerun with '--covariance'. Will proceed without confidence estimation") vary_rate = False calc_confidence = False else: vary_rate = False # RUN root = None if params.keep_root else params.reroot success = myTree.run(root=root, relaxed_clock=relaxed_clock_params, resolve_polytomies=(not params.keep_polytomies), Tc=coalescent, max_iter=params.max_iter, fixed_clock_rate=params.clock_rate, n_iqd=params.clock_filter, time_marginal="assign" if calc_confidence else False, vary_rate = vary_rate, branch_length_mode = branch_length_mode, fixed_pi=fixed_pi, use_covariation = params.covariation) if success==ttconf.ERROR: # if TreeTime.run failed, exit print("\nTreeTime run FAILED: please check above for errors and/or rerun with --verbose 4.\n") return 1 ########################################################################### ### OUTPUT and saving of results ########################################################################### if infer_gtr: print('\nInferred GTR model:') print(myTree.gtr) print(myTree.date2dist) basename = get_basename(params, outdir) if coalescent in ['skyline', 'opt', 'const']: print("Inferred coalescent model") if coalescent=='skyline': print_save_plot_skyline(myTree, plot=basename+'skyline.pdf', save=basename+'skyline.tsv', screen=True) else: Tc = myTree.merger_model.Tc.y[0] print(" --T_c: \t %1.2e \toptimized inverse merger rate in units of substitutions"%Tc) print(" --T_c: \t %1.2e \toptimized inverse merger rate in years"%(Tc/myTree.date2dist.clock_rate)) print(" --N_e: \t %1.2e \tcorresponding 'effective population size' assuming 50 gen/year\n"%(Tc/myTree.date2dist.clock_rate*50)) # plot import matplotlib.pyplot as plt from .treetime import plot_vs_years leaf_count = myTree.tree.count_terminals() label_func = lambda x: (x.name if x.is_terminal() and ((leaf_count<30 and (not params.no_tip_labels)) or params.tip_labels) else '') plot_vs_years(myTree, show_confidence=False, label_func=label_func, confidence=0.9 if params.confidence else None) tree_fname = (outdir + params.plot_tree) plt.savefig(tree_fname) print("--- saved tree as \n\t %s\n"%tree_fname) plot_rtt(myTree, outdir + params.plot_rtt) if params.relax: fname = outdir+'substitution_rates.tsv' print("--- wrote branch specific rates to\n\t %s\n"%fname) with open(fname, 'w') as fh: fh.write("#node\tclock_length\tmutation_length\trate\tfold_change\n") for n in myTree.tree.find_clades(order="preorder"): if n==myTree.tree.root: continue g = n.branch_length_interpolator.gamma fh.write("%s\t%1.3e\t%1.3e\t%1.3e\t%1.2f\n"%(n.name, n.clock_length, n.mutation_length, myTree.date2dist.clock_rate*g, g)) export_sequences_and_tree(myTree, basename, is_vcf, params.zero_based, timetree=True, confidence=calc_confidence) return 0
[ "implementeing", "treetime", "tree" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/wrappers.py#L461-L609
[ "def", "timetree", "(", "params", ")", ":", "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", "]", "}", "dates", "=", "utils", ".", "parse_dates", "(", "params", ".", "dates", ")", "if", "len", "(", "dates", ")", "==", "0", ":", "print", "(", "\"No valid dates -- exiting.\"", ")", "return", "1", "if", "assure_tree", "(", "params", ",", "tmp_dir", "=", "'timetree_tmp'", ")", ":", "print", "(", "\"No tree -- exiting.\"", ")", "return", "1", "outdir", "=", "get_outdir", "(", "params", ",", "'_treetime'", ")", "gtr", "=", "create_gtr", "(", "params", ")", "infer_gtr", "=", "params", ".", "gtr", "==", "'infer'", "###########################################################################", "### READ IN VCF", "###########################################################################", "#sets ref and fixed_pi to None if not VCF", "aln", ",", "ref", ",", "fixed_pi", "=", "read_if_vcf", "(", "params", ")", "is_vcf", "=", "True", "if", "ref", "is", "not", "None", "else", "False", "branch_length_mode", "=", "params", ".", "branch_length_mode", "#variable-site-only trees can have big branch lengths, the auto setting won't work.", "if", "is_vcf", "or", "(", "params", ".", "aln", "and", "params", ".", "sequence_length", ")", ":", "if", "branch_length_mode", "==", "'auto'", ":", "branch_length_mode", "=", "'joint'", "###########################################################################", "### SET-UP and RUN", "###########################################################################", "if", "params", ".", "aln", "is", "None", "and", "params", ".", "sequence_length", "is", "None", ":", "print", "(", "\"one of arguments '--aln' and '--sequence-length' is required.\"", ",", "file", "=", "sys", ".", "stderr", ")", "return", "1", "myTree", "=", "TreeTime", "(", "dates", "=", "dates", ",", "tree", "=", "params", ".", "tree", ",", "ref", "=", "ref", ",", "aln", "=", "aln", ",", "gtr", "=", "gtr", ",", "seq_len", "=", "params", ".", "sequence_length", ",", "verbose", "=", "params", ".", "verbose", ")", "myTree", ".", "tip_slack", "=", "params", ".", "tip_slack", "if", "not", "myTree", ".", "one_mutation", ":", "print", "(", "\"TreeTime setup failed, exiting\"", ")", "return", "1", "# coalescent model options", "try", ":", "coalescent", "=", "float", "(", "params", ".", "coalescent", ")", "if", "coalescent", "<", "10", "*", "myTree", ".", "one_mutation", ":", "coalescent", "=", "None", "except", ":", "if", "params", ".", "coalescent", "in", "[", "'opt'", ",", "'const'", ",", "'skyline'", "]", ":", "coalescent", "=", "params", ".", "coalescent", "else", ":", "print", "(", "\"unknown coalescent model specification, has to be either \"", "\"a float, 'opt', 'const' or 'skyline' -- exiting\"", ")", "return", "1", "# determine whether confidence intervals are to be computed and how the", "# uncertainty in the rate estimate should be treated", "calc_confidence", "=", "params", ".", "confidence", "if", "params", ".", "clock_std_dev", ":", "vary_rate", "=", "params", ".", "clock_std_dev", "if", "calc_confidence", "else", "False", "elif", "params", ".", "confidence", "and", "params", ".", "covariation", ":", "vary_rate", "=", "True", "elif", "params", ".", "confidence", ":", "print", "(", "\"\\nOutside of covariance aware mode TreeTime cannot estimate confidence intervals \"", "\"without specified standard deviation of the clock rate Please specify '--clock-std-dev' \"", "\"or rerun with '--covariance'. Will proceed without confidence estimation\"", ")", "vary_rate", "=", "False", "calc_confidence", "=", "False", "else", ":", "vary_rate", "=", "False", "# RUN", "root", "=", "None", "if", "params", ".", "keep_root", "else", "params", ".", "reroot", "success", "=", "myTree", ".", "run", "(", "root", "=", "root", ",", "relaxed_clock", "=", "relaxed_clock_params", ",", "resolve_polytomies", "=", "(", "not", "params", ".", "keep_polytomies", ")", ",", "Tc", "=", "coalescent", ",", "max_iter", "=", "params", ".", "max_iter", ",", "fixed_clock_rate", "=", "params", ".", "clock_rate", ",", "n_iqd", "=", "params", ".", "clock_filter", ",", "time_marginal", "=", "\"assign\"", "if", "calc_confidence", "else", "False", ",", "vary_rate", "=", "vary_rate", ",", "branch_length_mode", "=", "branch_length_mode", ",", "fixed_pi", "=", "fixed_pi", ",", "use_covariation", "=", "params", ".", "covariation", ")", "if", "success", "==", "ttconf", ".", "ERROR", ":", "# if TreeTime.run failed, exit", "print", "(", "\"\\nTreeTime run FAILED: please check above for errors and/or rerun with --verbose 4.\\n\"", ")", "return", "1", "###########################################################################", "### OUTPUT and saving of results", "###########################################################################", "if", "infer_gtr", ":", "print", "(", "'\\nInferred GTR model:'", ")", "print", "(", "myTree", ".", "gtr", ")", "print", "(", "myTree", ".", "date2dist", ")", "basename", "=", "get_basename", "(", "params", ",", "outdir", ")", "if", "coalescent", "in", "[", "'skyline'", ",", "'opt'", ",", "'const'", "]", ":", "print", "(", "\"Inferred coalescent model\"", ")", "if", "coalescent", "==", "'skyline'", ":", "print_save_plot_skyline", "(", "myTree", ",", "plot", "=", "basename", "+", "'skyline.pdf'", ",", "save", "=", "basename", "+", "'skyline.tsv'", ",", "screen", "=", "True", ")", "else", ":", "Tc", "=", "myTree", ".", "merger_model", ".", "Tc", ".", "y", "[", "0", "]", "print", "(", "\" --T_c: \\t %1.2e \\toptimized inverse merger rate in units of substitutions\"", "%", "Tc", ")", "print", "(", "\" --T_c: \\t %1.2e \\toptimized inverse merger rate in years\"", "%", "(", "Tc", "/", "myTree", ".", "date2dist", ".", "clock_rate", ")", ")", "print", "(", "\" --N_e: \\t %1.2e \\tcorresponding 'effective population size' assuming 50 gen/year\\n\"", "%", "(", "Tc", "/", "myTree", ".", "date2dist", ".", "clock_rate", "*", "50", ")", ")", "# plot", "import", "matplotlib", ".", "pyplot", "as", "plt", "from", ".", "treetime", "import", "plot_vs_years", "leaf_count", "=", "myTree", ".", "tree", ".", "count_terminals", "(", ")", "label_func", "=", "lambda", "x", ":", "(", "x", ".", "name", "if", "x", ".", "is_terminal", "(", ")", "and", "(", "(", "leaf_count", "<", "30", "and", "(", "not", "params", ".", "no_tip_labels", ")", ")", "or", "params", ".", "tip_labels", ")", "else", "''", ")", "plot_vs_years", "(", "myTree", ",", "show_confidence", "=", "False", ",", "label_func", "=", "label_func", ",", "confidence", "=", "0.9", "if", "params", ".", "confidence", "else", "None", ")", "tree_fname", "=", "(", "outdir", "+", "params", ".", "plot_tree", ")", "plt", ".", "savefig", "(", "tree_fname", ")", "print", "(", "\"--- saved tree as \\n\\t %s\\n\"", "%", "tree_fname", ")", "plot_rtt", "(", "myTree", ",", "outdir", "+", "params", ".", "plot_rtt", ")", "if", "params", ".", "relax", ":", "fname", "=", "outdir", "+", "'substitution_rates.tsv'", "print", "(", "\"--- wrote branch specific rates to\\n\\t %s\\n\"", "%", "fname", ")", "with", "open", "(", "fname", ",", "'w'", ")", "as", "fh", ":", "fh", ".", "write", "(", "\"#node\\tclock_length\\tmutation_length\\trate\\tfold_change\\n\"", ")", "for", "n", "in", "myTree", ".", "tree", ".", "find_clades", "(", "order", "=", "\"preorder\"", ")", ":", "if", "n", "==", "myTree", ".", "tree", ".", "root", ":", "continue", "g", "=", "n", ".", "branch_length_interpolator", ".", "gamma", "fh", ".", "write", "(", "\"%s\\t%1.3e\\t%1.3e\\t%1.3e\\t%1.2f\\n\"", "%", "(", "n", ".", "name", ",", "n", ".", "clock_length", ",", "n", ".", "mutation_length", ",", "myTree", ".", "date2dist", ".", "clock_rate", "*", "g", ",", "g", ")", ")", "export_sequences_and_tree", "(", "myTree", ",", "basename", ",", "is_vcf", ",", "params", ".", "zero_based", ",", "timetree", "=", "True", ",", "confidence", "=", "calc_confidence", ")", "return", "0" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ancestral_reconstruction
implementing treetime ancestral
treetime/wrappers.py
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) ########################################################################### ### READ IN VCF ########################################################################### #sets ref and fixed_pi to None if not VCF aln, ref, fixed_pi = read_if_vcf(params) is_vcf = True if ref is not None else False treeanc = TreeAnc(params.tree, aln=aln, ref=ref, gtr=gtr, verbose=1, fill_overhangs=not params.keep_overhangs) ndiff =treeanc.infer_ancestral_sequences('ml', infer_gtr=params.gtr=='infer', marginal=params.marginal, fixed_pi=fixed_pi) if ndiff==ttconf.ERROR: # if reconstruction failed, exit return 1 ########################################################################### ### OUTPUT and saving of results ########################################################################### if params.gtr=="infer": print('\nInferred GTR model:') print(treeanc.gtr) export_sequences_and_tree(treeanc, basename, is_vcf, params.zero_based, report_ambiguous=params.report_ambiguous) return 0
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) ########################################################################### ### READ IN VCF ########################################################################### #sets ref and fixed_pi to None if not VCF aln, ref, fixed_pi = read_if_vcf(params) is_vcf = True if ref is not None else False treeanc = TreeAnc(params.tree, aln=aln, ref=ref, gtr=gtr, verbose=1, fill_overhangs=not params.keep_overhangs) ndiff =treeanc.infer_ancestral_sequences('ml', infer_gtr=params.gtr=='infer', marginal=params.marginal, fixed_pi=fixed_pi) if ndiff==ttconf.ERROR: # if reconstruction failed, exit return 1 ########################################################################### ### OUTPUT and saving of results ########################################################################### if params.gtr=="infer": print('\nInferred GTR model:') print(treeanc.gtr) export_sequences_and_tree(treeanc, basename, is_vcf, params.zero_based, report_ambiguous=params.report_ambiguous) return 0
[ "implementing", "treetime", "ancestral" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/wrappers.py#L612-L650
[ "def", "ancestral_reconstruction", "(", "params", ")", ":", "# 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", ")", "###########################################################################", "### READ IN VCF", "###########################################################################", "#sets ref and fixed_pi to None if not VCF", "aln", ",", "ref", ",", "fixed_pi", "=", "read_if_vcf", "(", "params", ")", "is_vcf", "=", "True", "if", "ref", "is", "not", "None", "else", "False", "treeanc", "=", "TreeAnc", "(", "params", ".", "tree", ",", "aln", "=", "aln", ",", "ref", "=", "ref", ",", "gtr", "=", "gtr", ",", "verbose", "=", "1", ",", "fill_overhangs", "=", "not", "params", ".", "keep_overhangs", ")", "ndiff", "=", "treeanc", ".", "infer_ancestral_sequences", "(", "'ml'", ",", "infer_gtr", "=", "params", ".", "gtr", "==", "'infer'", ",", "marginal", "=", "params", ".", "marginal", ",", "fixed_pi", "=", "fixed_pi", ")", "if", "ndiff", "==", "ttconf", ".", "ERROR", ":", "# if reconstruction failed, exit", "return", "1", "###########################################################################", "### OUTPUT and saving of results", "###########################################################################", "if", "params", ".", "gtr", "==", "\"infer\"", ":", "print", "(", "'\\nInferred GTR model:'", ")", "print", "(", "treeanc", ".", "gtr", ")", "export_sequences_and_tree", "(", "treeanc", ",", "basename", ",", "is_vcf", ",", "params", ".", "zero_based", ",", "report_ambiguous", "=", "params", ".", "report_ambiguous", ")", "return", "0" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
mugration
implementing treetime mugration
treetime/wrappers.py
def mugration(params): """ implementing treetime mugration """ ########################################################################### ### Parse states ########################################################################### if os.path.isfile(params.states): states = pd.read_csv(params.states, sep='\t' if params.states[-3:]=='tsv' else ',', skipinitialspace=True) else: print("file with states does not exist") return 1 outdir = get_outdir(params, '_mugration') taxon_name = 'name' if 'name' in states.columns else states.columns[0] if params.attribute: if params.attribute in states.columns: attr = params.attribute else: print("The specified attribute was not found in the metadata file "+params.states, file=sys.stderr) print("Available columns are: "+", ".join(states.columns), file=sys.stderr) return 1 else: attr = states.columns[1] print("Attribute for mugration inference was not specified. Using "+attr, file=sys.stderr) leaf_to_attr = {x[taxon_name]:x[attr] for xi, x in states.iterrows() if x[attr]!=params.missing_data} unique_states = sorted(set(leaf_to_attr.values())) nc = len(unique_states) if nc>180: print("mugration: can't have more than 180 states!", file=sys.stderr) return 1 elif nc<2: print("mugration: only one or zero states found -- this doesn't make any sense", file=sys.stderr) return 1 ########################################################################### ### make a single character alphabet that maps to discrete states ########################################################################### alphabet = [chr(65+i) for i,state in enumerate(unique_states)] missing_char = chr(65+nc) letter_to_state = {a:unique_states[i] for i,a in enumerate(alphabet)} letter_to_state[missing_char]=params.missing_data reverse_alphabet = {v:k for k,v in letter_to_state.items()} ########################################################################### ### construct gtr model ########################################################################### if params.weights: params.infer_gtr = True tmp_weights = pd.read_csv(params.weights, sep='\t' if params.states[-3:]=='tsv' else ',', skipinitialspace=True) weights = {row[0]:row[1] for ri,row in tmp_weights.iterrows()} mean_weight = np.mean(list(weights.values())) weights = np.array([weights[c] if c in weights else mean_weight for c in unique_states], dtype=float) weights/=weights.sum() else: weights = np.ones(nc, dtype=float)/nc # set up dummy matrix W = np.ones((nc,nc), dtype=float) mugration_GTR = GTR.custom(pi = weights, W=W, alphabet = np.array(alphabet)) mugration_GTR.profile_map[missing_char] = np.ones(nc) mugration_GTR.ambiguous=missing_char ########################################################################### ### set up treeanc ########################################################################### treeanc = TreeAnc(params.tree, gtr=mugration_GTR, verbose=params.verbose, convert_upper=False, one_mutation=0.001) pseudo_seqs = [SeqRecord(id=n.name,name=n.name, seq=Seq(reverse_alphabet[leaf_to_attr[n.name]] if n.name in leaf_to_attr else missing_char)) for n in treeanc.tree.get_terminals()] treeanc.aln = MultipleSeqAlignment(pseudo_seqs) ndiff = treeanc.infer_ancestral_sequences(method='ml', infer_gtr=True, store_compressed=False, pc=params.pc, marginal=True, normalized_rate=False, fixed_pi=weights if params.weights else None) if ndiff==ttconf.ERROR: # if reconstruction failed, exit return 1 ########################################################################### ### output ########################################################################### print("\nCompleted mugration model inference of attribute '%s' for"%attr,params.tree) basename = get_basename(params, outdir) gtr_name = basename + 'GTR.txt' with open(gtr_name, 'w') as ofile: ofile.write('Character to attribute mapping:\n') for state in unique_states: ofile.write(' %s: %s\n'%(reverse_alphabet[state], state)) ofile.write('\n\n'+str(treeanc.gtr)+'\n') print("\nSaved inferred mugration model as:", gtr_name) terminal_count = 0 for n in treeanc.tree.find_clades(): if n.up is None: continue n.confidence=None # due to a bug in older versions of biopython that truncated filenames in nexus export # we truncate them by hand and make them unique. if n.is_terminal() and len(n.name)>40 and bioversion<"1.69": n.name = n.name[:35]+'_%03d'%terminal_count terminal_count+=1 n.comment= '&%s="'%attr + letter_to_state[n.sequence[0]] +'"' if params.confidence: conf_name = basename+'confidence.csv' with open(conf_name, 'w') as ofile: ofile.write('#name, '+', '.join(unique_states)+'\n') for n in treeanc.tree.find_clades(): ofile.write(n.name + ', '+', '.join([str(x) for x in n.marginal_profile[0]])+'\n') print("Saved table with ancestral state confidences as:", conf_name) # write tree to file outtree_name = basename+'annotated_tree.nexus' Phylo.write(treeanc.tree, outtree_name, 'nexus') print("Saved annotated tree as:",outtree_name) return 0
def mugration(params): """ implementing treetime mugration """ ########################################################################### ### Parse states ########################################################################### if os.path.isfile(params.states): states = pd.read_csv(params.states, sep='\t' if params.states[-3:]=='tsv' else ',', skipinitialspace=True) else: print("file with states does not exist") return 1 outdir = get_outdir(params, '_mugration') taxon_name = 'name' if 'name' in states.columns else states.columns[0] if params.attribute: if params.attribute in states.columns: attr = params.attribute else: print("The specified attribute was not found in the metadata file "+params.states, file=sys.stderr) print("Available columns are: "+", ".join(states.columns), file=sys.stderr) return 1 else: attr = states.columns[1] print("Attribute for mugration inference was not specified. Using "+attr, file=sys.stderr) leaf_to_attr = {x[taxon_name]:x[attr] for xi, x in states.iterrows() if x[attr]!=params.missing_data} unique_states = sorted(set(leaf_to_attr.values())) nc = len(unique_states) if nc>180: print("mugration: can't have more than 180 states!", file=sys.stderr) return 1 elif nc<2: print("mugration: only one or zero states found -- this doesn't make any sense", file=sys.stderr) return 1 ########################################################################### ### make a single character alphabet that maps to discrete states ########################################################################### alphabet = [chr(65+i) for i,state in enumerate(unique_states)] missing_char = chr(65+nc) letter_to_state = {a:unique_states[i] for i,a in enumerate(alphabet)} letter_to_state[missing_char]=params.missing_data reverse_alphabet = {v:k for k,v in letter_to_state.items()} ########################################################################### ### construct gtr model ########################################################################### if params.weights: params.infer_gtr = True tmp_weights = pd.read_csv(params.weights, sep='\t' if params.states[-3:]=='tsv' else ',', skipinitialspace=True) weights = {row[0]:row[1] for ri,row in tmp_weights.iterrows()} mean_weight = np.mean(list(weights.values())) weights = np.array([weights[c] if c in weights else mean_weight for c in unique_states], dtype=float) weights/=weights.sum() else: weights = np.ones(nc, dtype=float)/nc # set up dummy matrix W = np.ones((nc,nc), dtype=float) mugration_GTR = GTR.custom(pi = weights, W=W, alphabet = np.array(alphabet)) mugration_GTR.profile_map[missing_char] = np.ones(nc) mugration_GTR.ambiguous=missing_char ########################################################################### ### set up treeanc ########################################################################### treeanc = TreeAnc(params.tree, gtr=mugration_GTR, verbose=params.verbose, convert_upper=False, one_mutation=0.001) pseudo_seqs = [SeqRecord(id=n.name,name=n.name, seq=Seq(reverse_alphabet[leaf_to_attr[n.name]] if n.name in leaf_to_attr else missing_char)) for n in treeanc.tree.get_terminals()] treeanc.aln = MultipleSeqAlignment(pseudo_seqs) ndiff = treeanc.infer_ancestral_sequences(method='ml', infer_gtr=True, store_compressed=False, pc=params.pc, marginal=True, normalized_rate=False, fixed_pi=weights if params.weights else None) if ndiff==ttconf.ERROR: # if reconstruction failed, exit return 1 ########################################################################### ### output ########################################################################### print("\nCompleted mugration model inference of attribute '%s' for"%attr,params.tree) basename = get_basename(params, outdir) gtr_name = basename + 'GTR.txt' with open(gtr_name, 'w') as ofile: ofile.write('Character to attribute mapping:\n') for state in unique_states: ofile.write(' %s: %s\n'%(reverse_alphabet[state], state)) ofile.write('\n\n'+str(treeanc.gtr)+'\n') print("\nSaved inferred mugration model as:", gtr_name) terminal_count = 0 for n in treeanc.tree.find_clades(): if n.up is None: continue n.confidence=None # due to a bug in older versions of biopython that truncated filenames in nexus export # we truncate them by hand and make them unique. if n.is_terminal() and len(n.name)>40 and bioversion<"1.69": n.name = n.name[:35]+'_%03d'%terminal_count terminal_count+=1 n.comment= '&%s="'%attr + letter_to_state[n.sequence[0]] +'"' if params.confidence: conf_name = basename+'confidence.csv' with open(conf_name, 'w') as ofile: ofile.write('#name, '+', '.join(unique_states)+'\n') for n in treeanc.tree.find_clades(): ofile.write(n.name + ', '+', '.join([str(x) for x in n.marginal_profile[0]])+'\n') print("Saved table with ancestral state confidences as:", conf_name) # write tree to file outtree_name = basename+'annotated_tree.nexus' Phylo.write(treeanc.tree, outtree_name, 'nexus') print("Saved annotated tree as:",outtree_name) return 0
[ "implementing", "treetime", "mugration" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/wrappers.py#L652-L779
[ "def", "mugration", "(", "params", ")", ":", "###########################################################################", "### Parse states", "###########################################################################", "if", "os", ".", "path", ".", "isfile", "(", "params", ".", "states", ")", ":", "states", "=", "pd", ".", "read_csv", "(", "params", ".", "states", ",", "sep", "=", "'\\t'", "if", "params", ".", "states", "[", "-", "3", ":", "]", "==", "'tsv'", "else", "','", ",", "skipinitialspace", "=", "True", ")", "else", ":", "print", "(", "\"file with states does not exist\"", ")", "return", "1", "outdir", "=", "get_outdir", "(", "params", ",", "'_mugration'", ")", "taxon_name", "=", "'name'", "if", "'name'", "in", "states", ".", "columns", "else", "states", ".", "columns", "[", "0", "]", "if", "params", ".", "attribute", ":", "if", "params", ".", "attribute", "in", "states", ".", "columns", ":", "attr", "=", "params", ".", "attribute", "else", ":", "print", "(", "\"The specified attribute was not found in the metadata file \"", "+", "params", ".", "states", ",", "file", "=", "sys", ".", "stderr", ")", "print", "(", "\"Available columns are: \"", "+", "\", \"", ".", "join", "(", "states", ".", "columns", ")", ",", "file", "=", "sys", ".", "stderr", ")", "return", "1", "else", ":", "attr", "=", "states", ".", "columns", "[", "1", "]", "print", "(", "\"Attribute for mugration inference was not specified. Using \"", "+", "attr", ",", "file", "=", "sys", ".", "stderr", ")", "leaf_to_attr", "=", "{", "x", "[", "taxon_name", "]", ":", "x", "[", "attr", "]", "for", "xi", ",", "x", "in", "states", ".", "iterrows", "(", ")", "if", "x", "[", "attr", "]", "!=", "params", ".", "missing_data", "}", "unique_states", "=", "sorted", "(", "set", "(", "leaf_to_attr", ".", "values", "(", ")", ")", ")", "nc", "=", "len", "(", "unique_states", ")", "if", "nc", ">", "180", ":", "print", "(", "\"mugration: can't have more than 180 states!\"", ",", "file", "=", "sys", ".", "stderr", ")", "return", "1", "elif", "nc", "<", "2", ":", "print", "(", "\"mugration: only one or zero states found -- this doesn't make any sense\"", ",", "file", "=", "sys", ".", "stderr", ")", "return", "1", "###########################################################################", "### make a single character alphabet that maps to discrete states", "###########################################################################", "alphabet", "=", "[", "chr", "(", "65", "+", "i", ")", "for", "i", ",", "state", "in", "enumerate", "(", "unique_states", ")", "]", "missing_char", "=", "chr", "(", "65", "+", "nc", ")", "letter_to_state", "=", "{", "a", ":", "unique_states", "[", "i", "]", "for", "i", ",", "a", "in", "enumerate", "(", "alphabet", ")", "}", "letter_to_state", "[", "missing_char", "]", "=", "params", ".", "missing_data", "reverse_alphabet", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "letter_to_state", ".", "items", "(", ")", "}", "###########################################################################", "### construct gtr model", "###########################################################################", "if", "params", ".", "weights", ":", "params", ".", "infer_gtr", "=", "True", "tmp_weights", "=", "pd", ".", "read_csv", "(", "params", ".", "weights", ",", "sep", "=", "'\\t'", "if", "params", ".", "states", "[", "-", "3", ":", "]", "==", "'tsv'", "else", "','", ",", "skipinitialspace", "=", "True", ")", "weights", "=", "{", "row", "[", "0", "]", ":", "row", "[", "1", "]", "for", "ri", ",", "row", "in", "tmp_weights", ".", "iterrows", "(", ")", "}", "mean_weight", "=", "np", ".", "mean", "(", "list", "(", "weights", ".", "values", "(", ")", ")", ")", "weights", "=", "np", ".", "array", "(", "[", "weights", "[", "c", "]", "if", "c", "in", "weights", "else", "mean_weight", "for", "c", "in", "unique_states", "]", ",", "dtype", "=", "float", ")", "weights", "/=", "weights", ".", "sum", "(", ")", "else", ":", "weights", "=", "np", ".", "ones", "(", "nc", ",", "dtype", "=", "float", ")", "/", "nc", "# set up dummy matrix", "W", "=", "np", ".", "ones", "(", "(", "nc", ",", "nc", ")", ",", "dtype", "=", "float", ")", "mugration_GTR", "=", "GTR", ".", "custom", "(", "pi", "=", "weights", ",", "W", "=", "W", ",", "alphabet", "=", "np", ".", "array", "(", "alphabet", ")", ")", "mugration_GTR", ".", "profile_map", "[", "missing_char", "]", "=", "np", ".", "ones", "(", "nc", ")", "mugration_GTR", ".", "ambiguous", "=", "missing_char", "###########################################################################", "### set up treeanc", "###########################################################################", "treeanc", "=", "TreeAnc", "(", "params", ".", "tree", ",", "gtr", "=", "mugration_GTR", ",", "verbose", "=", "params", ".", "verbose", ",", "convert_upper", "=", "False", ",", "one_mutation", "=", "0.001", ")", "pseudo_seqs", "=", "[", "SeqRecord", "(", "id", "=", "n", ".", "name", ",", "name", "=", "n", ".", "name", ",", "seq", "=", "Seq", "(", "reverse_alphabet", "[", "leaf_to_attr", "[", "n", ".", "name", "]", "]", "if", "n", ".", "name", "in", "leaf_to_attr", "else", "missing_char", ")", ")", "for", "n", "in", "treeanc", ".", "tree", ".", "get_terminals", "(", ")", "]", "treeanc", ".", "aln", "=", "MultipleSeqAlignment", "(", "pseudo_seqs", ")", "ndiff", "=", "treeanc", ".", "infer_ancestral_sequences", "(", "method", "=", "'ml'", ",", "infer_gtr", "=", "True", ",", "store_compressed", "=", "False", ",", "pc", "=", "params", ".", "pc", ",", "marginal", "=", "True", ",", "normalized_rate", "=", "False", ",", "fixed_pi", "=", "weights", "if", "params", ".", "weights", "else", "None", ")", "if", "ndiff", "==", "ttconf", ".", "ERROR", ":", "# if reconstruction failed, exit", "return", "1", "###########################################################################", "### output", "###########################################################################", "print", "(", "\"\\nCompleted mugration model inference of attribute '%s' for\"", "%", "attr", ",", "params", ".", "tree", ")", "basename", "=", "get_basename", "(", "params", ",", "outdir", ")", "gtr_name", "=", "basename", "+", "'GTR.txt'", "with", "open", "(", "gtr_name", ",", "'w'", ")", "as", "ofile", ":", "ofile", ".", "write", "(", "'Character to attribute mapping:\\n'", ")", "for", "state", "in", "unique_states", ":", "ofile", ".", "write", "(", "' %s: %s\\n'", "%", "(", "reverse_alphabet", "[", "state", "]", ",", "state", ")", ")", "ofile", ".", "write", "(", "'\\n\\n'", "+", "str", "(", "treeanc", ".", "gtr", ")", "+", "'\\n'", ")", "print", "(", "\"\\nSaved inferred mugration model as:\"", ",", "gtr_name", ")", "terminal_count", "=", "0", "for", "n", "in", "treeanc", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "n", ".", "up", "is", "None", ":", "continue", "n", ".", "confidence", "=", "None", "# due to a bug in older versions of biopython that truncated filenames in nexus export", "# we truncate them by hand and make them unique.", "if", "n", ".", "is_terminal", "(", ")", "and", "len", "(", "n", ".", "name", ")", ">", "40", "and", "bioversion", "<", "\"1.69\"", ":", "n", ".", "name", "=", "n", ".", "name", "[", ":", "35", "]", "+", "'_%03d'", "%", "terminal_count", "terminal_count", "+=", "1", "n", ".", "comment", "=", "'&%s=\"'", "%", "attr", "+", "letter_to_state", "[", "n", ".", "sequence", "[", "0", "]", "]", "+", "'\"'", "if", "params", ".", "confidence", ":", "conf_name", "=", "basename", "+", "'confidence.csv'", "with", "open", "(", "conf_name", ",", "'w'", ")", "as", "ofile", ":", "ofile", ".", "write", "(", "'#name, '", "+", "', '", ".", "join", "(", "unique_states", ")", "+", "'\\n'", ")", "for", "n", "in", "treeanc", ".", "tree", ".", "find_clades", "(", ")", ":", "ofile", ".", "write", "(", "n", ".", "name", "+", "', '", "+", "', '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "n", ".", "marginal_profile", "[", "0", "]", "]", ")", "+", "'\\n'", ")", "print", "(", "\"Saved table with ancestral state confidences as:\"", ",", "conf_name", ")", "# write tree to file", "outtree_name", "=", "basename", "+", "'annotated_tree.nexus'", "Phylo", ".", "write", "(", "treeanc", ".", "tree", ",", "outtree_name", ",", "'nexus'", ")", "print", "(", "\"Saved annotated tree as:\"", ",", "outtree_name", ")", "return", "0" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
estimate_clock_model
implementing treetime clock
treetime/wrappers.py
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') ########################################################################### ### READ IN VCF ########################################################################### #sets ref and fixed_pi to None if not VCF aln, ref, fixed_pi = read_if_vcf(params) is_vcf = True if ref is not None else False ########################################################################### ### ESTIMATE ROOT (if requested) AND DETERMINE TEMPORAL SIGNAL ########################################################################### if params.aln is None and params.sequence_length is None: print("one of arguments '--aln' and '--sequence-length' is required.", file=sys.stderr) return 1 basename = get_basename(params, outdir) myTree = TreeTime(dates=dates, tree=params.tree, aln=aln, gtr='JC69', verbose=params.verbose, seq_len=params.sequence_length, ref=ref) myTree.tip_slack=params.tip_slack if myTree.tree is None: print("ERROR: tree loading failed. exiting...") return 1 if params.clock_filter: n_bad = [n.name for n in myTree.tree.get_terminals() if n.bad_branch] myTree.clock_filter(n_iqd=params.clock_filter, reroot=params.reroot or 'least-squares') n_bad_after = [n.name for n in myTree.tree.get_terminals() if n.bad_branch] if len(n_bad_after)>len(n_bad): print("The following leaves don't follow a loose clock and " "will be ignored in rate estimation:\n\t" +"\n\t".join(set(n_bad_after).difference(n_bad))) if not params.keep_root: # reroot to optimal root, this assigns clock_model to myTree if params.covariation: # this requires branch length estimates myTree.run(root="least-squares", max_iter=0, use_covariation=params.covariation) res = myTree.reroot(params.reroot, force_positive=not params.allow_negative_rate) myTree.get_clock_model(covariation=params.covariation) if res==ttconf.ERROR: print("ERROR: unknown root or rooting mechanism!\n" "\tvalid choices are 'least-squares', 'ML', and 'ML-rough'") return 1 else: myTree.get_clock_model(covariation=params.covariation) d2d = utils.DateConversion.from_regression(myTree.clock_model) print('\n',d2d) print('The R^2 value indicates the fraction of variation in' '\nroot-to-tip distance explained by the sampling times.' '\nHigher values corresponds more clock-like behavior (max 1.0).') print('\nThe rate is the slope of the best fit of the date to' '\nthe root-to-tip distance and provides an estimate of' '\nthe substitution rate. The rate needs to be positive!' '\nNegative rates suggest an inappropriate root.\n') print('\nThe estimated rate and tree correspond to a root date:') if params.covariation: reg = myTree.clock_model dp = np.array([reg['intercept']/reg['slope']**2,-1./reg['slope']]) droot = np.sqrt(reg['cov'][:2,:2].dot(dp).dot(dp)) print('\n--- root-date:\t %3.2f +/- %1.2f (one std-dev)\n\n'%(-d2d.intercept/d2d.clock_rate, droot)) else: print('\n--- root-date:\t %3.2f\n\n'%(-d2d.intercept/d2d.clock_rate)) if not params.keep_root: # write rerooted tree to file outtree_name = basename+'rerooted.newick' Phylo.write(myTree.tree, outtree_name, 'newick') print("--- re-rooted tree written to \n\t%s\n"%outtree_name) table_fname = basename+'rtt.csv' with open(table_fname, 'w') as ofile: ofile.write("#name, date, root-to-tip distance\n") ofile.write("#Dates of nodes that didn't have a specified date are inferred from the root-to-tip regression.\n") for n in myTree.tree.get_terminals(): if hasattr(n, "raw_date_constraint") and (n.raw_date_constraint is not None): if np.isscalar(n.raw_date_constraint): tmp_str = str(n.raw_date_constraint) elif len(n.raw_date_constraint): tmp_str = str(n.raw_date_constraint[0])+'-'+str(n.raw_date_constraint[1]) else: tmp_str = '' ofile.write("%s, %s, %f\n"%(n.name, tmp_str, n.dist2root)) else: ofile.write("%s, %f, %f\n"%(n.name, d2d.numdate_from_dist2root(n.dist2root), n.dist2root)) for n in myTree.tree.get_nonterminals(order='preorder'): ofile.write("%s, %f, %f\n"%(n.name, d2d.numdate_from_dist2root(n.dist2root), n.dist2root)) print("--- wrote dates and root-to-tip distances to \n\t%s\n"%table_fname) ########################################################################### ### PLOT AND SAVE RESULT ########################################################################### plot_rtt(myTree, outdir+params.plot_rtt) return 0
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') ########################################################################### ### READ IN VCF ########################################################################### #sets ref and fixed_pi to None if not VCF aln, ref, fixed_pi = read_if_vcf(params) is_vcf = True if ref is not None else False ########################################################################### ### ESTIMATE ROOT (if requested) AND DETERMINE TEMPORAL SIGNAL ########################################################################### if params.aln is None and params.sequence_length is None: print("one of arguments '--aln' and '--sequence-length' is required.", file=sys.stderr) return 1 basename = get_basename(params, outdir) myTree = TreeTime(dates=dates, tree=params.tree, aln=aln, gtr='JC69', verbose=params.verbose, seq_len=params.sequence_length, ref=ref) myTree.tip_slack=params.tip_slack if myTree.tree is None: print("ERROR: tree loading failed. exiting...") return 1 if params.clock_filter: n_bad = [n.name for n in myTree.tree.get_terminals() if n.bad_branch] myTree.clock_filter(n_iqd=params.clock_filter, reroot=params.reroot or 'least-squares') n_bad_after = [n.name for n in myTree.tree.get_terminals() if n.bad_branch] if len(n_bad_after)>len(n_bad): print("The following leaves don't follow a loose clock and " "will be ignored in rate estimation:\n\t" +"\n\t".join(set(n_bad_after).difference(n_bad))) if not params.keep_root: # reroot to optimal root, this assigns clock_model to myTree if params.covariation: # this requires branch length estimates myTree.run(root="least-squares", max_iter=0, use_covariation=params.covariation) res = myTree.reroot(params.reroot, force_positive=not params.allow_negative_rate) myTree.get_clock_model(covariation=params.covariation) if res==ttconf.ERROR: print("ERROR: unknown root or rooting mechanism!\n" "\tvalid choices are 'least-squares', 'ML', and 'ML-rough'") return 1 else: myTree.get_clock_model(covariation=params.covariation) d2d = utils.DateConversion.from_regression(myTree.clock_model) print('\n',d2d) print('The R^2 value indicates the fraction of variation in' '\nroot-to-tip distance explained by the sampling times.' '\nHigher values corresponds more clock-like behavior (max 1.0).') print('\nThe rate is the slope of the best fit of the date to' '\nthe root-to-tip distance and provides an estimate of' '\nthe substitution rate. The rate needs to be positive!' '\nNegative rates suggest an inappropriate root.\n') print('\nThe estimated rate and tree correspond to a root date:') if params.covariation: reg = myTree.clock_model dp = np.array([reg['intercept']/reg['slope']**2,-1./reg['slope']]) droot = np.sqrt(reg['cov'][:2,:2].dot(dp).dot(dp)) print('\n--- root-date:\t %3.2f +/- %1.2f (one std-dev)\n\n'%(-d2d.intercept/d2d.clock_rate, droot)) else: print('\n--- root-date:\t %3.2f\n\n'%(-d2d.intercept/d2d.clock_rate)) if not params.keep_root: # write rerooted tree to file outtree_name = basename+'rerooted.newick' Phylo.write(myTree.tree, outtree_name, 'newick') print("--- re-rooted tree written to \n\t%s\n"%outtree_name) table_fname = basename+'rtt.csv' with open(table_fname, 'w') as ofile: ofile.write("#name, date, root-to-tip distance\n") ofile.write("#Dates of nodes that didn't have a specified date are inferred from the root-to-tip regression.\n") for n in myTree.tree.get_terminals(): if hasattr(n, "raw_date_constraint") and (n.raw_date_constraint is not None): if np.isscalar(n.raw_date_constraint): tmp_str = str(n.raw_date_constraint) elif len(n.raw_date_constraint): tmp_str = str(n.raw_date_constraint[0])+'-'+str(n.raw_date_constraint[1]) else: tmp_str = '' ofile.write("%s, %s, %f\n"%(n.name, tmp_str, n.dist2root)) else: ofile.write("%s, %f, %f\n"%(n.name, d2d.numdate_from_dist2root(n.dist2root), n.dist2root)) for n in myTree.tree.get_nonterminals(order='preorder'): ofile.write("%s, %f, %f\n"%(n.name, d2d.numdate_from_dist2root(n.dist2root), n.dist2root)) print("--- wrote dates and root-to-tip distances to \n\t%s\n"%table_fname) ########################################################################### ### PLOT AND SAVE RESULT ########################################################################### plot_rtt(myTree, outdir+params.plot_rtt) return 0
[ "implementing", "treetime", "clock" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/wrappers.py#L782-L894
[ "def", "estimate_clock_model", "(", "params", ")", ":", "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'", ")", "###########################################################################", "### READ IN VCF", "###########################################################################", "#sets ref and fixed_pi to None if not VCF", "aln", ",", "ref", ",", "fixed_pi", "=", "read_if_vcf", "(", "params", ")", "is_vcf", "=", "True", "if", "ref", "is", "not", "None", "else", "False", "###########################################################################", "### ESTIMATE ROOT (if requested) AND DETERMINE TEMPORAL SIGNAL", "###########################################################################", "if", "params", ".", "aln", "is", "None", "and", "params", ".", "sequence_length", "is", "None", ":", "print", "(", "\"one of arguments '--aln' and '--sequence-length' is required.\"", ",", "file", "=", "sys", ".", "stderr", ")", "return", "1", "basename", "=", "get_basename", "(", "params", ",", "outdir", ")", "myTree", "=", "TreeTime", "(", "dates", "=", "dates", ",", "tree", "=", "params", ".", "tree", ",", "aln", "=", "aln", ",", "gtr", "=", "'JC69'", ",", "verbose", "=", "params", ".", "verbose", ",", "seq_len", "=", "params", ".", "sequence_length", ",", "ref", "=", "ref", ")", "myTree", ".", "tip_slack", "=", "params", ".", "tip_slack", "if", "myTree", ".", "tree", "is", "None", ":", "print", "(", "\"ERROR: tree loading failed. exiting...\"", ")", "return", "1", "if", "params", ".", "clock_filter", ":", "n_bad", "=", "[", "n", ".", "name", "for", "n", "in", "myTree", ".", "tree", ".", "get_terminals", "(", ")", "if", "n", ".", "bad_branch", "]", "myTree", ".", "clock_filter", "(", "n_iqd", "=", "params", ".", "clock_filter", ",", "reroot", "=", "params", ".", "reroot", "or", "'least-squares'", ")", "n_bad_after", "=", "[", "n", ".", "name", "for", "n", "in", "myTree", ".", "tree", ".", "get_terminals", "(", ")", "if", "n", ".", "bad_branch", "]", "if", "len", "(", "n_bad_after", ")", ">", "len", "(", "n_bad", ")", ":", "print", "(", "\"The following leaves don't follow a loose clock and \"", "\"will be ignored in rate estimation:\\n\\t\"", "+", "\"\\n\\t\"", ".", "join", "(", "set", "(", "n_bad_after", ")", ".", "difference", "(", "n_bad", ")", ")", ")", "if", "not", "params", ".", "keep_root", ":", "# reroot to optimal root, this assigns clock_model to myTree", "if", "params", ".", "covariation", ":", "# this requires branch length estimates", "myTree", ".", "run", "(", "root", "=", "\"least-squares\"", ",", "max_iter", "=", "0", ",", "use_covariation", "=", "params", ".", "covariation", ")", "res", "=", "myTree", ".", "reroot", "(", "params", ".", "reroot", ",", "force_positive", "=", "not", "params", ".", "allow_negative_rate", ")", "myTree", ".", "get_clock_model", "(", "covariation", "=", "params", ".", "covariation", ")", "if", "res", "==", "ttconf", ".", "ERROR", ":", "print", "(", "\"ERROR: unknown root or rooting mechanism!\\n\"", "\"\\tvalid choices are 'least-squares', 'ML', and 'ML-rough'\"", ")", "return", "1", "else", ":", "myTree", ".", "get_clock_model", "(", "covariation", "=", "params", ".", "covariation", ")", "d2d", "=", "utils", ".", "DateConversion", ".", "from_regression", "(", "myTree", ".", "clock_model", ")", "print", "(", "'\\n'", ",", "d2d", ")", "print", "(", "'The R^2 value indicates the fraction of variation in'", "'\\nroot-to-tip distance explained by the sampling times.'", "'\\nHigher values corresponds more clock-like behavior (max 1.0).'", ")", "print", "(", "'\\nThe rate is the slope of the best fit of the date to'", "'\\nthe root-to-tip distance and provides an estimate of'", "'\\nthe substitution rate. The rate needs to be positive!'", "'\\nNegative rates suggest an inappropriate root.\\n'", ")", "print", "(", "'\\nThe estimated rate and tree correspond to a root date:'", ")", "if", "params", ".", "covariation", ":", "reg", "=", "myTree", ".", "clock_model", "dp", "=", "np", ".", "array", "(", "[", "reg", "[", "'intercept'", "]", "/", "reg", "[", "'slope'", "]", "**", "2", ",", "-", "1.", "/", "reg", "[", "'slope'", "]", "]", ")", "droot", "=", "np", ".", "sqrt", "(", "reg", "[", "'cov'", "]", "[", ":", "2", ",", ":", "2", "]", ".", "dot", "(", "dp", ")", ".", "dot", "(", "dp", ")", ")", "print", "(", "'\\n--- root-date:\\t %3.2f +/- %1.2f (one std-dev)\\n\\n'", "%", "(", "-", "d2d", ".", "intercept", "/", "d2d", ".", "clock_rate", ",", "droot", ")", ")", "else", ":", "print", "(", "'\\n--- root-date:\\t %3.2f\\n\\n'", "%", "(", "-", "d2d", ".", "intercept", "/", "d2d", ".", "clock_rate", ")", ")", "if", "not", "params", ".", "keep_root", ":", "# write rerooted tree to file", "outtree_name", "=", "basename", "+", "'rerooted.newick'", "Phylo", ".", "write", "(", "myTree", ".", "tree", ",", "outtree_name", ",", "'newick'", ")", "print", "(", "\"--- re-rooted tree written to \\n\\t%s\\n\"", "%", "outtree_name", ")", "table_fname", "=", "basename", "+", "'rtt.csv'", "with", "open", "(", "table_fname", ",", "'w'", ")", "as", "ofile", ":", "ofile", ".", "write", "(", "\"#name, date, root-to-tip distance\\n\"", ")", "ofile", ".", "write", "(", "\"#Dates of nodes that didn't have a specified date are inferred from the root-to-tip regression.\\n\"", ")", "for", "n", "in", "myTree", ".", "tree", ".", "get_terminals", "(", ")", ":", "if", "hasattr", "(", "n", ",", "\"raw_date_constraint\"", ")", "and", "(", "n", ".", "raw_date_constraint", "is", "not", "None", ")", ":", "if", "np", ".", "isscalar", "(", "n", ".", "raw_date_constraint", ")", ":", "tmp_str", "=", "str", "(", "n", ".", "raw_date_constraint", ")", "elif", "len", "(", "n", ".", "raw_date_constraint", ")", ":", "tmp_str", "=", "str", "(", "n", ".", "raw_date_constraint", "[", "0", "]", ")", "+", "'-'", "+", "str", "(", "n", ".", "raw_date_constraint", "[", "1", "]", ")", "else", ":", "tmp_str", "=", "''", "ofile", ".", "write", "(", "\"%s, %s, %f\\n\"", "%", "(", "n", ".", "name", ",", "tmp_str", ",", "n", ".", "dist2root", ")", ")", "else", ":", "ofile", ".", "write", "(", "\"%s, %f, %f\\n\"", "%", "(", "n", ".", "name", ",", "d2d", ".", "numdate_from_dist2root", "(", "n", ".", "dist2root", ")", ",", "n", ".", "dist2root", ")", ")", "for", "n", "in", "myTree", ".", "tree", ".", "get_nonterminals", "(", "order", "=", "'preorder'", ")", ":", "ofile", ".", "write", "(", "\"%s, %f, %f\\n\"", "%", "(", "n", ".", "name", ",", "d2d", ".", "numdate_from_dist2root", "(", "n", ".", "dist2root", ")", ",", "n", ".", "dist2root", ")", ")", "print", "(", "\"--- wrote dates and root-to-tip distances to \\n\\t%s\\n\"", "%", "table_fname", ")", "###########################################################################", "### PLOT AND SAVE RESULT", "###########################################################################", "plot_rtt", "(", "myTree", ",", "outdir", "+", "params", ".", "plot_rtt", ")", "return", "0" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
Distribution.calc_fwhm
Assess the width of the probability distribution. This returns full-width-half-max
treetime/distribution.py
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 = distribution.y-ymin else: log_prob = -np.log(distribution.y) log_prob -= log_prob.min() xvals = distribution.x elif isinstance(distribution, Distribution): # Distribution always stores neg log-prob with the peak value subtracted xvals = distribution._func.x log_prob = distribution._func.y else: raise TypeError("Error in computing the FWHM for the distribution. " " The input should be either Distribution or interpolation object"); L = xvals.shape[0] # 0.69... is log(2), there is always one value for which this is true since # the minimum is subtracted tmp = np.where(log_prob < 0.693147)[0] x_l, x_u = tmp[0], tmp[-1] if L < 2: print ("Not enough points to compute FWHM: returning zero") return min(TINY_NUMBER, distribution.xmax - distribution.xmin) else: # need to guard against out-of-bounds errors return max(TINY_NUMBER, xvals[min(x_u+1,L-1)] - xvals[max(0,x_l-1)])
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 = distribution.y-ymin else: log_prob = -np.log(distribution.y) log_prob -= log_prob.min() xvals = distribution.x elif isinstance(distribution, Distribution): # Distribution always stores neg log-prob with the peak value subtracted xvals = distribution._func.x log_prob = distribution._func.y else: raise TypeError("Error in computing the FWHM for the distribution. " " The input should be either Distribution or interpolation object"); L = xvals.shape[0] # 0.69... is log(2), there is always one value for which this is true since # the minimum is subtracted tmp = np.where(log_prob < 0.693147)[0] x_l, x_u = tmp[0], tmp[-1] if L < 2: print ("Not enough points to compute FWHM: returning zero") return min(TINY_NUMBER, distribution.xmax - distribution.xmin) else: # need to guard against out-of-bounds errors return max(TINY_NUMBER, xvals[min(x_u+1,L-1)] - xvals[max(0,x_l-1)])
[ "Assess", "the", "width", "of", "the", "probability", "distribution", ".", "This", "returns", "full", "-", "width", "-", "half", "-", "max" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/distribution.py#L20-L55
[ "def", "calc_fwhm", "(", "distribution", ",", "is_neg_log", "=", "True", ")", ":", "if", "isinstance", "(", "distribution", ",", "interp1d", ")", ":", "if", "is_neg_log", ":", "ymin", "=", "distribution", ".", "y", ".", "min", "(", ")", "log_prob", "=", "distribution", ".", "y", "-", "ymin", "else", ":", "log_prob", "=", "-", "np", ".", "log", "(", "distribution", ".", "y", ")", "log_prob", "-=", "log_prob", ".", "min", "(", ")", "xvals", "=", "distribution", ".", "x", "elif", "isinstance", "(", "distribution", ",", "Distribution", ")", ":", "# Distribution always stores neg log-prob with the peak value subtracted", "xvals", "=", "distribution", ".", "_func", ".", "x", "log_prob", "=", "distribution", ".", "_func", ".", "y", "else", ":", "raise", "TypeError", "(", "\"Error in computing the FWHM for the distribution. \"", "\" The input should be either Distribution or interpolation object\"", ")", "L", "=", "xvals", ".", "shape", "[", "0", "]", "# 0.69... is log(2), there is always one value for which this is true since", "# the minimum is subtracted", "tmp", "=", "np", ".", "where", "(", "log_prob", "<", "0.693147", ")", "[", "0", "]", "x_l", ",", "x_u", "=", "tmp", "[", "0", "]", ",", "tmp", "[", "-", "1", "]", "if", "L", "<", "2", ":", "print", "(", "\"Not enough points to compute FWHM: returning zero\"", ")", "return", "min", "(", "TINY_NUMBER", ",", "distribution", ".", "xmax", "-", "distribution", ".", "xmin", ")", "else", ":", "# need to guard against out-of-bounds errors", "return", "max", "(", "TINY_NUMBER", ",", "xvals", "[", "min", "(", "x_u", "+", "1", ",", "L", "-", "1", ")", "]", "-", "xvals", "[", "max", "(", "0", ",", "x_l", "-", "1", ")", "]", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
Distribution.delta_function
Create delta function distribution.
treetime/distribution.py
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
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
[ "Create", "delta", "function", "distribution", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/distribution.py#L59-L66
[ "def", "delta_function", "(", "cls", ",", "x_pos", ",", "weight", "=", "1.", ",", "min_width", "=", "MIN_INTEGRATION_PEAK", ")", ":", "distribution", "=", "cls", "(", "x_pos", ",", "0.", ",", "is_log", "=", "True", ",", "min_width", "=", "min_width", ")", "distribution", ".", "weight", "=", "weight", "return", "distribution" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
Distribution.multiply
multiplies a list of Distribution objects
treetime/distribution.py
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.max([k.min_width for k in dists]) if n_delta>1: raise ArithmeticError("Cannot multiply more than one delta functions!") elif n_delta==1: delta_dist_ii = np.where([k.is_delta for k in dists])[0][0] delta_dist = dists[delta_dist_ii] new_xpos = delta_dist.peak_pos new_weight = np.prod([k.prob(new_xpos) for k in dists if k!=delta_dist_ii]) * delta_dist.weight res = Distribution.delta_function(new_xpos, weight = new_weight,min_width=min_width) else: new_xmin = np.max([k.xmin for k in dists]) new_xmax = np.min([k.xmax for k in dists]) x_vals = np.unique(np.concatenate([k.x for k in dists])) x_vals = x_vals[(x_vals>new_xmin-TINY_NUMBER)&(x_vals<new_xmax+TINY_NUMBER)] y_vals = np.sum([k.__call__(x_vals) for k in dists], axis=0) peak = y_vals.min() ind = (y_vals-peak)<BIG_NUMBER/1000 n_points = ind.sum() if n_points == 0: print ("ERROR in distribution multiplication: Distributions do not overlap") x_vals = [0,1] y_vals = [BIG_NUMBER,BIG_NUMBER] res = Distribution(x_vals, y_vals, is_log=True, min_width=min_width, kind='linear') elif n_points == 1: res = Distribution.delta_function(x_vals[0]) else: res = Distribution(x_vals[ind], y_vals[ind], is_log=True, min_width=min_width, kind='linear', assume_sorted=True) return res
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.max([k.min_width for k in dists]) if n_delta>1: raise ArithmeticError("Cannot multiply more than one delta functions!") elif n_delta==1: delta_dist_ii = np.where([k.is_delta for k in dists])[0][0] delta_dist = dists[delta_dist_ii] new_xpos = delta_dist.peak_pos new_weight = np.prod([k.prob(new_xpos) for k in dists if k!=delta_dist_ii]) * delta_dist.weight res = Distribution.delta_function(new_xpos, weight = new_weight,min_width=min_width) else: new_xmin = np.max([k.xmin for k in dists]) new_xmax = np.min([k.xmax for k in dists]) x_vals = np.unique(np.concatenate([k.x for k in dists])) x_vals = x_vals[(x_vals>new_xmin-TINY_NUMBER)&(x_vals<new_xmax+TINY_NUMBER)] y_vals = np.sum([k.__call__(x_vals) for k in dists], axis=0) peak = y_vals.min() ind = (y_vals-peak)<BIG_NUMBER/1000 n_points = ind.sum() if n_points == 0: print ("ERROR in distribution multiplication: Distributions do not overlap") x_vals = [0,1] y_vals = [BIG_NUMBER,BIG_NUMBER] res = Distribution(x_vals, y_vals, is_log=True, min_width=min_width, kind='linear') elif n_points == 1: res = Distribution.delta_function(x_vals[0]) else: res = Distribution(x_vals[ind], y_vals[ind], is_log=True, min_width=min_width, kind='linear', assume_sorted=True) return res
[ "multiplies", "a", "list", "of", "Distribution", "objects" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/distribution.py#L75-L114
[ "def", "multiply", "(", "dists", ")", ":", "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", ".", "max", "(", "[", "k", ".", "min_width", "for", "k", "in", "dists", "]", ")", "if", "n_delta", ">", "1", ":", "raise", "ArithmeticError", "(", "\"Cannot multiply more than one delta functions!\"", ")", "elif", "n_delta", "==", "1", ":", "delta_dist_ii", "=", "np", ".", "where", "(", "[", "k", ".", "is_delta", "for", "k", "in", "dists", "]", ")", "[", "0", "]", "[", "0", "]", "delta_dist", "=", "dists", "[", "delta_dist_ii", "]", "new_xpos", "=", "delta_dist", ".", "peak_pos", "new_weight", "=", "np", ".", "prod", "(", "[", "k", ".", "prob", "(", "new_xpos", ")", "for", "k", "in", "dists", "if", "k", "!=", "delta_dist_ii", "]", ")", "*", "delta_dist", ".", "weight", "res", "=", "Distribution", ".", "delta_function", "(", "new_xpos", ",", "weight", "=", "new_weight", ",", "min_width", "=", "min_width", ")", "else", ":", "new_xmin", "=", "np", ".", "max", "(", "[", "k", ".", "xmin", "for", "k", "in", "dists", "]", ")", "new_xmax", "=", "np", ".", "min", "(", "[", "k", ".", "xmax", "for", "k", "in", "dists", "]", ")", "x_vals", "=", "np", ".", "unique", "(", "np", ".", "concatenate", "(", "[", "k", ".", "x", "for", "k", "in", "dists", "]", ")", ")", "x_vals", "=", "x_vals", "[", "(", "x_vals", ">", "new_xmin", "-", "TINY_NUMBER", ")", "&", "(", "x_vals", "<", "new_xmax", "+", "TINY_NUMBER", ")", "]", "y_vals", "=", "np", ".", "sum", "(", "[", "k", ".", "__call__", "(", "x_vals", ")", "for", "k", "in", "dists", "]", ",", "axis", "=", "0", ")", "peak", "=", "y_vals", ".", "min", "(", ")", "ind", "=", "(", "y_vals", "-", "peak", ")", "<", "BIG_NUMBER", "/", "1000", "n_points", "=", "ind", ".", "sum", "(", ")", "if", "n_points", "==", "0", ":", "print", "(", "\"ERROR in distribution multiplication: Distributions do not overlap\"", ")", "x_vals", "=", "[", "0", ",", "1", "]", "y_vals", "=", "[", "BIG_NUMBER", ",", "BIG_NUMBER", "]", "res", "=", "Distribution", "(", "x_vals", ",", "y_vals", ",", "is_log", "=", "True", ",", "min_width", "=", "min_width", ",", "kind", "=", "'linear'", ")", "elif", "n_points", "==", "1", ":", "res", "=", "Distribution", ".", "delta_function", "(", "x_vals", "[", "0", "]", ")", "else", ":", "res", "=", "Distribution", "(", "x_vals", "[", "ind", "]", ",", "y_vals", "[", "ind", "]", ",", "is_log", "=", "True", ",", "min_width", "=", "min_width", ",", "kind", "=", "'linear'", ",", "assume_sorted", "=", "True", ")", "return", "res" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree._assign_dates
assign dates to nodes Returns ------- str success/error code
treetime/clock_tree.py
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_counter = 0 for node in self.tree.find_clades(order='postorder'): if node.name in self.date_dict: tmp_date = self.date_dict[node.name] if np.isscalar(tmp_date) and np.isnan(tmp_date): self.logger("WARNING: ClockTree.init: node %s has a bad date: %s"%(node.name, str(tmp_date)), 2, warn=True) node.raw_date_constraint = None node.bad_branch = True else: try: tmp = np.mean(tmp_date) node.raw_date_constraint = tmp_date node.bad_branch = False except: self.logger("WARNING: ClockTree.init: node %s has a bad date: %s"%(node.name, str(tmp_date)), 2, warn=True) node.raw_date_constraint = None node.bad_branch = True else: # nodes without date contraints node.raw_date_constraint = None if node.is_terminal(): # Terminal branches without date constraints marked as 'bad' node.bad_branch = True else: # If all branches dowstream are 'bad', and there is no date constraint for # this node, the branch is marked as 'bad' node.bad_branch = np.all([x.bad_branch for x in node]) if node.is_terminal() and node.bad_branch: bad_branch_counter += 1 if bad_branch_counter>self.tree.count_terminals()-3: self.logger("ERROR: ALMOST NO VALID DATE CONSTRAINTS, EXITING", 1, warn=True) return ttconf.ERROR return ttconf.SUCCESS
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_counter = 0 for node in self.tree.find_clades(order='postorder'): if node.name in self.date_dict: tmp_date = self.date_dict[node.name] if np.isscalar(tmp_date) and np.isnan(tmp_date): self.logger("WARNING: ClockTree.init: node %s has a bad date: %s"%(node.name, str(tmp_date)), 2, warn=True) node.raw_date_constraint = None node.bad_branch = True else: try: tmp = np.mean(tmp_date) node.raw_date_constraint = tmp_date node.bad_branch = False except: self.logger("WARNING: ClockTree.init: node %s has a bad date: %s"%(node.name, str(tmp_date)), 2, warn=True) node.raw_date_constraint = None node.bad_branch = True else: # nodes without date contraints node.raw_date_constraint = None if node.is_terminal(): # Terminal branches without date constraints marked as 'bad' node.bad_branch = True else: # If all branches dowstream are 'bad', and there is no date constraint for # this node, the branch is marked as 'bad' node.bad_branch = np.all([x.bad_branch for x in node]) if node.is_terminal() and node.bad_branch: bad_branch_counter += 1 if bad_branch_counter>self.tree.count_terminals()-3: self.logger("ERROR: ALMOST NO VALID DATE CONSTRAINTS, EXITING", 1, warn=True) return ttconf.ERROR return ttconf.SUCCESS
[ "assign", "dates", "to", "nodes" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L86-L134
[ "def", "_assign_dates", "(", "self", ")", ":", "if", "self", ".", "tree", "is", "None", ":", "self", ".", "logger", "(", "\"ClockTree._assign_dates: tree is not set, can't assign dates\"", ",", "0", ")", "return", "ttconf", ".", "ERROR", "bad_branch_counter", "=", "0", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'postorder'", ")", ":", "if", "node", ".", "name", "in", "self", ".", "date_dict", ":", "tmp_date", "=", "self", ".", "date_dict", "[", "node", ".", "name", "]", "if", "np", ".", "isscalar", "(", "tmp_date", ")", "and", "np", ".", "isnan", "(", "tmp_date", ")", ":", "self", ".", "logger", "(", "\"WARNING: ClockTree.init: node %s has a bad date: %s\"", "%", "(", "node", ".", "name", ",", "str", "(", "tmp_date", ")", ")", ",", "2", ",", "warn", "=", "True", ")", "node", ".", "raw_date_constraint", "=", "None", "node", ".", "bad_branch", "=", "True", "else", ":", "try", ":", "tmp", "=", "np", ".", "mean", "(", "tmp_date", ")", "node", ".", "raw_date_constraint", "=", "tmp_date", "node", ".", "bad_branch", "=", "False", "except", ":", "self", ".", "logger", "(", "\"WARNING: ClockTree.init: node %s has a bad date: %s\"", "%", "(", "node", ".", "name", ",", "str", "(", "tmp_date", ")", ")", ",", "2", ",", "warn", "=", "True", ")", "node", ".", "raw_date_constraint", "=", "None", "node", ".", "bad_branch", "=", "True", "else", ":", "# nodes without date contraints", "node", ".", "raw_date_constraint", "=", "None", "if", "node", ".", "is_terminal", "(", ")", ":", "# Terminal branches without date constraints marked as 'bad'", "node", ".", "bad_branch", "=", "True", "else", ":", "# If all branches dowstream are 'bad', and there is no date constraint for", "# this node, the branch is marked as 'bad'", "node", ".", "bad_branch", "=", "np", ".", "all", "(", "[", "x", ".", "bad_branch", "for", "x", "in", "node", "]", ")", "if", "node", ".", "is_terminal", "(", ")", "and", "node", ".", "bad_branch", ":", "bad_branch_counter", "+=", "1", "if", "bad_branch_counter", ">", "self", ".", "tree", ".", "count_terminals", "(", ")", "-", "3", ":", "self", ".", "logger", "(", "\"ERROR: ALMOST NO VALID DATE CONSTRAINTS, EXITING\"", ",", "1", ",", "warn", "=", "True", ")", "return", "ttconf", ".", "ERROR", "return", "ttconf", ".", "SUCCESS" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree._set_precision
function that sets precision to an (hopfully) reasonable guess based on the length of the sequence if not explicitly set
treetime/clock_tree.py
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*self.one_mutation else: self.min_width = 0.001 if precision in [0,1,2,3]: self.precision=precision if self.one_mutation and self.one_mutation<1e-4 and precision<2: self.logger("ClockTree._set_precision: FOR LONG SEQUENCES (>1e4) precision>=2 IS RECOMMENDED." " \n\t **** precision %d was specified by the user"%precision, level=0) else: # otherwise adjust it depending on the minimal sensible branch length if self.one_mutation: if self.one_mutation>1e-4: self.precision=1 else: self.precision=2 else: self.precision=1 self.logger("ClockTree: Setting precision to level %s"%self.precision, 2) if self.precision==0: self.node_grid_points = ttconf.NODE_GRID_SIZE_ROUGH self.branch_grid_points = ttconf.BRANCH_GRID_SIZE_ROUGH self.n_integral = ttconf.N_INTEGRAL_ROUGH elif self.precision==2: self.node_grid_points = ttconf.NODE_GRID_SIZE_FINE self.branch_grid_points = ttconf.BRANCH_GRID_SIZE_FINE self.n_integral = ttconf.N_INTEGRAL_FINE elif self.precision==3: self.node_grid_points = ttconf.NODE_GRID_SIZE_ULTRA self.branch_grid_points = ttconf.BRANCH_GRID_SIZE_ULTRA self.n_integral = ttconf.N_INTEGRAL_ULTRA else: self.node_grid_points = ttconf.NODE_GRID_SIZE self.branch_grid_points = ttconf.BRANCH_GRID_SIZE self.n_integral = ttconf.N_INTEGRAL
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*self.one_mutation else: self.min_width = 0.001 if precision in [0,1,2,3]: self.precision=precision if self.one_mutation and self.one_mutation<1e-4 and precision<2: self.logger("ClockTree._set_precision: FOR LONG SEQUENCES (>1e4) precision>=2 IS RECOMMENDED." " \n\t **** precision %d was specified by the user"%precision, level=0) else: # otherwise adjust it depending on the minimal sensible branch length if self.one_mutation: if self.one_mutation>1e-4: self.precision=1 else: self.precision=2 else: self.precision=1 self.logger("ClockTree: Setting precision to level %s"%self.precision, 2) if self.precision==0: self.node_grid_points = ttconf.NODE_GRID_SIZE_ROUGH self.branch_grid_points = ttconf.BRANCH_GRID_SIZE_ROUGH self.n_integral = ttconf.N_INTEGRAL_ROUGH elif self.precision==2: self.node_grid_points = ttconf.NODE_GRID_SIZE_FINE self.branch_grid_points = ttconf.BRANCH_GRID_SIZE_FINE self.n_integral = ttconf.N_INTEGRAL_FINE elif self.precision==3: self.node_grid_points = ttconf.NODE_GRID_SIZE_ULTRA self.branch_grid_points = ttconf.BRANCH_GRID_SIZE_ULTRA self.n_integral = ttconf.N_INTEGRAL_ULTRA else: self.node_grid_points = ttconf.NODE_GRID_SIZE self.branch_grid_points = ttconf.BRANCH_GRID_SIZE self.n_integral = ttconf.N_INTEGRAL
[ "function", "that", "sets", "precision", "to", "an", "(", "hopfully", ")", "reasonable", "guess", "based", "on", "the", "length", "of", "the", "sequence", "if", "not", "explicitly", "set" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L137-L179
[ "def", "_set_precision", "(", "self", ",", "precision", ")", ":", "# if precision is explicitly specified, use it.", "if", "self", ".", "one_mutation", ":", "self", ".", "min_width", "=", "10", "*", "self", ".", "one_mutation", "else", ":", "self", ".", "min_width", "=", "0.001", "if", "precision", "in", "[", "0", ",", "1", ",", "2", ",", "3", "]", ":", "self", ".", "precision", "=", "precision", "if", "self", ".", "one_mutation", "and", "self", ".", "one_mutation", "<", "1e-4", "and", "precision", "<", "2", ":", "self", ".", "logger", "(", "\"ClockTree._set_precision: FOR LONG SEQUENCES (>1e4) precision>=2 IS RECOMMENDED.\"", "\" \\n\\t **** precision %d was specified by the user\"", "%", "precision", ",", "level", "=", "0", ")", "else", ":", "# otherwise adjust it depending on the minimal sensible branch length", "if", "self", ".", "one_mutation", ":", "if", "self", ".", "one_mutation", ">", "1e-4", ":", "self", ".", "precision", "=", "1", "else", ":", "self", ".", "precision", "=", "2", "else", ":", "self", ".", "precision", "=", "1", "self", ".", "logger", "(", "\"ClockTree: Setting precision to level %s\"", "%", "self", ".", "precision", ",", "2", ")", "if", "self", ".", "precision", "==", "0", ":", "self", ".", "node_grid_points", "=", "ttconf", ".", "NODE_GRID_SIZE_ROUGH", "self", ".", "branch_grid_points", "=", "ttconf", ".", "BRANCH_GRID_SIZE_ROUGH", "self", ".", "n_integral", "=", "ttconf", ".", "N_INTEGRAL_ROUGH", "elif", "self", ".", "precision", "==", "2", ":", "self", ".", "node_grid_points", "=", "ttconf", ".", "NODE_GRID_SIZE_FINE", "self", ".", "branch_grid_points", "=", "ttconf", ".", "BRANCH_GRID_SIZE_FINE", "self", ".", "n_integral", "=", "ttconf", ".", "N_INTEGRAL_FINE", "elif", "self", ".", "precision", "==", "3", ":", "self", ".", "node_grid_points", "=", "ttconf", ".", "NODE_GRID_SIZE_ULTRA", "self", ".", "branch_grid_points", "=", "ttconf", ".", "BRANCH_GRID_SIZE_ULTRA", "self", ".", "n_integral", "=", "ttconf", ".", "N_INTEGRAL_ULTRA", "else", ":", "self", ".", "node_grid_points", "=", "ttconf", ".", "NODE_GRID_SIZE", "self", ".", "branch_grid_points", "=", "ttconf", ".", "BRANCH_GRID_SIZE", "self", ".", "n_integral", "=", "ttconf", ".", "N_INTEGRAL" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree.setup_TreeRegression
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 covariation Returns ------- TreeRegression a TreeRegression instance with self.tree attached as tree.
treetime/clock_tree.py
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 covariation Returns ------- TreeRegression a TreeRegression instance with self.tree attached as tree. """ from .treeregression import TreeRegression tip_value = lambda x:np.mean(x.raw_date_constraint) if (x.is_terminal() and (x.bad_branch is False)) else None branch_value = lambda x:x.mutation_length if covariation: om = self.one_mutation branch_variance = lambda x:((x.clock_length if hasattr(x,'clock_length') else x.mutation_length) +(self.tip_slack**2*om if x.is_terminal() else 0.0))*om else: branch_variance = lambda x:1.0 if x.is_terminal() else 0.0 Treg = TreeRegression(self.tree, tip_value=tip_value, branch_value=branch_value, branch_variance=branch_variance) Treg.valid_confidence = covariation return Treg
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 covariation Returns ------- TreeRegression a TreeRegression instance with self.tree attached as tree. """ from .treeregression import TreeRegression tip_value = lambda x:np.mean(x.raw_date_constraint) if (x.is_terminal() and (x.bad_branch is False)) else None branch_value = lambda x:x.mutation_length if covariation: om = self.one_mutation branch_variance = lambda x:((x.clock_length if hasattr(x,'clock_length') else x.mutation_length) +(self.tip_slack**2*om if x.is_terminal() else 0.0))*om else: branch_variance = lambda x:1.0 if x.is_terminal() else 0.0 Treg = TreeRegression(self.tree, tip_value=tip_value, branch_value=branch_value, branch_variance=branch_variance) Treg.valid_confidence = covariation return Treg
[ "instantiate", "a", "TreeRegression", "object", "and", "set", "its", "tip_value", "and", "branch_value", "function", "to", "defaults", "that", "are", "sensible", "for", "treetime", "instances", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L195-L221
[ "def", "setup_TreeRegression", "(", "self", ",", "covariation", "=", "True", ")", ":", "from", ".", "treeregression", "import", "TreeRegression", "tip_value", "=", "lambda", "x", ":", "np", ".", "mean", "(", "x", ".", "raw_date_constraint", ")", "if", "(", "x", ".", "is_terminal", "(", ")", "and", "(", "x", ".", "bad_branch", "is", "False", ")", ")", "else", "None", "branch_value", "=", "lambda", "x", ":", "x", ".", "mutation_length", "if", "covariation", ":", "om", "=", "self", ".", "one_mutation", "branch_variance", "=", "lambda", "x", ":", "(", "(", "x", ".", "clock_length", "if", "hasattr", "(", "x", ",", "'clock_length'", ")", "else", "x", ".", "mutation_length", ")", "+", "(", "self", ".", "tip_slack", "**", "2", "*", "om", "if", "x", ".", "is_terminal", "(", ")", "else", "0.0", ")", ")", "*", "om", "else", ":", "branch_variance", "=", "lambda", "x", ":", "1.0", "if", "x", ".", "is_terminal", "(", ")", "else", "0.0", "Treg", "=", "TreeRegression", "(", "self", ".", "tree", ",", "tip_value", "=", "tip_value", ",", "branch_value", "=", "branch_value", ",", "branch_variance", "=", "branch_variance", ")", "Treg", ".", "valid_confidence", "=", "covariation", "return", "Treg" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree.init_date_constraints
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. .. Note:: The tree must have dates set to all nodes before calling this function. Parameters ---------- ancestral_inference: bool If True, reinfer ancestral sequences when ancestral sequences are missing clock_rate: float If specified, timetree optimization will be done assuming a fixed clock rate as specified
treetime/clock_tree.py
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, these coefficients as well as regression parameters are stored in the 'dates2dist' object. .. Note:: The tree must have dates set to all nodes before calling this function. Parameters ---------- ancestral_inference: bool If True, reinfer ancestral sequences when ancestral sequences are missing clock_rate: float If specified, timetree optimization will be done assuming a fixed clock rate as specified """ self.logger("ClockTree.init_date_constraints...",2) self.tree.coalescent_joint_LH = 0 if self.aln and (ancestral_inference or (not hasattr(self.tree.root, 'sequence'))): self.infer_ancestral_sequences('probabilistic', marginal=self.branch_length_mode=='marginal', sample_from_profile='root',**kwarks) # set the None for the date-related attributes in the internal nodes. # make interpolation objects for the branches self.logger('ClockTree.init_date_constraints: Initializing branch length interpolation objects...',3) has_clock_length = [] for node in self.tree.find_clades(order='postorder'): if node.up is None: node.branch_length_interpolator = None else: has_clock_length.append(hasattr(node, 'clock_length')) # copy the merger rate and gamma if they are set if hasattr(node,'branch_length_interpolator') and node.branch_length_interpolator is not None: gamma = node.branch_length_interpolator.gamma merger_cost = node.branch_length_interpolator.merger_cost else: gamma = 1.0 merger_cost = None if self.branch_length_mode=='marginal': node.profile_pair = self.marginal_branch_profile(node) node.branch_length_interpolator = BranchLenInterpolator(node, self.gtr, pattern_multiplicity = self.multiplicity, min_width=self.min_width, one_mutation=self.one_mutation, branch_length_mode=self.branch_length_mode) node.branch_length_interpolator.merger_cost = merger_cost node.branch_length_interpolator.gamma = gamma # use covariance in clock model only after initial timetree estimation is done use_cov = (np.sum(has_clock_length) > len(has_clock_length)*0.7) and self.use_covariation self.get_clock_model(covariation=use_cov, slope=clock_rate) # make node distribution objects for node in self.tree.find_clades(order="postorder"): # node is constrained if hasattr(node, 'raw_date_constraint') and node.raw_date_constraint is not None: # set the absolute time before present in branch length units if np.isscalar(node.raw_date_constraint): tbp = self.date2dist.get_time_before_present(node.raw_date_constraint) node.date_constraint = Distribution.delta_function(tbp, weight=1.0, min_width=self.min_width) else: tbp = self.date2dist.get_time_before_present(np.array(node.raw_date_constraint)) node.date_constraint = Distribution(tbp, np.ones_like(tbp), is_log=False, min_width=self.min_width) if hasattr(node, 'bad_branch') and node.bad_branch is True: self.logger("ClockTree.init_date_constraints -- WARNING: Branch is marked as bad" ", excluding it from the optimization process.\n" "\t\tDate constraint will be ignored!", 4, warn=True) else: # node without sampling date set node.raw_date_constraint = None node.date_constraint = None
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, these coefficients as well as regression parameters are stored in the 'dates2dist' object. .. Note:: The tree must have dates set to all nodes before calling this function. Parameters ---------- ancestral_inference: bool If True, reinfer ancestral sequences when ancestral sequences are missing clock_rate: float If specified, timetree optimization will be done assuming a fixed clock rate as specified """ self.logger("ClockTree.init_date_constraints...",2) self.tree.coalescent_joint_LH = 0 if self.aln and (ancestral_inference or (not hasattr(self.tree.root, 'sequence'))): self.infer_ancestral_sequences('probabilistic', marginal=self.branch_length_mode=='marginal', sample_from_profile='root',**kwarks) # set the None for the date-related attributes in the internal nodes. # make interpolation objects for the branches self.logger('ClockTree.init_date_constraints: Initializing branch length interpolation objects...',3) has_clock_length = [] for node in self.tree.find_clades(order='postorder'): if node.up is None: node.branch_length_interpolator = None else: has_clock_length.append(hasattr(node, 'clock_length')) # copy the merger rate and gamma if they are set if hasattr(node,'branch_length_interpolator') and node.branch_length_interpolator is not None: gamma = node.branch_length_interpolator.gamma merger_cost = node.branch_length_interpolator.merger_cost else: gamma = 1.0 merger_cost = None if self.branch_length_mode=='marginal': node.profile_pair = self.marginal_branch_profile(node) node.branch_length_interpolator = BranchLenInterpolator(node, self.gtr, pattern_multiplicity = self.multiplicity, min_width=self.min_width, one_mutation=self.one_mutation, branch_length_mode=self.branch_length_mode) node.branch_length_interpolator.merger_cost = merger_cost node.branch_length_interpolator.gamma = gamma # use covariance in clock model only after initial timetree estimation is done use_cov = (np.sum(has_clock_length) > len(has_clock_length)*0.7) and self.use_covariation self.get_clock_model(covariation=use_cov, slope=clock_rate) # make node distribution objects for node in self.tree.find_clades(order="postorder"): # node is constrained if hasattr(node, 'raw_date_constraint') and node.raw_date_constraint is not None: # set the absolute time before present in branch length units if np.isscalar(node.raw_date_constraint): tbp = self.date2dist.get_time_before_present(node.raw_date_constraint) node.date_constraint = Distribution.delta_function(tbp, weight=1.0, min_width=self.min_width) else: tbp = self.date2dist.get_time_before_present(np.array(node.raw_date_constraint)) node.date_constraint = Distribution(tbp, np.ones_like(tbp), is_log=False, min_width=self.min_width) if hasattr(node, 'bad_branch') and node.bad_branch is True: self.logger("ClockTree.init_date_constraints -- WARNING: Branch is marked as bad" ", excluding it from the optimization process.\n" "\t\tDate constraint will be ignored!", 4, warn=True) else: # node without sampling date set node.raw_date_constraint = None node.date_constraint = None
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L237-L316
[ "def", "init_date_constraints", "(", "self", ",", "ancestral_inference", "=", "False", ",", "clock_rate", "=", "None", ",", "*", "*", "kwarks", ")", ":", "self", ".", "logger", "(", "\"ClockTree.init_date_constraints...\"", ",", "2", ")", "self", ".", "tree", ".", "coalescent_joint_LH", "=", "0", "if", "self", ".", "aln", "and", "(", "ancestral_inference", "or", "(", "not", "hasattr", "(", "self", ".", "tree", ".", "root", ",", "'sequence'", ")", ")", ")", ":", "self", ".", "infer_ancestral_sequences", "(", "'probabilistic'", ",", "marginal", "=", "self", ".", "branch_length_mode", "==", "'marginal'", ",", "sample_from_profile", "=", "'root'", ",", "*", "*", "kwarks", ")", "# set the None for the date-related attributes in the internal nodes.", "# make interpolation objects for the branches", "self", ".", "logger", "(", "'ClockTree.init_date_constraints: Initializing branch length interpolation objects...'", ",", "3", ")", "has_clock_length", "=", "[", "]", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'postorder'", ")", ":", "if", "node", ".", "up", "is", "None", ":", "node", ".", "branch_length_interpolator", "=", "None", "else", ":", "has_clock_length", ".", "append", "(", "hasattr", "(", "node", ",", "'clock_length'", ")", ")", "# copy the merger rate and gamma if they are set", "if", "hasattr", "(", "node", ",", "'branch_length_interpolator'", ")", "and", "node", ".", "branch_length_interpolator", "is", "not", "None", ":", "gamma", "=", "node", ".", "branch_length_interpolator", ".", "gamma", "merger_cost", "=", "node", ".", "branch_length_interpolator", ".", "merger_cost", "else", ":", "gamma", "=", "1.0", "merger_cost", "=", "None", "if", "self", ".", "branch_length_mode", "==", "'marginal'", ":", "node", ".", "profile_pair", "=", "self", ".", "marginal_branch_profile", "(", "node", ")", "node", ".", "branch_length_interpolator", "=", "BranchLenInterpolator", "(", "node", ",", "self", ".", "gtr", ",", "pattern_multiplicity", "=", "self", ".", "multiplicity", ",", "min_width", "=", "self", ".", "min_width", ",", "one_mutation", "=", "self", ".", "one_mutation", ",", "branch_length_mode", "=", "self", ".", "branch_length_mode", ")", "node", ".", "branch_length_interpolator", ".", "merger_cost", "=", "merger_cost", "node", ".", "branch_length_interpolator", ".", "gamma", "=", "gamma", "# use covariance in clock model only after initial timetree estimation is done", "use_cov", "=", "(", "np", ".", "sum", "(", "has_clock_length", ")", ">", "len", "(", "has_clock_length", ")", "*", "0.7", ")", "and", "self", ".", "use_covariation", "self", ".", "get_clock_model", "(", "covariation", "=", "use_cov", ",", "slope", "=", "clock_rate", ")", "# make node distribution objects", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "\"postorder\"", ")", ":", "# node is constrained", "if", "hasattr", "(", "node", ",", "'raw_date_constraint'", ")", "and", "node", ".", "raw_date_constraint", "is", "not", "None", ":", "# set the absolute time before present in branch length units", "if", "np", ".", "isscalar", "(", "node", ".", "raw_date_constraint", ")", ":", "tbp", "=", "self", ".", "date2dist", ".", "get_time_before_present", "(", "node", ".", "raw_date_constraint", ")", "node", ".", "date_constraint", "=", "Distribution", ".", "delta_function", "(", "tbp", ",", "weight", "=", "1.0", ",", "min_width", "=", "self", ".", "min_width", ")", "else", ":", "tbp", "=", "self", ".", "date2dist", ".", "get_time_before_present", "(", "np", ".", "array", "(", "node", ".", "raw_date_constraint", ")", ")", "node", ".", "date_constraint", "=", "Distribution", "(", "tbp", ",", "np", ".", "ones_like", "(", "tbp", ")", ",", "is_log", "=", "False", ",", "min_width", "=", "self", ".", "min_width", ")", "if", "hasattr", "(", "node", ",", "'bad_branch'", ")", "and", "node", ".", "bad_branch", "is", "True", ":", "self", ".", "logger", "(", "\"ClockTree.init_date_constraints -- WARNING: Branch is marked as bad\"", "\", excluding it from the optimization process.\\n\"", "\"\\t\\tDate constraint will be ignored!\"", ",", "4", ",", "warn", "=", "True", ")", "else", ":", "# node without sampling date set", "node", ".", "raw_date_constraint", "=", "None", "node", ".", "date_constraint", "=", "None" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree.make_time_tree
Use the date constraints to calculate the most likely positions of unconstrained nodes. Parameters ---------- time_marginal : bool If true, use marginal reconstruction for node positions **kwargs Key word arguments to initialize dates constraints
treetime/clock_tree.py
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 positions **kwargs Key word arguments to initialize dates constraints ''' self.logger("ClockTree: Maximum likelihood tree optimization with temporal constraints",1) self.init_date_constraints(clock_rate=clock_rate, **kwargs) if time_marginal: self._ml_t_marginal(assign_dates = time_marginal=="assign") else: self._ml_t_joint() self.convert_dates()
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 positions **kwargs Key word arguments to initialize dates constraints ''' self.logger("ClockTree: Maximum likelihood tree optimization with temporal constraints",1) self.init_date_constraints(clock_rate=clock_rate, **kwargs) if time_marginal: self._ml_t_marginal(assign_dates = time_marginal=="assign") else: self._ml_t_joint() self.convert_dates()
[ "Use", "the", "date", "constraints", "to", "calculate", "the", "most", "likely", "positions", "of", "unconstrained", "nodes", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L319-L343
[ "def", "make_time_tree", "(", "self", ",", "time_marginal", "=", "False", ",", "clock_rate", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "logger", "(", "\"ClockTree: Maximum likelihood tree optimization with temporal constraints\"", ",", "1", ")", "self", ".", "init_date_constraints", "(", "clock_rate", "=", "clock_rate", ",", "*", "*", "kwargs", ")", "if", "time_marginal", ":", "self", ".", "_ml_t_marginal", "(", "assign_dates", "=", "time_marginal", "==", "\"assign\"", ")", "else", ":", "self", ".", "_ml_t_joint", "(", ")", "self", ".", "convert_dates", "(", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree._ml_t_joint
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 time_before_present value, which is the position of the node, expressed in the units of the branch length, and scaled from the present-day. The value is assigned to the corresponding attribute of each node of the tree. Returns ------- None Every internal node is assigned the probability distribution in form of an interpolation object and sends this distribution further towards the root.
treetime/clock_tree.py
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 from the root to the leaves. The result of this operation is the time_before_present value, which is the position of the node, expressed in the units of the branch length, and scaled from the present-day. The value is assigned to the corresponding attribute of each node of the tree. Returns ------- None Every internal node is assigned the probability distribution in form of an interpolation object and sends this distribution further towards the root. """ def _cleanup(): for node in self.tree.find_clades(): del node.joint_pos_Lx del node.joint_pos_Cx self.logger("ClockTree - Joint reconstruction: Propagating leaves -> root...", 2) # go through the nodes from leaves towards the root: for node in self.tree.find_clades(order='postorder'): # children first, msg to parents # Lx is the maximal likelihood of a subtree given the parent position # Cx is the branch length corresponding to the maximally likely subtree if node.bad_branch: # no information at the node node.joint_pos_Lx = None node.joint_pos_Cx = None else: # all other nodes if node.date_constraint is not None and node.date_constraint.is_delta: # there is a time constraint # subtree probability given the position of the parent node # Lx.x is the position of the parent node # Lx.y is the probablity of the subtree (consisting of one terminal node in this case) # Cx.y is the branch length corresponding the optimal subtree bl = node.branch_length_interpolator.x x = bl + node.date_constraint.peak_pos node.joint_pos_Lx = Distribution(x, node.branch_length_interpolator(bl), min_width=self.min_width, is_log=True) node.joint_pos_Cx = Distribution(x, bl, min_width=self.min_width) # map back to the branch length else: # all nodes without precise constraint but positional information msgs_to_multiply = [node.date_constraint] if node.date_constraint is not None else [] msgs_to_multiply.extend([child.joint_pos_Lx for child in node.clades if child.joint_pos_Lx is not None]) # subtree likelihood given the node's constraint and child messages if len(msgs_to_multiply) == 0: # there are no constraints node.joint_pos_Lx = None node.joint_pos_Cx = None continue elif len(msgs_to_multiply)>1: # combine the different msgs and constraints subtree_distribution = Distribution.multiply(msgs_to_multiply) else: # there is exactly one constraint. subtree_distribution = msgs_to_multiply[0] if node.up is None: # this is the root, set dates subtree_distribution._adjust_grid(rel_tol=self.rel_tol_prune) # set root position and joint likelihood of the tree node.time_before_present = subtree_distribution.peak_pos node.joint_pos_Lx = subtree_distribution node.joint_pos_Cx = None node.clock_length = node.branch_length else: # otherwise propagate to parent res, res_t = NodeInterpolator.convolve(subtree_distribution, node.branch_length_interpolator, max_or_integral='max', inverse_time=True, n_grid_points = self.node_grid_points, n_integral=self.n_integral, rel_tol=self.rel_tol_refine) res._adjust_grid(rel_tol=self.rel_tol_prune) node.joint_pos_Lx = res node.joint_pos_Cx = res_t # go through the nodes from root towards the leaves and assign joint ML positions: self.logger("ClockTree - Joint reconstruction: Propagating root -> leaves...", 2) for node in self.tree.find_clades(order='preorder'): # root first, msgs to children if node.up is None: # root node continue # the position was already set on the previous step if node.joint_pos_Cx is None: # no constraints or branch is bad - reconstruct from the branch len interpolator node.branch_length = node.branch_length_interpolator.peak_pos elif isinstance(node.joint_pos_Cx, Distribution): # NOTE the Lx distribution is the likelihood, given the position of the parent # (Lx.x = parent position, Lx.y = LH of the node_pos given Lx.x, # the length of the branch corresponding to the most likely # subtree is node.Cx(node.time_before_present)) subtree_LH = node.joint_pos_Lx(node.up.time_before_present) node.branch_length = node.joint_pos_Cx(max(node.joint_pos_Cx.xmin, node.up.time_before_present)+ttconf.TINY_NUMBER) node.time_before_present = node.up.time_before_present - node.branch_length node.clock_length = node.branch_length # just sanity check, should never happen: if node.branch_length < 0 or node.time_before_present < 0: if node.branch_length<0 and node.branch_length>-ttconf.TINY_NUMBER: self.logger("ClockTree - Joint reconstruction: correcting rounding error of %s"%node.name, 4) node.branch_length = 0 self.tree.positional_joint_LH = self.timetree_likelihood() # cleanup, if required if not self.debug: _cleanup()
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 from the root to the leaves. The result of this operation is the time_before_present value, which is the position of the node, expressed in the units of the branch length, and scaled from the present-day. The value is assigned to the corresponding attribute of each node of the tree. Returns ------- None Every internal node is assigned the probability distribution in form of an interpolation object and sends this distribution further towards the root. """ def _cleanup(): for node in self.tree.find_clades(): del node.joint_pos_Lx del node.joint_pos_Cx self.logger("ClockTree - Joint reconstruction: Propagating leaves -> root...", 2) # go through the nodes from leaves towards the root: for node in self.tree.find_clades(order='postorder'): # children first, msg to parents # Lx is the maximal likelihood of a subtree given the parent position # Cx is the branch length corresponding to the maximally likely subtree if node.bad_branch: # no information at the node node.joint_pos_Lx = None node.joint_pos_Cx = None else: # all other nodes if node.date_constraint is not None and node.date_constraint.is_delta: # there is a time constraint # subtree probability given the position of the parent node # Lx.x is the position of the parent node # Lx.y is the probablity of the subtree (consisting of one terminal node in this case) # Cx.y is the branch length corresponding the optimal subtree bl = node.branch_length_interpolator.x x = bl + node.date_constraint.peak_pos node.joint_pos_Lx = Distribution(x, node.branch_length_interpolator(bl), min_width=self.min_width, is_log=True) node.joint_pos_Cx = Distribution(x, bl, min_width=self.min_width) # map back to the branch length else: # all nodes without precise constraint but positional information msgs_to_multiply = [node.date_constraint] if node.date_constraint is not None else [] msgs_to_multiply.extend([child.joint_pos_Lx for child in node.clades if child.joint_pos_Lx is not None]) # subtree likelihood given the node's constraint and child messages if len(msgs_to_multiply) == 0: # there are no constraints node.joint_pos_Lx = None node.joint_pos_Cx = None continue elif len(msgs_to_multiply)>1: # combine the different msgs and constraints subtree_distribution = Distribution.multiply(msgs_to_multiply) else: # there is exactly one constraint. subtree_distribution = msgs_to_multiply[0] if node.up is None: # this is the root, set dates subtree_distribution._adjust_grid(rel_tol=self.rel_tol_prune) # set root position and joint likelihood of the tree node.time_before_present = subtree_distribution.peak_pos node.joint_pos_Lx = subtree_distribution node.joint_pos_Cx = None node.clock_length = node.branch_length else: # otherwise propagate to parent res, res_t = NodeInterpolator.convolve(subtree_distribution, node.branch_length_interpolator, max_or_integral='max', inverse_time=True, n_grid_points = self.node_grid_points, n_integral=self.n_integral, rel_tol=self.rel_tol_refine) res._adjust_grid(rel_tol=self.rel_tol_prune) node.joint_pos_Lx = res node.joint_pos_Cx = res_t # go through the nodes from root towards the leaves and assign joint ML positions: self.logger("ClockTree - Joint reconstruction: Propagating root -> leaves...", 2) for node in self.tree.find_clades(order='preorder'): # root first, msgs to children if node.up is None: # root node continue # the position was already set on the previous step if node.joint_pos_Cx is None: # no constraints or branch is bad - reconstruct from the branch len interpolator node.branch_length = node.branch_length_interpolator.peak_pos elif isinstance(node.joint_pos_Cx, Distribution): # NOTE the Lx distribution is the likelihood, given the position of the parent # (Lx.x = parent position, Lx.y = LH of the node_pos given Lx.x, # the length of the branch corresponding to the most likely # subtree is node.Cx(node.time_before_present)) subtree_LH = node.joint_pos_Lx(node.up.time_before_present) node.branch_length = node.joint_pos_Cx(max(node.joint_pos_Cx.xmin, node.up.time_before_present)+ttconf.TINY_NUMBER) node.time_before_present = node.up.time_before_present - node.branch_length node.clock_length = node.branch_length # just sanity check, should never happen: if node.branch_length < 0 or node.time_before_present < 0: if node.branch_length<0 and node.branch_length>-ttconf.TINY_NUMBER: self.logger("ClockTree - Joint reconstruction: correcting rounding error of %s"%node.name, 4) node.branch_length = 0 self.tree.positional_joint_LH = self.timetree_likelihood() # cleanup, if required if not self.debug: _cleanup()
[ "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", "time_before_present", "value", "which", "is", "the", "position", "of", "the", "node", "expressed", "in", "the", "units", "of", "the", "branch", "length", "and", "scaled", "from", "the", "present", "-", "day", ".", "The", "value", "is", "assigned", "to", "the", "corresponding", "attribute", "of", "each", "node", "of", "the", "tree", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L346-L460
[ "def", "_ml_t_joint", "(", "self", ")", ":", "def", "_cleanup", "(", ")", ":", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "del", "node", ".", "joint_pos_Lx", "del", "node", ".", "joint_pos_Cx", "self", ".", "logger", "(", "\"ClockTree - Joint reconstruction: Propagating leaves -> root...\"", ",", "2", ")", "# go through the nodes from leaves towards the root:", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'postorder'", ")", ":", "# children first, msg to parents", "# Lx is the maximal likelihood of a subtree given the parent position", "# Cx is the branch length corresponding to the maximally likely subtree", "if", "node", ".", "bad_branch", ":", "# no information at the node", "node", ".", "joint_pos_Lx", "=", "None", "node", ".", "joint_pos_Cx", "=", "None", "else", ":", "# all other nodes", "if", "node", ".", "date_constraint", "is", "not", "None", "and", "node", ".", "date_constraint", ".", "is_delta", ":", "# there is a time constraint", "# subtree probability given the position of the parent node", "# Lx.x is the position of the parent node", "# Lx.y is the probablity of the subtree (consisting of one terminal node in this case)", "# Cx.y is the branch length corresponding the optimal subtree", "bl", "=", "node", ".", "branch_length_interpolator", ".", "x", "x", "=", "bl", "+", "node", ".", "date_constraint", ".", "peak_pos", "node", ".", "joint_pos_Lx", "=", "Distribution", "(", "x", ",", "node", ".", "branch_length_interpolator", "(", "bl", ")", ",", "min_width", "=", "self", ".", "min_width", ",", "is_log", "=", "True", ")", "node", ".", "joint_pos_Cx", "=", "Distribution", "(", "x", ",", "bl", ",", "min_width", "=", "self", ".", "min_width", ")", "# map back to the branch length", "else", ":", "# all nodes without precise constraint but positional information", "msgs_to_multiply", "=", "[", "node", ".", "date_constraint", "]", "if", "node", ".", "date_constraint", "is", "not", "None", "else", "[", "]", "msgs_to_multiply", ".", "extend", "(", "[", "child", ".", "joint_pos_Lx", "for", "child", "in", "node", ".", "clades", "if", "child", ".", "joint_pos_Lx", "is", "not", "None", "]", ")", "# subtree likelihood given the node's constraint and child messages", "if", "len", "(", "msgs_to_multiply", ")", "==", "0", ":", "# there are no constraints", "node", ".", "joint_pos_Lx", "=", "None", "node", ".", "joint_pos_Cx", "=", "None", "continue", "elif", "len", "(", "msgs_to_multiply", ")", ">", "1", ":", "# combine the different msgs and constraints", "subtree_distribution", "=", "Distribution", ".", "multiply", "(", "msgs_to_multiply", ")", "else", ":", "# there is exactly one constraint.", "subtree_distribution", "=", "msgs_to_multiply", "[", "0", "]", "if", "node", ".", "up", "is", "None", ":", "# this is the root, set dates", "subtree_distribution", ".", "_adjust_grid", "(", "rel_tol", "=", "self", ".", "rel_tol_prune", ")", "# set root position and joint likelihood of the tree", "node", ".", "time_before_present", "=", "subtree_distribution", ".", "peak_pos", "node", ".", "joint_pos_Lx", "=", "subtree_distribution", "node", ".", "joint_pos_Cx", "=", "None", "node", ".", "clock_length", "=", "node", ".", "branch_length", "else", ":", "# otherwise propagate to parent", "res", ",", "res_t", "=", "NodeInterpolator", ".", "convolve", "(", "subtree_distribution", ",", "node", ".", "branch_length_interpolator", ",", "max_or_integral", "=", "'max'", ",", "inverse_time", "=", "True", ",", "n_grid_points", "=", "self", ".", "node_grid_points", ",", "n_integral", "=", "self", ".", "n_integral", ",", "rel_tol", "=", "self", ".", "rel_tol_refine", ")", "res", ".", "_adjust_grid", "(", "rel_tol", "=", "self", ".", "rel_tol_prune", ")", "node", ".", "joint_pos_Lx", "=", "res", "node", ".", "joint_pos_Cx", "=", "res_t", "# go through the nodes from root towards the leaves and assign joint ML positions:", "self", ".", "logger", "(", "\"ClockTree - Joint reconstruction: Propagating root -> leaves...\"", ",", "2", ")", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'preorder'", ")", ":", "# root first, msgs to children", "if", "node", ".", "up", "is", "None", ":", "# root node", "continue", "# the position was already set on the previous step", "if", "node", ".", "joint_pos_Cx", "is", "None", ":", "# no constraints or branch is bad - reconstruct from the branch len interpolator", "node", ".", "branch_length", "=", "node", ".", "branch_length_interpolator", ".", "peak_pos", "elif", "isinstance", "(", "node", ".", "joint_pos_Cx", ",", "Distribution", ")", ":", "# NOTE the Lx distribution is the likelihood, given the position of the parent", "# (Lx.x = parent position, Lx.y = LH of the node_pos given Lx.x,", "# the length of the branch corresponding to the most likely", "# subtree is node.Cx(node.time_before_present))", "subtree_LH", "=", "node", ".", "joint_pos_Lx", "(", "node", ".", "up", ".", "time_before_present", ")", "node", ".", "branch_length", "=", "node", ".", "joint_pos_Cx", "(", "max", "(", "node", ".", "joint_pos_Cx", ".", "xmin", ",", "node", ".", "up", ".", "time_before_present", ")", "+", "ttconf", ".", "TINY_NUMBER", ")", "node", ".", "time_before_present", "=", "node", ".", "up", ".", "time_before_present", "-", "node", ".", "branch_length", "node", ".", "clock_length", "=", "node", ".", "branch_length", "# just sanity check, should never happen:", "if", "node", ".", "branch_length", "<", "0", "or", "node", ".", "time_before_present", "<", "0", ":", "if", "node", ".", "branch_length", "<", "0", "and", "node", ".", "branch_length", ">", "-", "ttconf", ".", "TINY_NUMBER", ":", "self", ".", "logger", "(", "\"ClockTree - Joint reconstruction: correcting rounding error of %s\"", "%", "node", ".", "name", ",", "4", ")", "node", ".", "branch_length", "=", "0", "self", ".", "tree", ".", "positional_joint_LH", "=", "self", ".", "timetree_likelihood", "(", ")", "# cleanup, if required", "if", "not", "self", ".", "debug", ":", "_cleanup", "(", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree.timetree_likelihood
Return the likelihood of the data given the current branch length in the tree
treetime/clock_tree.py
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 continue LH -= node.branch_length_interpolator(node.branch_length) # add the root sequence LH and return if self.aln: LH += self.gtr.sequence_logLH(self.tree.root.cseq, pattern_multiplicity=self.multiplicity) return LH
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 continue LH -= node.branch_length_interpolator(node.branch_length) # add the root sequence LH and return if self.aln: LH += self.gtr.sequence_logLH(self.tree.root.cseq, pattern_multiplicity=self.multiplicity) return LH
[ "Return", "the", "likelihood", "of", "the", "data", "given", "the", "current", "branch", "length", "in", "the", "tree" ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L463-L476
[ "def", "timetree_likelihood", "(", "self", ")", ":", "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", "continue", "LH", "-=", "node", ".", "branch_length_interpolator", "(", "node", ".", "branch_length", ")", "# add the root sequence LH and return", "if", "self", ".", "aln", ":", "LH", "+=", "self", ".", "gtr", ".", "sequence_logLH", "(", "self", ".", "tree", ".", "root", ".", "cseq", ",", "pattern_multiplicity", "=", "self", ".", "multiplicity", ")", "return", "LH" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree._ml_t_marginal
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 distributions are set as marginal_pos_LH attributes to the nodes. Parameters ---------- assign_dates : bool, default False If True, the inferred dates will be assigned to the nodes as :code:`time_before_present' attributes, and their branch lengths will be corrected accordingly. .. Note:: Normally, the dates are assigned by running joint reconstruction. Returns ------- None Every internal node is assigned the probability distribution in form of an interpolation object and sends this distribution further towards the root.
treetime/clock_tree.py
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 on the constraints on all leaves of the tree, which have sampling dates. The probability distributions are set as marginal_pos_LH attributes to the nodes. Parameters ---------- assign_dates : bool, default False If True, the inferred dates will be assigned to the nodes as :code:`time_before_present' attributes, and their branch lengths will be corrected accordingly. .. Note:: Normally, the dates are assigned by running joint reconstruction. Returns ------- None Every internal node is assigned the probability distribution in form of an interpolation object and sends this distribution further towards the root. """ def _cleanup(): for node in self.tree.find_clades(): try: del node.marginal_pos_Lx del node.subtree_distribution del node.msg_from_parent #del node.marginal_pos_LH except: pass self.logger("ClockTree - Marginal reconstruction: Propagating leaves -> root...", 2) # go through the nodes from leaves towards the root: for node in self.tree.find_clades(order='postorder'): # children first, msg to parents if node.bad_branch: # no information node.marginal_pos_Lx = None else: # all other nodes if node.date_constraint is not None and node.date_constraint.is_delta: # there is a time constraint # initialize the Lx for nodes with precise date constraint: # subtree probability given the position of the parent node # position of the parent node is given by the branch length # distribution attached to the child node position node.subtree_distribution = node.date_constraint bl = node.branch_length_interpolator.x x = bl + node.date_constraint.peak_pos node.marginal_pos_Lx = Distribution(x, node.branch_length_interpolator(bl), min_width=self.min_width, is_log=True) else: # all nodes without precise constraint but positional information # subtree likelihood given the node's constraint and child msg: msgs_to_multiply = [node.date_constraint] if node.date_constraint is not None else [] msgs_to_multiply.extend([child.marginal_pos_Lx for child in node.clades if child.marginal_pos_Lx is not None]) # combine the different msgs and constraints if len(msgs_to_multiply)==0: # no information node.marginal_pos_Lx = None continue elif len(msgs_to_multiply)==1: node.subtree_distribution = msgs_to_multiply[0] else: # combine the different msgs and constraints node.subtree_distribution = Distribution.multiply(msgs_to_multiply) if node.up is None: # this is the root, set dates node.subtree_distribution._adjust_grid(rel_tol=self.rel_tol_prune) node.marginal_pos_Lx = node.subtree_distribution node.marginal_pos_LH = node.subtree_distribution self.tree.positional_marginal_LH = -node.subtree_distribution.peak_val else: # otherwise propagate to parent res, res_t = NodeInterpolator.convolve(node.subtree_distribution, node.branch_length_interpolator, max_or_integral='integral', n_grid_points = self.node_grid_points, n_integral=self.n_integral, rel_tol=self.rel_tol_refine) res._adjust_grid(rel_tol=self.rel_tol_prune) node.marginal_pos_Lx = res self.logger("ClockTree - Marginal reconstruction: Propagating root -> leaves...", 2) from scipy.interpolate import interp1d for node in self.tree.find_clades(order='preorder'): ## The root node if node.up is None: node.msg_from_parent = None # nothing beyond the root # all other cases (All internal nodes + unconstrained terminals) else: parent = node.up # messages from the complementary subtree (iterate over all sister nodes) complementary_msgs = [sister.marginal_pos_Lx for sister in parent.clades if (sister != node) and (sister.marginal_pos_Lx is not None)] # if parent itself got smth from the root node, include it if parent.msg_from_parent is not None: complementary_msgs.append(parent.msg_from_parent) elif parent.marginal_pos_Lx is not None: complementary_msgs.append(parent.marginal_pos_LH) if len(complementary_msgs): msg_parent_to_node = NodeInterpolator.multiply(complementary_msgs) msg_parent_to_node._adjust_grid(rel_tol=self.rel_tol_prune) else: x = [parent.numdate, numeric_date()] msg_parent_to_node = NodeInterpolator(x, [1.0, 1.0],min_width=self.min_width) # integral message, which delivers to the node the positional information # from the complementary subtree res, res_t = NodeInterpolator.convolve(msg_parent_to_node, node.branch_length_interpolator, max_or_integral='integral', inverse_time=False, n_grid_points = self.node_grid_points, n_integral=self.n_integral, rel_tol=self.rel_tol_refine) node.msg_from_parent = res if node.marginal_pos_Lx is None: node.marginal_pos_LH = node.msg_from_parent else: node.marginal_pos_LH = NodeInterpolator.multiply((node.msg_from_parent, node.subtree_distribution)) self.logger('ClockTree._ml_t_root_to_leaves: computed convolution' ' with %d points at node %s'%(len(res.x),node.name),4) if self.debug: tmp = np.diff(res.y-res.peak_val) nsign_changed = np.sum((tmp[1:]*tmp[:-1]<0)&(res.y[1:-1]-res.peak_val<500)) if nsign_changed>1: import matplotlib.pyplot as plt plt.ion() plt.plot(res.x, res.y-res.peak_val, '-o') plt.plot(res.peak_pos - node.branch_length_interpolator.x, node.branch_length_interpolator(node.branch_length_interpolator.x)-node.branch_length_interpolator.peak_val, '-o') plt.plot(msg_parent_to_node.x,msg_parent_to_node.y-msg_parent_to_node.peak_val, '-o') plt.ylim(0,100) plt.xlim(-0.05, 0.05) import ipdb; ipdb.set_trace() # assign positions of nodes and branch length only when desired # since marginal reconstruction can result in negative branch length if assign_dates: node.time_before_present = node.marginal_pos_LH.peak_pos if node.up: node.clock_length = node.up.time_before_present - node.time_before_present node.branch_length = node.clock_length # construct the inverse cumulant distribution to evaluate confidence intervals if node.marginal_pos_LH.is_delta: node.marginal_inverse_cdf=interp1d([0,1], node.marginal_pos_LH.peak_pos*np.ones(2), kind="linear") else: dt = np.diff(node.marginal_pos_LH.x) y = node.marginal_pos_LH.prob_relative(node.marginal_pos_LH.x) int_y = np.concatenate(([0], np.cumsum(dt*(y[1:]+y[:-1])/2.0))) int_y/=int_y[-1] node.marginal_inverse_cdf = interp1d(int_y, node.marginal_pos_LH.x, kind="linear") node.marginal_cdf = interp1d(node.marginal_pos_LH.x, int_y, kind="linear") if not self.debug: _cleanup() return
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 on the constraints on all leaves of the tree, which have sampling dates. The probability distributions are set as marginal_pos_LH attributes to the nodes. Parameters ---------- assign_dates : bool, default False If True, the inferred dates will be assigned to the nodes as :code:`time_before_present' attributes, and their branch lengths will be corrected accordingly. .. Note:: Normally, the dates are assigned by running joint reconstruction. Returns ------- None Every internal node is assigned the probability distribution in form of an interpolation object and sends this distribution further towards the root. """ def _cleanup(): for node in self.tree.find_clades(): try: del node.marginal_pos_Lx del node.subtree_distribution del node.msg_from_parent #del node.marginal_pos_LH except: pass self.logger("ClockTree - Marginal reconstruction: Propagating leaves -> root...", 2) # go through the nodes from leaves towards the root: for node in self.tree.find_clades(order='postorder'): # children first, msg to parents if node.bad_branch: # no information node.marginal_pos_Lx = None else: # all other nodes if node.date_constraint is not None and node.date_constraint.is_delta: # there is a time constraint # initialize the Lx for nodes with precise date constraint: # subtree probability given the position of the parent node # position of the parent node is given by the branch length # distribution attached to the child node position node.subtree_distribution = node.date_constraint bl = node.branch_length_interpolator.x x = bl + node.date_constraint.peak_pos node.marginal_pos_Lx = Distribution(x, node.branch_length_interpolator(bl), min_width=self.min_width, is_log=True) else: # all nodes without precise constraint but positional information # subtree likelihood given the node's constraint and child msg: msgs_to_multiply = [node.date_constraint] if node.date_constraint is not None else [] msgs_to_multiply.extend([child.marginal_pos_Lx for child in node.clades if child.marginal_pos_Lx is not None]) # combine the different msgs and constraints if len(msgs_to_multiply)==0: # no information node.marginal_pos_Lx = None continue elif len(msgs_to_multiply)==1: node.subtree_distribution = msgs_to_multiply[0] else: # combine the different msgs and constraints node.subtree_distribution = Distribution.multiply(msgs_to_multiply) if node.up is None: # this is the root, set dates node.subtree_distribution._adjust_grid(rel_tol=self.rel_tol_prune) node.marginal_pos_Lx = node.subtree_distribution node.marginal_pos_LH = node.subtree_distribution self.tree.positional_marginal_LH = -node.subtree_distribution.peak_val else: # otherwise propagate to parent res, res_t = NodeInterpolator.convolve(node.subtree_distribution, node.branch_length_interpolator, max_or_integral='integral', n_grid_points = self.node_grid_points, n_integral=self.n_integral, rel_tol=self.rel_tol_refine) res._adjust_grid(rel_tol=self.rel_tol_prune) node.marginal_pos_Lx = res self.logger("ClockTree - Marginal reconstruction: Propagating root -> leaves...", 2) from scipy.interpolate import interp1d for node in self.tree.find_clades(order='preorder'): ## The root node if node.up is None: node.msg_from_parent = None # nothing beyond the root # all other cases (All internal nodes + unconstrained terminals) else: parent = node.up # messages from the complementary subtree (iterate over all sister nodes) complementary_msgs = [sister.marginal_pos_Lx for sister in parent.clades if (sister != node) and (sister.marginal_pos_Lx is not None)] # if parent itself got smth from the root node, include it if parent.msg_from_parent is not None: complementary_msgs.append(parent.msg_from_parent) elif parent.marginal_pos_Lx is not None: complementary_msgs.append(parent.marginal_pos_LH) if len(complementary_msgs): msg_parent_to_node = NodeInterpolator.multiply(complementary_msgs) msg_parent_to_node._adjust_grid(rel_tol=self.rel_tol_prune) else: x = [parent.numdate, numeric_date()] msg_parent_to_node = NodeInterpolator(x, [1.0, 1.0],min_width=self.min_width) # integral message, which delivers to the node the positional information # from the complementary subtree res, res_t = NodeInterpolator.convolve(msg_parent_to_node, node.branch_length_interpolator, max_or_integral='integral', inverse_time=False, n_grid_points = self.node_grid_points, n_integral=self.n_integral, rel_tol=self.rel_tol_refine) node.msg_from_parent = res if node.marginal_pos_Lx is None: node.marginal_pos_LH = node.msg_from_parent else: node.marginal_pos_LH = NodeInterpolator.multiply((node.msg_from_parent, node.subtree_distribution)) self.logger('ClockTree._ml_t_root_to_leaves: computed convolution' ' with %d points at node %s'%(len(res.x),node.name),4) if self.debug: tmp = np.diff(res.y-res.peak_val) nsign_changed = np.sum((tmp[1:]*tmp[:-1]<0)&(res.y[1:-1]-res.peak_val<500)) if nsign_changed>1: import matplotlib.pyplot as plt plt.ion() plt.plot(res.x, res.y-res.peak_val, '-o') plt.plot(res.peak_pos - node.branch_length_interpolator.x, node.branch_length_interpolator(node.branch_length_interpolator.x)-node.branch_length_interpolator.peak_val, '-o') plt.plot(msg_parent_to_node.x,msg_parent_to_node.y-msg_parent_to_node.peak_val, '-o') plt.ylim(0,100) plt.xlim(-0.05, 0.05) import ipdb; ipdb.set_trace() # assign positions of nodes and branch length only when desired # since marginal reconstruction can result in negative branch length if assign_dates: node.time_before_present = node.marginal_pos_LH.peak_pos if node.up: node.clock_length = node.up.time_before_present - node.time_before_present node.branch_length = node.clock_length # construct the inverse cumulant distribution to evaluate confidence intervals if node.marginal_pos_LH.is_delta: node.marginal_inverse_cdf=interp1d([0,1], node.marginal_pos_LH.peak_pos*np.ones(2), kind="linear") else: dt = np.diff(node.marginal_pos_LH.x) y = node.marginal_pos_LH.prob_relative(node.marginal_pos_LH.x) int_y = np.concatenate(([0], np.cumsum(dt*(y[1:]+y[:-1])/2.0))) int_y/=int_y[-1] node.marginal_inverse_cdf = interp1d(int_y, node.marginal_pos_LH.x, kind="linear") node.marginal_cdf = interp1d(node.marginal_pos_LH.x, int_y, kind="linear") if not self.debug: _cleanup() return
[ "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", "distributions", "are", "set", "as", "marginal_pos_LH", "attributes", "to", "the", "nodes", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L479-L648
[ "def", "_ml_t_marginal", "(", "self", ",", "assign_dates", "=", "False", ")", ":", "def", "_cleanup", "(", ")", ":", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "try", ":", "del", "node", ".", "marginal_pos_Lx", "del", "node", ".", "subtree_distribution", "del", "node", ".", "msg_from_parent", "#del node.marginal_pos_LH", "except", ":", "pass", "self", ".", "logger", "(", "\"ClockTree - Marginal reconstruction: Propagating leaves -> root...\"", ",", "2", ")", "# go through the nodes from leaves towards the root:", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'postorder'", ")", ":", "# children first, msg to parents", "if", "node", ".", "bad_branch", ":", "# no information", "node", ".", "marginal_pos_Lx", "=", "None", "else", ":", "# all other nodes", "if", "node", ".", "date_constraint", "is", "not", "None", "and", "node", ".", "date_constraint", ".", "is_delta", ":", "# there is a time constraint", "# initialize the Lx for nodes with precise date constraint:", "# subtree probability given the position of the parent node", "# position of the parent node is given by the branch length", "# distribution attached to the child node position", "node", ".", "subtree_distribution", "=", "node", ".", "date_constraint", "bl", "=", "node", ".", "branch_length_interpolator", ".", "x", "x", "=", "bl", "+", "node", ".", "date_constraint", ".", "peak_pos", "node", ".", "marginal_pos_Lx", "=", "Distribution", "(", "x", ",", "node", ".", "branch_length_interpolator", "(", "bl", ")", ",", "min_width", "=", "self", ".", "min_width", ",", "is_log", "=", "True", ")", "else", ":", "# all nodes without precise constraint but positional information", "# subtree likelihood given the node's constraint and child msg:", "msgs_to_multiply", "=", "[", "node", ".", "date_constraint", "]", "if", "node", ".", "date_constraint", "is", "not", "None", "else", "[", "]", "msgs_to_multiply", ".", "extend", "(", "[", "child", ".", "marginal_pos_Lx", "for", "child", "in", "node", ".", "clades", "if", "child", ".", "marginal_pos_Lx", "is", "not", "None", "]", ")", "# combine the different msgs and constraints", "if", "len", "(", "msgs_to_multiply", ")", "==", "0", ":", "# no information", "node", ".", "marginal_pos_Lx", "=", "None", "continue", "elif", "len", "(", "msgs_to_multiply", ")", "==", "1", ":", "node", ".", "subtree_distribution", "=", "msgs_to_multiply", "[", "0", "]", "else", ":", "# combine the different msgs and constraints", "node", ".", "subtree_distribution", "=", "Distribution", ".", "multiply", "(", "msgs_to_multiply", ")", "if", "node", ".", "up", "is", "None", ":", "# this is the root, set dates", "node", ".", "subtree_distribution", ".", "_adjust_grid", "(", "rel_tol", "=", "self", ".", "rel_tol_prune", ")", "node", ".", "marginal_pos_Lx", "=", "node", ".", "subtree_distribution", "node", ".", "marginal_pos_LH", "=", "node", ".", "subtree_distribution", "self", ".", "tree", ".", "positional_marginal_LH", "=", "-", "node", ".", "subtree_distribution", ".", "peak_val", "else", ":", "# otherwise propagate to parent", "res", ",", "res_t", "=", "NodeInterpolator", ".", "convolve", "(", "node", ".", "subtree_distribution", ",", "node", ".", "branch_length_interpolator", ",", "max_or_integral", "=", "'integral'", ",", "n_grid_points", "=", "self", ".", "node_grid_points", ",", "n_integral", "=", "self", ".", "n_integral", ",", "rel_tol", "=", "self", ".", "rel_tol_refine", ")", "res", ".", "_adjust_grid", "(", "rel_tol", "=", "self", ".", "rel_tol_prune", ")", "node", ".", "marginal_pos_Lx", "=", "res", "self", ".", "logger", "(", "\"ClockTree - Marginal reconstruction: Propagating root -> leaves...\"", ",", "2", ")", "from", "scipy", ".", "interpolate", "import", "interp1d", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'preorder'", ")", ":", "## The root node", "if", "node", ".", "up", "is", "None", ":", "node", ".", "msg_from_parent", "=", "None", "# nothing beyond the root", "# all other cases (All internal nodes + unconstrained terminals)", "else", ":", "parent", "=", "node", ".", "up", "# messages from the complementary subtree (iterate over all sister nodes)", "complementary_msgs", "=", "[", "sister", ".", "marginal_pos_Lx", "for", "sister", "in", "parent", ".", "clades", "if", "(", "sister", "!=", "node", ")", "and", "(", "sister", ".", "marginal_pos_Lx", "is", "not", "None", ")", "]", "# if parent itself got smth from the root node, include it", "if", "parent", ".", "msg_from_parent", "is", "not", "None", ":", "complementary_msgs", ".", "append", "(", "parent", ".", "msg_from_parent", ")", "elif", "parent", ".", "marginal_pos_Lx", "is", "not", "None", ":", "complementary_msgs", ".", "append", "(", "parent", ".", "marginal_pos_LH", ")", "if", "len", "(", "complementary_msgs", ")", ":", "msg_parent_to_node", "=", "NodeInterpolator", ".", "multiply", "(", "complementary_msgs", ")", "msg_parent_to_node", ".", "_adjust_grid", "(", "rel_tol", "=", "self", ".", "rel_tol_prune", ")", "else", ":", "x", "=", "[", "parent", ".", "numdate", ",", "numeric_date", "(", ")", "]", "msg_parent_to_node", "=", "NodeInterpolator", "(", "x", ",", "[", "1.0", ",", "1.0", "]", ",", "min_width", "=", "self", ".", "min_width", ")", "# integral message, which delivers to the node the positional information", "# from the complementary subtree", "res", ",", "res_t", "=", "NodeInterpolator", ".", "convolve", "(", "msg_parent_to_node", ",", "node", ".", "branch_length_interpolator", ",", "max_or_integral", "=", "'integral'", ",", "inverse_time", "=", "False", ",", "n_grid_points", "=", "self", ".", "node_grid_points", ",", "n_integral", "=", "self", ".", "n_integral", ",", "rel_tol", "=", "self", ".", "rel_tol_refine", ")", "node", ".", "msg_from_parent", "=", "res", "if", "node", ".", "marginal_pos_Lx", "is", "None", ":", "node", ".", "marginal_pos_LH", "=", "node", ".", "msg_from_parent", "else", ":", "node", ".", "marginal_pos_LH", "=", "NodeInterpolator", ".", "multiply", "(", "(", "node", ".", "msg_from_parent", ",", "node", ".", "subtree_distribution", ")", ")", "self", ".", "logger", "(", "'ClockTree._ml_t_root_to_leaves: computed convolution'", "' with %d points at node %s'", "%", "(", "len", "(", "res", ".", "x", ")", ",", "node", ".", "name", ")", ",", "4", ")", "if", "self", ".", "debug", ":", "tmp", "=", "np", ".", "diff", "(", "res", ".", "y", "-", "res", ".", "peak_val", ")", "nsign_changed", "=", "np", ".", "sum", "(", "(", "tmp", "[", "1", ":", "]", "*", "tmp", "[", ":", "-", "1", "]", "<", "0", ")", "&", "(", "res", ".", "y", "[", "1", ":", "-", "1", "]", "-", "res", ".", "peak_val", "<", "500", ")", ")", "if", "nsign_changed", ">", "1", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "plt", ".", "ion", "(", ")", "plt", ".", "plot", "(", "res", ".", "x", ",", "res", ".", "y", "-", "res", ".", "peak_val", ",", "'-o'", ")", "plt", ".", "plot", "(", "res", ".", "peak_pos", "-", "node", ".", "branch_length_interpolator", ".", "x", ",", "node", ".", "branch_length_interpolator", "(", "node", ".", "branch_length_interpolator", ".", "x", ")", "-", "node", ".", "branch_length_interpolator", ".", "peak_val", ",", "'-o'", ")", "plt", ".", "plot", "(", "msg_parent_to_node", ".", "x", ",", "msg_parent_to_node", ".", "y", "-", "msg_parent_to_node", ".", "peak_val", ",", "'-o'", ")", "plt", ".", "ylim", "(", "0", ",", "100", ")", "plt", ".", "xlim", "(", "-", "0.05", ",", "0.05", ")", "import", "ipdb", "ipdb", ".", "set_trace", "(", ")", "# assign positions of nodes and branch length only when desired", "# since marginal reconstruction can result in negative branch length", "if", "assign_dates", ":", "node", ".", "time_before_present", "=", "node", ".", "marginal_pos_LH", ".", "peak_pos", "if", "node", ".", "up", ":", "node", ".", "clock_length", "=", "node", ".", "up", ".", "time_before_present", "-", "node", ".", "time_before_present", "node", ".", "branch_length", "=", "node", ".", "clock_length", "# construct the inverse cumulant distribution to evaluate confidence intervals", "if", "node", ".", "marginal_pos_LH", ".", "is_delta", ":", "node", ".", "marginal_inverse_cdf", "=", "interp1d", "(", "[", "0", ",", "1", "]", ",", "node", ".", "marginal_pos_LH", ".", "peak_pos", "*", "np", ".", "ones", "(", "2", ")", ",", "kind", "=", "\"linear\"", ")", "else", ":", "dt", "=", "np", ".", "diff", "(", "node", ".", "marginal_pos_LH", ".", "x", ")", "y", "=", "node", ".", "marginal_pos_LH", ".", "prob_relative", "(", "node", ".", "marginal_pos_LH", ".", "x", ")", "int_y", "=", "np", ".", "concatenate", "(", "(", "[", "0", "]", ",", "np", ".", "cumsum", "(", "dt", "*", "(", "y", "[", "1", ":", "]", "+", "y", "[", ":", "-", "1", "]", ")", "/", "2.0", ")", ")", ")", "int_y", "/=", "int_y", "[", "-", "1", "]", "node", ".", "marginal_inverse_cdf", "=", "interp1d", "(", "int_y", ",", "node", ".", "marginal_pos_LH", ".", "x", ",", "kind", "=", "\"linear\"", ")", "node", ".", "marginal_cdf", "=", "interp1d", "(", "node", ".", "marginal_pos_LH", ".", "x", ",", "int_y", ",", "kind", "=", "\"linear\"", ")", "if", "not", "self", ".", "debug", ":", "_cleanup", "(", ")", "return" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree.convert_dates
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. Returns ------- None All manipulations are done in place on the tree
treetime/clock_tree.py
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. Returns ------- None All manipulations are done in place on the tree ''' from datetime import datetime, timedelta now = numeric_date() for node in self.tree.find_clades(): years_bp = self.date2dist.to_years(node.time_before_present) if years_bp < 0 and self.real_dates: if not hasattr(node, "bad_branch") or node.bad_branch is False: self.logger("ClockTree.convert_dates -- WARNING: The node is later than today, but it is not " "marked as \"BAD\", which indicates the error in the " "likelihood optimization.",4 , warn=True) else: self.logger("ClockTree.convert_dates -- WARNING: node which is marked as \"BAD\" optimized " "later than present day",4 , warn=True) node.numdate = now - years_bp # set the human-readable date year = np.floor(node.numdate) days = max(0,365.25 * (node.numdate - year)-1) try: # datetime will only operate on dates after 1900 n_date = datetime(year, 1, 1) + timedelta(days=days) node.date = datetime.strftime(n_date, "%Y-%m-%d") except: # this is the approximation not accounting for gap years etc n_date = datetime(1900, 1, 1) + timedelta(days=days) node.date = "%04d-%02d-%02d"%(year, n_date.month, n_date.day)
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. Returns ------- None All manipulations are done in place on the tree ''' from datetime import datetime, timedelta now = numeric_date() for node in self.tree.find_clades(): years_bp = self.date2dist.to_years(node.time_before_present) if years_bp < 0 and self.real_dates: if not hasattr(node, "bad_branch") or node.bad_branch is False: self.logger("ClockTree.convert_dates -- WARNING: The node is later than today, but it is not " "marked as \"BAD\", which indicates the error in the " "likelihood optimization.",4 , warn=True) else: self.logger("ClockTree.convert_dates -- WARNING: node which is marked as \"BAD\" optimized " "later than present day",4 , warn=True) node.numdate = now - years_bp # set the human-readable date year = np.floor(node.numdate) days = max(0,365.25 * (node.numdate - year)-1) try: # datetime will only operate on dates after 1900 n_date = datetime(year, 1, 1) + timedelta(days=days) node.date = datetime.strftime(n_date, "%Y-%m-%d") except: # this is the approximation not accounting for gap years etc n_date = datetime(1900, 1, 1) + timedelta(days=days) node.date = "%04d-%02d-%02d"%(year, n_date.month, n_date.day)
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L651-L687
[ "def", "convert_dates", "(", "self", ")", ":", "from", "datetime", "import", "datetime", ",", "timedelta", "now", "=", "numeric_date", "(", ")", "for", "node", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "years_bp", "=", "self", ".", "date2dist", ".", "to_years", "(", "node", ".", "time_before_present", ")", "if", "years_bp", "<", "0", "and", "self", ".", "real_dates", ":", "if", "not", "hasattr", "(", "node", ",", "\"bad_branch\"", ")", "or", "node", ".", "bad_branch", "is", "False", ":", "self", ".", "logger", "(", "\"ClockTree.convert_dates -- WARNING: The node is later than today, but it is not \"", "\"marked as \\\"BAD\\\", which indicates the error in the \"", "\"likelihood optimization.\"", ",", "4", ",", "warn", "=", "True", ")", "else", ":", "self", ".", "logger", "(", "\"ClockTree.convert_dates -- WARNING: node which is marked as \\\"BAD\\\" optimized \"", "\"later than present day\"", ",", "4", ",", "warn", "=", "True", ")", "node", ".", "numdate", "=", "now", "-", "years_bp", "# set the human-readable date", "year", "=", "np", ".", "floor", "(", "node", ".", "numdate", ")", "days", "=", "max", "(", "0", ",", "365.25", "*", "(", "node", ".", "numdate", "-", "year", ")", "-", "1", ")", "try", ":", "# datetime will only operate on dates after 1900", "n_date", "=", "datetime", "(", "year", ",", "1", ",", "1", ")", "+", "timedelta", "(", "days", "=", "days", ")", "node", ".", "date", "=", "datetime", ".", "strftime", "(", "n_date", ",", "\"%Y-%m-%d\"", ")", "except", ":", "# this is the approximation not accounting for gap years etc", "n_date", "=", "datetime", "(", "1900", ",", "1", ",", "1", ")", "+", "timedelta", "(", "days", "=", "days", ")", "node", ".", "date", "=", "\"%04d-%02d-%02d\"", "%", "(", "year", ",", "n_date", ".", "month", ",", "n_date", ".", "day", ")" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree.branch_length_to_years
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 All manipulations are done in place on the tree
treetime/clock_tree.py
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 All manipulations are done in place on the tree ''' self.logger('ClockTree.branch_length_to_years: setting node positions in units of years', 2) if not hasattr(self.tree.root, 'numdate'): self.logger('ClockTree.branch_length_to_years: infer ClockTree first', 2,warn=True) self.tree.root.branch_length = 0.1 for n in self.tree.find_clades(order='preorder'): if n.up is not None: n.branch_length = n.numdate - n.up.numdate
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 All manipulations are done in place on the tree ''' self.logger('ClockTree.branch_length_to_years: setting node positions in units of years', 2) if not hasattr(self.tree.root, 'numdate'): self.logger('ClockTree.branch_length_to_years: infer ClockTree first', 2,warn=True) self.tree.root.branch_length = 0.1 for n in self.tree.find_clades(order='preorder'): if n.up is not None: n.branch_length = n.numdate - n.up.numdate
[ "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", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L690-L707
[ "def", "branch_length_to_years", "(", "self", ")", ":", "self", ".", "logger", "(", "'ClockTree.branch_length_to_years: setting node positions in units of years'", ",", "2", ")", "if", "not", "hasattr", "(", "self", ".", "tree", ".", "root", ",", "'numdate'", ")", ":", "self", ".", "logger", "(", "'ClockTree.branch_length_to_years: infer ClockTree first'", ",", "2", ",", "warn", "=", "True", ")", "self", ".", "tree", ".", "root", ".", "branch_length", "=", "0.1", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", "order", "=", "'preorder'", ")", ":", "if", "n", ".", "up", "is", "not", "None", ":", "n", ".", "branch_length", "=", "n", ".", "numdate", "-", "n", ".", "up", ".", "numdate" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0
test
ClockTree.calc_rate_susceptibility
return the time tree estimation of evolutionary rates +/- one standard deviation form the ML estimate. Returns ------- TreeTime.return_code : str success or failure
treetime/clock_tree.py
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 or {} if rate_std is None: if not (self.clock_model['valid_confidence'] and 'cov' in self.clock_model): self.logger("ClockTree.calc_rate_susceptibility: need valid standard deviation of the clock rate to estimate dating error.", 1, warn=True) return ttconf.ERROR rate_std = np.sqrt(self.clock_model['cov'][0,0]) current_rate = np.abs(self.clock_model['slope']) upper_rate = self.clock_model['slope'] + rate_std lower_rate = max(0.1*current_rate, self.clock_model['slope'] - rate_std) for n in self.tree.find_clades(): if n.up: n._orig_gamma = n.branch_length_interpolator.gamma n.branch_length_interpolator.gamma = n._orig_gamma*upper_rate/current_rate self.logger("###ClockTree.calc_rate_susceptibility: run with upper bound of rate estimate", 1) self.make_time_tree(**params) self.logger("###ClockTree.calc_rate_susceptibility: rate: %f, LH:%f"%(upper_rate, self.tree.positional_joint_LH), 2) for n in self.tree.find_clades(): n.numdate_rate_variation = [(upper_rate, n.numdate)] if n.up: n.branch_length_interpolator.gamma = n._orig_gamma*lower_rate/current_rate self.logger("###ClockTree.calc_rate_susceptibility: run with lower bound of rate estimate", 1) self.make_time_tree(**params) self.logger("###ClockTree.calc_rate_susceptibility: rate: %f, LH:%f"%(lower_rate, self.tree.positional_joint_LH), 2) for n in self.tree.find_clades(): n.numdate_rate_variation.append((lower_rate, n.numdate)) if n.up: n.branch_length_interpolator.gamma = n._orig_gamma self.logger("###ClockTree.calc_rate_susceptibility: run with central rate estimate", 1) self.make_time_tree(**params) self.logger("###ClockTree.calc_rate_susceptibility: rate: %f, LH:%f"%(current_rate, self.tree.positional_joint_LH), 2) for n in self.tree.find_clades(): n.numdate_rate_variation.append((current_rate, n.numdate)) n.numdate_rate_variation.sort(key=lambda x:x[1]) # sort estimates for different rates by numdate return ttconf.SUCCESS
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 or {} if rate_std is None: if not (self.clock_model['valid_confidence'] and 'cov' in self.clock_model): self.logger("ClockTree.calc_rate_susceptibility: need valid standard deviation of the clock rate to estimate dating error.", 1, warn=True) return ttconf.ERROR rate_std = np.sqrt(self.clock_model['cov'][0,0]) current_rate = np.abs(self.clock_model['slope']) upper_rate = self.clock_model['slope'] + rate_std lower_rate = max(0.1*current_rate, self.clock_model['slope'] - rate_std) for n in self.tree.find_clades(): if n.up: n._orig_gamma = n.branch_length_interpolator.gamma n.branch_length_interpolator.gamma = n._orig_gamma*upper_rate/current_rate self.logger("###ClockTree.calc_rate_susceptibility: run with upper bound of rate estimate", 1) self.make_time_tree(**params) self.logger("###ClockTree.calc_rate_susceptibility: rate: %f, LH:%f"%(upper_rate, self.tree.positional_joint_LH), 2) for n in self.tree.find_clades(): n.numdate_rate_variation = [(upper_rate, n.numdate)] if n.up: n.branch_length_interpolator.gamma = n._orig_gamma*lower_rate/current_rate self.logger("###ClockTree.calc_rate_susceptibility: run with lower bound of rate estimate", 1) self.make_time_tree(**params) self.logger("###ClockTree.calc_rate_susceptibility: rate: %f, LH:%f"%(lower_rate, self.tree.positional_joint_LH), 2) for n in self.tree.find_clades(): n.numdate_rate_variation.append((lower_rate, n.numdate)) if n.up: n.branch_length_interpolator.gamma = n._orig_gamma self.logger("###ClockTree.calc_rate_susceptibility: run with central rate estimate", 1) self.make_time_tree(**params) self.logger("###ClockTree.calc_rate_susceptibility: rate: %f, LH:%f"%(current_rate, self.tree.positional_joint_LH), 2) for n in self.tree.find_clades(): n.numdate_rate_variation.append((current_rate, n.numdate)) n.numdate_rate_variation.sort(key=lambda x:x[1]) # sort estimates for different rates by numdate return ttconf.SUCCESS
[ "return", "the", "time", "tree", "estimation", "of", "evolutionary", "rates", "+", "/", "-", "one", "standard", "deviation", "form", "the", "ML", "estimate", "." ]
neherlab/treetime
python
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/clock_tree.py#L710-L757
[ "def", "calc_rate_susceptibility", "(", "self", ",", "rate_std", "=", "None", ",", "params", "=", "None", ")", ":", "params", "=", "params", "or", "{", "}", "if", "rate_std", "is", "None", ":", "if", "not", "(", "self", ".", "clock_model", "[", "'valid_confidence'", "]", "and", "'cov'", "in", "self", ".", "clock_model", ")", ":", "self", ".", "logger", "(", "\"ClockTree.calc_rate_susceptibility: need valid standard deviation of the clock rate to estimate dating error.\"", ",", "1", ",", "warn", "=", "True", ")", "return", "ttconf", ".", "ERROR", "rate_std", "=", "np", ".", "sqrt", "(", "self", ".", "clock_model", "[", "'cov'", "]", "[", "0", ",", "0", "]", ")", "current_rate", "=", "np", ".", "abs", "(", "self", ".", "clock_model", "[", "'slope'", "]", ")", "upper_rate", "=", "self", ".", "clock_model", "[", "'slope'", "]", "+", "rate_std", "lower_rate", "=", "max", "(", "0.1", "*", "current_rate", ",", "self", ".", "clock_model", "[", "'slope'", "]", "-", "rate_std", ")", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "if", "n", ".", "up", ":", "n", ".", "_orig_gamma", "=", "n", ".", "branch_length_interpolator", ".", "gamma", "n", ".", "branch_length_interpolator", ".", "gamma", "=", "n", ".", "_orig_gamma", "*", "upper_rate", "/", "current_rate", "self", ".", "logger", "(", "\"###ClockTree.calc_rate_susceptibility: run with upper bound of rate estimate\"", ",", "1", ")", "self", ".", "make_time_tree", "(", "*", "*", "params", ")", "self", ".", "logger", "(", "\"###ClockTree.calc_rate_susceptibility: rate: %f, LH:%f\"", "%", "(", "upper_rate", ",", "self", ".", "tree", ".", "positional_joint_LH", ")", ",", "2", ")", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "n", ".", "numdate_rate_variation", "=", "[", "(", "upper_rate", ",", "n", ".", "numdate", ")", "]", "if", "n", ".", "up", ":", "n", ".", "branch_length_interpolator", ".", "gamma", "=", "n", ".", "_orig_gamma", "*", "lower_rate", "/", "current_rate", "self", ".", "logger", "(", "\"###ClockTree.calc_rate_susceptibility: run with lower bound of rate estimate\"", ",", "1", ")", "self", ".", "make_time_tree", "(", "*", "*", "params", ")", "self", ".", "logger", "(", "\"###ClockTree.calc_rate_susceptibility: rate: %f, LH:%f\"", "%", "(", "lower_rate", ",", "self", ".", "tree", ".", "positional_joint_LH", ")", ",", "2", ")", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "n", ".", "numdate_rate_variation", ".", "append", "(", "(", "lower_rate", ",", "n", ".", "numdate", ")", ")", "if", "n", ".", "up", ":", "n", ".", "branch_length_interpolator", ".", "gamma", "=", "n", ".", "_orig_gamma", "self", ".", "logger", "(", "\"###ClockTree.calc_rate_susceptibility: run with central rate estimate\"", ",", "1", ")", "self", ".", "make_time_tree", "(", "*", "*", "params", ")", "self", ".", "logger", "(", "\"###ClockTree.calc_rate_susceptibility: rate: %f, LH:%f\"", "%", "(", "current_rate", ",", "self", ".", "tree", ".", "positional_joint_LH", ")", ",", "2", ")", "for", "n", "in", "self", ".", "tree", ".", "find_clades", "(", ")", ":", "n", ".", "numdate_rate_variation", ".", "append", "(", "(", "current_rate", ",", "n", ".", "numdate", ")", ")", "n", ".", "numdate_rate_variation", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", "# sort estimates for different rates by numdate", "return", "ttconf", ".", "SUCCESS" ]
f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0