_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q273000 | Coalescent.attach_to_tree | test | def attach_to_tree(self):
'''
attaches the the merger cost to each branch length interpolator in the tree.
| python | {
"resource": ""
} |
q273001 | Coalescent.optimize_Tc | test | def optimize_Tc(self):
'''
determines the coalescent time scale that optimizes the coalescent likelihood of the tree
'''
from scipy.optimize import minimize_scalar
initial_Tc = self.Tc
def cost(Tc):
self.set_Tc(Tc)
return -self.total_LH()
sol = minimize_scalar(cost, bounds=[ttconf.TINY_NUMBER,10.0])
if | python | {
"resource": ""
} |
q273002 | prof2seq | test | 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: | python | {
"resource": ""
} |
q273003 | normalize_profile | test | 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 | python | {
"resource": ""
} |
q273004 | TreeAnc.gtr | test | def gtr(self, value):
"""
Set a new GTR object
Parameters
-----------
value : GTR
| python | {
"resource": ""
} |
q273005 | TreeAnc.set_gtr | test | 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):
| python | {
"resource": ""
} |
q273006 | TreeAnc.seq_len | test | 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 | python | {
"resource": ""
} |
q273007 | TreeAnc._attach_sequences_to_nodes | test | 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
| python | {
"resource": ""
} |
q273008 | TreeAnc.prepare_tree | test | 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
| python | {
"resource": ""
} |
q273009 | TreeAnc._prepare_nodes | test | 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:
| python | {
"resource": ""
} |
q273010 | TreeAnc._calc_dist2root | test | 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:
| python | {
"resource": ""
} |
q273011 | TreeAnc.reconstruct_anc | test | 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)
| python | {
"resource": ""
} |
q273012 | TreeAnc.get_branch_mutation_matrix | test | 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))
| python | {
"resource": ""
} |
q273013 | TreeAnc.expanded_sequence | test | 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 | python | {
"resource": ""
} |
q273014 | TreeAnc._fitch_anc | test | 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:
| python | {
"resource": ""
} |
q273015 | TreeAnc._fitch_state | test | 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.
| python | {
"resource": ""
} |
q273016 | TreeAnc._fitch_intersect | test | 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
| python | {
"resource": ""
} |
q273017 | TreeAnc.sequence_LH | test | 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"):
| python | {
"resource": ""
} |
q273018 | TreeAnc.ancestral_likelihood | test | 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
| python | {
"resource": ""
} |
q273019 | TreeAnc._branch_length_to_gtr | test | 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 | python | {
"resource": ""
} |
q273020 | TreeAnc.optimize_branch_length | test | 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)
| python | {
"resource": ""
} |
q273021 | TreeAnc.optimize_branch_length_global | test | 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))
| python | {
"resource": ""
} |
q273022 | TreeAnc.optimal_branch_length | test | 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'],
| python | {
"resource": ""
} |
q273023 | TreeAnc.optimize_seq_and_branch_len | test | 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,
| python | {
"resource": ""
} |
q273024 | TreeAnc.get_reconstructed_alignment | test | 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)
| python | {
"resource": ""
} |
q273025 | GTR_site_specific.Q | test | 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 | python | {
"resource": ""
} |
q273026 | GTR_site_specific.custom | test | 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
| python | {
"resource": ""
} |
q273027 | GTR.standard | test | 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
| python | {
"resource": ""
} |
q273028 | GTR._check_fix_Q | test | 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
| python | {
"resource": ""
} |
q273029 | GTR.prob_t_compressed | test | 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
| python | {
"resource": ""
} |
q273030 | GTR.optimal_t | test | 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.
| python | {
"resource": ""
} |
q273031 | GTR.optimal_t_compressed | test | 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:
| python | {
"resource": ""
} |
q273032 | GTR.prob_t_profiles | test | 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])
| python | {
"resource": ""
} |
q273033 | GTR.evolve | test | 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
| python | {
"resource": ""
} |
q273034 | GTR.sequence_logLH | test | 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
"""
| python | {
"resource": ""
} |
q273035 | TreeTime._set_branch_length_mode | test | 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]
| python | {
"resource": ""
} |
q273036 | TreeTime.clock_filter | test | 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:
| python | {
"resource": ""
} |
q273037 | TreeTime.plot_root_to_tip | test | 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
| python | {
"resource": ""
} |
q273038 | TreeTime.resolve_polytomies | test | 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)
| python | {
"resource": ""
} |
q273039 | TreeTime.print_lh | test | 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
| python | {
"resource": ""
} |
q273040 | TreeTime.add_coalescent_model | test | 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,
| python | {
"resource": ""
} |
q273041 | TreeTime._find_best_root | test | 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
| python | {
"resource": ""
} |
q273042 | assure_tree | test | 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'
| python | {
"resource": ""
} |
q273043 | create_gtr | test | 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]
| python | {
"resource": ""
} |
q273044 | read_if_vcf | test | 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']
| python | {
"resource": ""
} |
q273045 | ancestral_reconstruction | test | 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',
| python | {
"resource": ""
} |
q273046 | Distribution.calc_fwhm | test | 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
| python | {
"resource": ""
} |
q273047 | Distribution.delta_function | test | def delta_function(cls, x_pos, weight=1., min_width=MIN_INTEGRATION_PEAK):
"""
Create delta function distribution.
"""
| python | {
"resource": ""
} |
q273048 | Distribution.multiply | test | 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
| python | {
"resource": ""
} |
q273049 | ClockTree._assign_dates | test | 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:
| python | {
"resource": ""
} |
q273050 | ClockTree.setup_TreeRegression | test | 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 | python | {
"resource": ""
} |
q273051 | ClockTree.make_time_tree | test | 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
| python | {
"resource": ""
} |
q273052 | ClockTree.timetree_likelihood | test | 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 | python | {
"resource": ""
} |
q273053 | ClockTree.convert_dates | test | 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 " | python | {
"resource": ""
} |
q273054 | ClockTree.date_uncertainty_due_to_rate | test | def date_uncertainty_due_to_rate(self, node, interval=(0.05, 0.095)):
"""use previously calculated variation of the rate to estimate
the uncertainty in a particular numdate due to rate variation.
Parameters
----------
node : PhyloTree.Clade
node for which the confidence interval is to be calculated
interval : tuple, optional
Array of length two, or tuple, defining the bounds of the confidence interval
"""
if hasattr(node, "numdate_rate_variation"):
from scipy.special import | python | {
"resource": ""
} |
q273055 | ClockTree.get_max_posterior_region | test | def get_max_posterior_region(self, node, fraction = 0.9):
'''
If temporal reconstruction was done using the marginal ML mode, the entire distribution of
times is available. This function determines the interval around the highest
posterior probability region that contains the specified fraction of the probability mass.
In absense of marginal reconstruction, it will return uncertainty based on rate
variation. If both are present, the wider interval will be returned.
Parameters
----------
node : PhyloTree.Clade
The node for which the posterior region is to be calculated
interval : float
Float specifying who much of the posterior probability is
to be contained in the region
Returns
-------
max_posterior_region : numpy array
Array with two numerical dates delineating the high posterior region
'''
if node.marginal_inverse_cdf=="delta":
return np.array([node.numdate, node.numdate])
min_max = (node.marginal_pos_LH.xmin, node.marginal_pos_LH.xmax)
min_date, max_date = [self.date2dist.to_numdate(x) for x in min_max][::-1]
if node.marginal_pos_LH.peak_pos == min_max[0]: #peak on the left
return self.get_confidence_interval(node, (0, fraction))
| python | {
"resource": ""
} |
q273056 | min_interp | test | def min_interp(interp_object):
"""
Find the global minimum of a function represented as an interpolation object.
"""
try:
return interp_object.x[interp_object(interp_object.x).argmin()]
except Exception as e:
s = | python | {
"resource": ""
} |
q273057 | median_interp | test | def median_interp(interp_object):
"""
Find the median of the function represented as an interpolation object.
"""
new_grid = np.sort(np.concatenate([interp_object.x[:-1] + 0.1*ii*np.diff(interp_object.x)
for ii in range(10)]).flatten())
| python | {
"resource": ""
} |
q273058 | numeric_date | test | def numeric_date(dt=None):
"""
Convert datetime object to the numeric date.
The numeric date format is YYYY.F, where F is the fraction of the year passed
Parameters
----------
dt: datetime.datetime, None
date of to be converted. if None, assume today
"""
| python | {
"resource": ""
} |
q273059 | DateConversion.from_regression | test | def from_regression(cls, clock_model):
"""
Create the conversion object automatically from the tree
Parameters
----------
clock_model : dict
dictionary as returned from TreeRegression with fields intercept and slope
"""
dc = cls()
dc.clock_rate = clock_model['slope']
dc.intercept = clock_model['intercept']
dc.chisq = clock_model['chisq'] if | python | {
"resource": ""
} |
q273060 | GuacamoleClient.client | test | def client(self):
"""
Socket connection.
"""
if not self._client:
self._client = socket.create_connection(
| python | {
"resource": ""
} |
q273061 | GuacamoleClient.close | test | def close(self):
"""
Terminate connection with Guacamole guacd server.
"""
self.client.close()
| python | {
"resource": ""
} |
q273062 | GuacamoleClient.receive | test | def receive(self):
"""
Receive instructions from Guacamole guacd server.
"""
start = 0
while True:
idx = self._buffer.find(INST_TERM.encode(), start)
if idx != -1:
# instruction was fully received!
line = self._buffer[:idx + 1].decode()
self._buffer = self._buffer[idx + 1:]
self.logger.debug('Received instruction: %s' % line)
return line
else:
start = len(self._buffer)
| python | {
"resource": ""
} |
q273063 | GuacamoleClient.send | test | def send(self, data):
"""
Send encoded instructions to Guacamole guacd server.
"""
| python | {
"resource": ""
} |
q273064 | GuacamoleClient.send_instruction | test | def send_instruction(self, instruction):
"""
Send instruction after encoding.
"""
self.logger.debug('Sending | python | {
"resource": ""
} |
q273065 | GuacamoleClient.handshake | test | def handshake(self, protocol='vnc', width=1024, height=768, dpi=96,
audio=None, video=None, image=None, **kwargs):
"""
Establish connection with Guacamole guacd server via handshake.
"""
if protocol not in PROTOCOLS:
self.logger.debug('Invalid protocol: %s' % protocol)
raise GuacamoleError('Cannot start Handshake. Missing protocol.')
if audio is None:
audio = list()
if video is None:
video = list()
if image is None:
image = list()
# 1. Send 'select' instruction
self.logger.debug('Send `select` instruction.')
self.send_instruction(Instruction('select', protocol))
# 2. Receive `args` instruction
instruction = self.read_instruction()
self.logger.debug('Expecting `args` instruction, received: %s'
% str(instruction))
if not instruction:
self.close()
raise GuacamoleError(
'Cannot establish Handshake. Connection Lost!')
if instruction.opcode != 'args':
self.close()
raise GuacamoleError(
'Cannot establish Handshake. Expected opcode `args`, '
'received `%s` instead.' % instruction.opcode)
# 3. Respond with size, audio & video support
self.logger.debug('Send `size` instruction (%s, %s, %s)'
% (width, height, dpi))
self.send_instruction(Instruction('size', width, height, dpi))
self.logger.debug('Send `audio` instruction (%s)' % audio)
| python | {
"resource": ""
} |
q273066 | utf8 | test | def utf8(unicode_str):
"""
Return a utf-8 encoded string from a valid unicode string.
:param unicode_str: Unicode string.
:return: str
"""
| python | {
"resource": ""
} |
q273067 | GuacamoleInstruction.load | test | def load(cls, instruction):
"""
Loads a new GuacamoleInstruction from encoded instruction string.
:param instruction: Instruction string.
:return: GuacamoleInstruction()
| python | {
"resource": ""
} |
q273068 | GuacamoleInstruction.encode_arg | test | def encode_arg(arg):
"""
Encode argument to be sent in a valid GuacamoleInstruction.
example:
>> arg = encode_arg('size')
>> arg == '4.size'
>> True
:param arg: arg string.
| python | {
"resource": ""
} |
q273069 | GuacamoleInstruction.encode | test | def encode(self):
"""
Prepare the instruction to be sent over the wire.
:return: str
"""
instruction_iter = itertools.chain([self.opcode], self.args)
| python | {
"resource": ""
} |
q273070 | APIResource.class_url | test | def class_url(cls):
"""Returns a versioned URI string for this class"""
base = 'v{0}'.format(getattr(cls, 'RESOURCE_VERSION', '1'))
| python | {
"resource": ""
} |
q273071 | APIResource.instance_url | test | def instance_url(self):
"""Get instance URL by ID"""
id_ = self.get(self.ID_ATTR)
base = self.class_url()
if id_:
return '/'.join([base, six.text_type(id_)])
else:
raise Exception(
| python | {
"resource": ""
} |
q273072 | SingletonAPIResource.class_url | test | def class_url(cls):
"""
Returns a versioned URI string for this class,
and don't pluralize the class name.
"""
base | python | {
"resource": ""
} |
q273073 | DownloadableAPIResource.download | test | def download(self, path=None, **kwargs):
"""
Download the file to the specified directory or file path.
Downloads to a temporary directory if no path is specified.
Returns the absolute path to the file.
"""
download_url = self.download_url(**kwargs)
try:
# For vault objects, use the object's filename
# as the fallback if none is specified.
filename = self.filename
except AttributeError:
# If the object has no filename attribute,
# extract one from the download URL.
filename = download_url.split('%3B%20filename%3D')[1]
# Remove additional URL params from the name and "unquote" it.
filename = unquote(filename.split('&')[0])
if path:
path = os.path.expanduser(path)
# If the path is a dir, use the extracted filename
if os.path.isdir(path):
path = os.path.join(path, filename)
else:
| python | {
"resource": ""
} |
q273074 | DatasetCommit.parent_object | test | def parent_object(self):
""" Get the commit objects parent Import or Migration """
from . import types
| python | {
"resource": ""
} |
q273075 | _ask_for_credentials | test | def _ask_for_credentials():
"""
Asks the user for their email and password.
"""
_print_msg('Please enter your SolveBio credentials')
domain = raw_input('Domain (e.g. <domain>.solvebio.com): ')
# Check to see if this domain supports password authentication
try:
account = client.request('get', '/p/accounts/{}'.format(domain))
auth = account['authentication']
except:
raise SolveError('Invalid domain: {}'.format(domain))
# Account must support password-based login
if auth.get('login') or auth.get('SAML', | python | {
"resource": ""
} |
q273076 | interactive_login | test | def interactive_login():
"""
Force an interactive login via the command line.
Sets the global API key and updates the client auth.
"""
solvebio.access_token = None
solvebio.api_key = None
client.set_token()
domain, email, password = _ask_for_credentials()
if not all([domain, email, password]):
print("Domain, email, and password are all required.")
return
try:
| python | {
"resource": ""
} |
q273077 | whoami | test | def whoami(*args, **kwargs):
"""
Prints information about the current user.
Assumes the user is already logged-in.
"""
user = client.whoami()
| python | {
"resource": ""
} |
q273078 | print_user | test | def print_user(user):
"""
Prints information about the current user.
"""
email = user['email']
domain = | python | {
"resource": ""
} |
q273079 | Query.filter | test | def filter(self, *filters, **kwargs):
"""
Returns this Query instance with the query args combined with
existing set with AND.
kwargs are simply passed to a new Filter object and combined to any
other filters with AND.
By default, everything is combined using AND. If you provide
multiple | python | {
"resource": ""
} |
q273080 | Query.range | test | def range(self, chromosome, start, stop, exact=False):
"""
Shortcut to do range filters on genomic datasets.
"""
| python | {
"resource": ""
} |
q273081 | Query.position | test | def position(self, chromosome, position, exact=False):
"""
Shortcut to do a single position filter on genomic datasets.
"""
| python | {
"resource": ""
} |
q273082 | Query.facets | test | def facets(self, *args, **kwargs):
"""
Returns a dictionary with the requested facets.
The facets function supports string args, and keyword
args.
q.facets('field_1', 'field_2') will return facets for
field_1 and field_2.
q.facets(field_1={'limit': 0}, field_2={'limit': 10})
will return all facets for field_1 and 10 facets for field_2.
"""
# Combine args and kwargs into facet format.
facets = dict((a, {}) for a in args)
facets.update(kwargs)
if not facets:
| python | {
"resource": ""
} |
q273083 | Query._process_filters | test | def _process_filters(cls, filters):
"""Takes a list of filters and returns JSON
:Parameters:
- `filters`: List of Filters, (key, val) tuples, or dicts
Returns: List of JSON API filters
"""
data = []
# Filters should always be a list
for f in filters:
if isinstance(f, Filter):
if f.filters:
data.extend(cls._process_filters(f.filters))
elif isinstance(f, dict):
key = list(f.keys())[0]
val = f[key]
if isinstance(val, dict):
# pass val (a dict) as list
# so that it gets processed properly
| python | {
"resource": ""
} |
q273084 | Query.next | test | def next(self):
"""
Allows the Query object to be an iterable.
This method will iterate through a cached result set
and fetch successive pages as required.
A `StopIteration` exception will be raised when there aren't
any more results available or when the requested result
slice range or limit has been fetched.
Returns: The next result.
"""
if not hasattr(self, '_cursor'):
# Iterator not initialized yet
self.__iter__()
| python | {
"resource": ""
} |
q273085 | Query.execute | test | def execute(self, offset=0, **query):
"""
Executes a query. Additional query parameters can be passed
as keyword arguments.
Returns: The request parameters and the raw query response.
"""
_params = self._build_query(**query)
self._page_offset = offset
_params.update(
offset=self._page_offset,
limit=min(self._page_size, self._limit)
)
logger.debug('executing query. from/limit: %6d/%d' %
(_params['offset'], _params['limit']))
# If the request results in a SolveError (ie bad filter) set the | python | {
"resource": ""
} |
q273086 | Query.migrate | test | def migrate(self, target, follow=True, **kwargs):
"""
Migrate the data from the Query to a target dataset.
Valid optional kwargs include:
* target_fields
* include_errors
* validation_params
* metadata
* commit_mode
"""
from solvebio import Dataset
from solvebio import DatasetMigration
# Target can be provided as a Dataset, or as an ID.
if isinstance(target, Dataset):
| python | {
"resource": ""
} |
q273087 | main | test | def main(argv=sys.argv[1:]):
""" Main entry point for SolveBio CLI """
parser = SolveArgumentParser()
args = parser.parse_solvebio_args(argv)
if args.api_host:
solvebio.api_host = args.api_host
if args.api_key:
solvebio.api_key = args.api_key
| python | {
"resource": ""
} |
q273088 | download_vault_folder | test | def download_vault_folder(remote_path, local_path, dry_run=False, force=False):
"""Recursively downloads a folder in a vault to a local directory.
Only downloads files, not datasets."""
local_path = os.path.normpath(os.path.expanduser(local_path))
if not os.access(local_path, os.W_OK):
raise Exception(
'Write access to local path ({}) is required'
.format(local_path))
full_path, path_dict = solvebio.Object.validate_full_path(remote_path)
vault = solvebio.Vault.get_by_full_path(path_dict['vault'])
print('Downloading all files from {} to {}'.format(full_path, local_path))
if path_dict['path'] == '/':
parent_object_id = None
else:
parent_object = solvebio.Object.get_by_full_path(
remote_path, assert_type='folder')
parent_object_id = parent_object.id
# Scan the folder for all sub-folders and create them locally
print('Creating local directory structure at: {}'.format(local_path))
if not os.path.exists(local_path):
if not dry_run:
os.makedirs(local_path)
folders = vault.folders(parent_object_id=parent_object_id)
for f in folders:
path = os.path.normpath(local_path + f.path)
if not os.path.exists(path):
print('Creating folder: {}'.format(path))
if not dry_run:
| python | {
"resource": ""
} |
q273089 | SolveObject.construct_from | test | def construct_from(cls, values, **kwargs):
"""Used to create a new object from an HTTP response"""
| python | {
"resource": ""
} |
q273090 | SolveBioAuth.logout | test | def logout(self):
"""Revoke the token and remove the cookie."""
if self._oauth_client_secret:
try:
oauth_token = flask.request.cookies[self.TOKEN_COOKIE_NAME]
# Revoke the token
requests.post(
urljoin(self._api_host, self.OAUTH2_REVOKE_TOKEN_PATH),
data={
'client_id': self._oauth_client_id,
| python | {
"resource": ""
} |
q273091 | SolveClient.request | test | def request(self, method, url, **kwargs):
"""
Issues an HTTP Request across the wire via the Python requests
library.
Parameters
----------
method : str
an HTTP method: GET, PUT, POST, DELETE, ...
url : str
the place to connect to. If the url doesn't start
with a protocol (https:// or http://), we'll slap
solvebio.api_host in the front.
allow_redirects: bool, optional
set *False* we won't follow any redirects
headers: dict, optional
Custom headers can be provided here; generally though this
will be set correctly by default dependent on the
method type. If the content type is JSON, we'll
JSON-encode params.
param : dict, optional
passed as *params* in the requests.request
timeout : int, optional
timeout value in seconds for the request
raw: bool, optional
unless *True* the response encoded to json
files: file
File content in the form of a file handle which is to be
uploaded. Files are passed in POST requests
Returns
-------
response object. If *raw* is not *True* and
repsonse if valid the object will be JSON encoded. Otherwise
it will be the request.reposne object.
"""
opts = {
'allow_redirects': True,
'auth': self._auth,
'data': {},
'files': None,
'headers': dict(self._headers),
'params': {},
'timeout': 80,
'verify': True
}
raw = kwargs.pop('raw', False)
debug = kwargs.pop('debug', False)
opts.update(kwargs)
method = method.upper()
if opts['files']:
# Don't use application/json for file uploads or GET requests
| python | {
"resource": ""
} |
q273092 | Task.child_object | test | def child_object(self):
""" Get Task child object class """
from . import types
child_klass | python | {
"resource": ""
} |
q273093 | Task.cancel | test | def cancel(self):
""" Cancel a task """
_status = self.status
self.status = "canceled"
try:
self.save()
except:
# Reset | python | {
"resource": ""
} |
q273094 | ExpandingVCFParser._parse_info_snpeff | test | def _parse_info_snpeff(self, info):
"""
Specialized INFO field parser for SnpEff ANN fields.
Requires self._snpeff_ann_fields to be set.
"""
ann = info.pop('ANN', []) or []
# Overwrite the existing ANN with something parsed
# Split on '|', merge with the ANN keys parsed above.
# Ensure empty values are None rather than empty string.
items = []
| python | {
"resource": ""
} |
q273095 | ExpandingVCFParser.row_to_dict | test | def row_to_dict(self, row, allele, alternate_alleles):
"""Return a parsed dictionary for JSON."""
def _variant_sbid(**kwargs):
"""Generates a SolveBio variant ID (SBID)."""
return '{build}-{chromosome}-{start}-{stop}-{allele}'\
.format(**kwargs).upper()
if allele == '.':
# Try to use the ref, if '.' is supplied for alt.
allele = row.REF or allele
genomic_coordinates = {
'build': self.genome_build,
'chromosome': row.CHROM,
'start': row.POS,
'stop': row.POS + len(row.REF) - 1
}
# SolveBio standard variant format
variant_sbid = _variant_sbid(allele=allele,
**genomic_coordinates)
return {
| python | {
"resource": ""
} |
q273096 | get_credentials | test | def get_credentials():
"""
Returns the user's stored API key if a valid credentials file is found.
Raises CredentialsError if no valid credentials file is found.
"""
try:
netrc_path = netrc.path()
auths = | python | {
"resource": ""
} |
q273097 | netrc.save | test | def save(self, path):
"""Dump the class data in the format of a .netrc file."""
rep = ""
for host in self.hosts.keys():
attrs = self.hosts[host]
rep = rep + "machine " + host + "\n\tlogin " \
+ six.text_type(attrs[0]) + "\n"
if attrs[1]:
rep = rep + "account " + six.text_type(attrs[1])
rep = rep + "\tpassword " + six.text_type(attrs[2]) + "\n"
for macro in self.macros.keys():
| python | {
"resource": ""
} |
q273098 | _format | test | def _format(val, valtype, floatfmt, missingval=""):
"""
Format a value accoding to its type.
Unicode is supported:
>>> hrow = ['\u0431\u0443\u043a\u0432\u0430', \
'\u0446\u0438\u0444\u0440\u0430'] ; \
tbl = [['\u0430\u0437', 2], ['\u0431\u0443\u043a\u0438', 4]] ; \
good_result = '\\u0431\\u0443\\u043a\\u0432\\u0430 \
\\u0446\\u0438\\u0444\\u0440\\u0430\\n-------\
-------\\n\\u0430\\u0437 \
| python | {
"resource": ""
} |
q273099 | _normalize_tabular_data | test | def _normalize_tabular_data(tabular_data, headers, sort=True):
"""
Transform a supported data type to a list of lists, and a list of headers.
Supported tabular data types:
* list-of-lists or another iterable of iterables
* 2D NumPy arrays
* dict of iterables (usually used with headers="keys")
* pandas.DataFrame (usually used with headers="keys")
The first row can be used as headers if headers="firstrow",
column indices can be used as headers if headers="keys".
"""
if hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"):
# dict-like and pandas.DataFrame?
if hasattr(tabular_data.values, "__call__"):
# likely a conventional dict
keys = list(tabular_data.keys())
# columns have to be transposed
rows = list(izip_longest(*list(tabular_data.values())))
elif hasattr(tabular_data, "index"):
# values is a property, has .index then
# it's likely a pandas.DataFrame (pandas 0.11.0)
keys = list(tabular_data.keys())
# values matrix doesn't need to be transposed
vals = tabular_data.values
names = tabular_data.index
rows = [[v] + list(row) for v, row in zip(names, vals)]
else:
raise ValueError("tabular data doesn't appear to be a dict "
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.