Search is not available for this dataset
text stringlengths 75 104k |
|---|
def compare(expr, value, regex_expr=False):
"""
Compares an string or regular expression againast a given value.
Arguments:
expr (str|regex): string or regular expression value to compare.
value (str): value to compare against to.
regex_expr (bool, optional): enables string based re... |
def trigger_methods(instance, args):
""""
Triggers specific class methods using a simple reflection
mechanism based on the given input dictionary params.
Arguments:
instance (object): target instance to dynamically trigger methods.
args (iterable): input arguments to trigger objects to
... |
def match(self, request):
"""
Match the given HTTP request instance against the registered
matcher functions in the current engine.
Arguments:
request (pook.Request): outgoing request to match.
Returns:
tuple(bool, list[Exception]): ``True`` if all match... |
def get(name):
"""
Returns a matcher instance by class or alias name.
Arguments:
name (str): matcher class name or alias.
Returns:
matcher: found matcher instance, otherwise ``None``.
"""
for matcher in matchers:
if matcher.__name__ == name or getattr(matcher, 'name', N... |
def init(name, *args):
"""
Initializes a matcher instance passing variadic arguments to
its constructor. Acts as a delegator proxy.
Arguments:
name (str): matcher class name or alias to execute.
*args (mixed): variadic argument
Returns:
matcher: matcher instance.
Raise... |
def header(self, key, value):
"""
Defines a new response header.
Alias to ``Response.header()``.
Arguments:
header (str): header name.
value (str): header value.
Returns:
self: ``pook.Response`` current instance.
"""
if type(k... |
def body(self, body):
"""
Defines response body data.
Arguments:
body (str|bytes): response body to use.
Returns:
self: ``pook.Response`` current instance.
"""
if isinstance(body, bytes):
body = body.decode('utf-8')
self._bod... |
def json(self, data):
"""
Defines the mock response JSON body.
Arguments:
data (dict|list|str): JSON body data.
Returns:
self: ``pook.Response`` current instance.
"""
self._headers['Content-Type'] = 'application/json'
if not isinstance(da... |
def set(self, key, val):
"""
Sets a header field with the given value, removing
previous values.
Usage::
headers = HTTPHeaderDict(foo='bar')
headers.set('Foo', 'baz')
headers['foo']
> 'baz'
"""
key_lower = key.lower()
... |
def _append_funcs(target, items):
"""
Helper function to append functions into a given list.
Arguments:
target (list): receptor list to append functions.
items (iterable): iterable that yields elements to append.
"""
[target.append(item) for item in items
if isfunction(item) or... |
def _trigger_request(instance, request):
"""
Triggers request mock definition methods dynamically based on input
keyword arguments passed to `pook.Mock` constructor.
This is used to provide a more Pythonic interface vs chainable API
approach.
"""
if not isinstance(request, Request):
... |
def url(self, url):
"""
Defines the mock URL to match.
It can be a full URL with path and query params.
Protocol schema is optional, defaults to ``http://``.
Arguments:
url (str): mock URL to match. E.g: ``server.com/api``.
Returns:
self: curren... |
def method(self, method):
"""
Defines the HTTP method to match.
Use ``*`` to match any method.
Arguments:
method (str): method value to match. E.g: ``GET``.
Returns:
self: current Mock instance.
"""
self._request.method = method
s... |
def path(self, path):
"""
Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance.
"""
url = fur... |
def header(self, name, value):
"""
Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance.
"""
... |
def headers(self, headers=None, **kw):
"""
Defines a dictionary of arguments.
Header keys are case insensitive.
Arguments:
headers (dict): headers to match.
**headers (dict): headers to match as variadic keyword arguments.
Returns:
self: cur... |
def header_present(self, *names):
"""
Defines a new header matcher expectation that must be present in the
outgoing request in order to be satisfied, no matter what value it
hosts.
Header keys are case insensitive.
Arguments:
*names (str): header or headers ... |
def headers_present(self, headers):
"""
Defines a list of headers that must be present in the
outgoing request in order to satisfy the matcher, no matter what value
the headers hosts.
Header keys are case insensitive.
Arguments:
headers (list|tuple): header ... |
def content(self, value):
"""
Defines the ``Content-Type`` outgoing header value to match.
You can pass one of the following type aliases instead of the full
MIME type representation:
- ``json`` = ``application/json``
- ``xml`` = ``application/xml``
- ``html`` =... |
def params(self, params):
"""
Defines a set of URL query params to match.
Arguments:
params (dict): set of params to match.
Returns:
self: current Mock instance.
"""
url = furl(self._request.rawurl)
url = url.add(params)
self._req... |
def body(self, body):
"""
Defines the body data to match.
``body`` argument can be a ``str``, ``binary`` or a regular expression.
Arguments:
body (str|binary|regex): body data to match.
Returns:
self: current Mock instance.
"""
self._req... |
def json(self, json):
"""
Defines the JSON body to match.
``json`` argument can be an JSON string, a JSON serializable
Python structure, such as a ``dict`` or ``list`` or it can be
a regular expression used to match the body.
Arguments:
json (str|dict|list|r... |
def xml(self, xml):
"""
Defines a XML body value to match.
Arguments:
xml (str|regex): body XML to match.
Returns:
self: current Mock instance.
"""
self._request.xml = xml
self.add_matcher(matcher('XMLMatcher', xml)) |
def file(self, path):
"""
Reads the body to match from a disk file.
Arguments:
path (str): relative or absolute path to file to read from.
Returns:
self: current Mock instance.
"""
with open(path, 'r') as f:
self.body(str(f.read())) |
def persist(self, status=None):
"""
Enables persistent mode for the current mock.
Returns:
self: current Mock instance.
"""
self._persist = status if type(status) is bool else True |
def error(self, error):
"""
Defines a simulated exception error that will be raised.
Arguments:
error (str|Exception): error to raise.
Returns:
self: current Mock instance.
"""
self._error = RuntimeError(error) if isinstance(error, str) else erro... |
def reply(self, status=200, new_response=False, **kw):
"""
Defines the mock response.
Arguments:
status (int, optional): response status code. Defaults to ``200``.
**kw (dict): optional keyword arguments passed to ``pook.Response``
constructor.
R... |
def match(self, request):
"""
Matches an outgoing HTTP request against the current mock matchers.
This method acts like a delegator to `pook.MatcherEngine`.
Arguments:
request (pook.Request): request instance to match.
Raises:
Exception: if the mock has... |
def activate_async(fn, _engine):
"""
Async version of activate decorator
Arguments:
fn (function): function that be wrapped by decorator.
_engine (Engine): pook engine instance
Returns:
function: decorator wrapper function.
"""
@coroutine
@functools.wraps(fn)
de... |
def set_mock_engine(self, engine):
"""
Sets a custom mock engine, replacing the built-in one.
This is particularly useful if you want to replace the built-in
HTTP traffic mock interceptor engine with your custom one.
For mock engine implementation details, see `pook.MockEngine`... |
def enable_network(self, *hostnames):
"""
Enables real networking mode, optionally passing one or multiple
hostnames that would be used as filter.
If at least one hostname matches with the outgoing traffic, the
request will be executed via the real network.
Arguments:
... |
def mock(self, url=None, **kw):
"""
Creates and registers a new HTTP mock in the current engine.
Arguments:
url (str): request URL to mock.
activate (bool): force mock engine activation.
Defaults to ``False``.
**kw (mixed): variadic keyword ar... |
def remove_mock(self, mock):
"""
Removes a specific mock instance by object reference.
Arguments:
mock (pook.Mock): mock instance to remove.
"""
self.mocks = [m for m in self.mocks if m is not mock] |
def activate(self):
"""
Activates the registered interceptors in the mocking engine.
This means any HTTP traffic captures by those interceptors will
trigger the HTTP mock matching engine in order to determine if a given
HTTP transaction should be mocked out or not.
"""
... |
def disable(self):
"""
Disables interceptors and stops intercepting any outgoing HTTP traffic.
"""
if not self.active:
return None
# Disable current mock engine
self.mock_engine.disable()
# Disable engine state
self.active = False |
def should_use_network(self, request):
"""
Verifies if real networking mode should be used for the given
request, passing it to the registered network filters.
Arguments:
request (pook.Request): outgoing HTTP request to test.
Returns:
bool
"""
... |
def match(self, request):
"""
Matches a given Request instance contract against the registered mocks.
If a mock passes all the matchers, its response will be returned.
Arguments:
request (pook.Request): Request contract to match.
Raises:
pook.PookNoMatc... |
def copy(self):
"""
Copies the current Request object instance for side-effects purposes.
Returns:
pook.Request: copy of the current Request instance.
"""
req = type(self)()
req.__dict__ = self.__dict__.copy()
req._headers = self.headers.copy()
... |
def activate(fn=None):
"""
Enables the HTTP traffic interceptors.
This function can be used as decorator.
Arguments:
fn (function|coroutinefunction): Optional function argument
if used as decorator.
Returns:
function: decorator wrapper function, only if called as decor... |
def use(network=False):
"""
Creates a new isolated mock engine to be used via context manager.
Example::
with pook.use() as engine:
pook.mock('server.com/foo').reply(404)
res = requests.get('server.com/foo')
assert res.status_code == 404
"""
global _eng... |
def regex(expression, flags=re.IGNORECASE):
"""
Convenient shortcut to ``re.compile()`` for fast, easy to use
regular expression compilation without an extra import statement.
Arguments:
expression (str): regular expression value.
flags (int): optional regular expression flags.
... |
def add_interceptor(self, *interceptors):
"""
Adds one or multiple HTTP traffic interceptors to the current
mocking engine.
Interceptors are typically HTTP client specific wrapper classes that
implements the pook interceptor interface.
Arguments:
interceptor... |
def remove_interceptor(self, name):
"""
Removes a specific interceptor by name.
Arguments:
name (str): interceptor name to disable.
Returns:
bool: `True` if the interceptor was disabled, otherwise `False`.
"""
for index, interceptor in enumerate(... |
def get_setting(connection, key):
"""Get key from connection or default to settings."""
if key in connection.settings_dict:
return connection.settings_dict[key]
else:
return getattr(settings, key) |
def as_sql(self, compiler, connection):
"""Build SQL with decryption and casting."""
sql, params = super(DecryptedCol, self).as_sql(compiler, connection)
sql = self.target.get_decrypt_sql(connection) % (sql, self.target.get_cast_sql())
return sql, params |
def pre_save(self, model_instance, add):
"""Save the original_value."""
if self.original:
original_value = getattr(model_instance, self.original)
setattr(model_instance, self.attname, original_value)
return super(HashMixin, self).pre_save(model_instance, add) |
def get_placeholder(self, value=None, compiler=None, connection=None):
"""
Tell postgres to encrypt this field with a hashing function.
The `value` string is checked to determine if we need to hash or keep
the current value.
`compiler` and `connection` is ignored here as we don... |
def get_col(self, alias, output_field=None):
"""Get the decryption for col."""
if output_field is None:
output_field = self
if alias != self.model._meta.db_table or output_field != self:
return DecryptedCol(
alias,
self,
out... |
def get_placeholder(self, value=None, compiler=None, connection=None):
"""Tell postgres to encrypt this field using PGP."""
return self.encrypt_sql.format(get_setting(connection, 'PUBLIC_PGP_KEY')) |
def hunt_repeated_yaml_keys(data):
"""Parses yaml and returns a list of repeated variables and
the line on which they occur
"""
loader = yaml.Loader(data)
def compose_node(parent, index):
# the line number where the previous token has ended (plus empty lines)
line = loader.line
... |
def base_regression(Q, slope=None):
"""
this function calculates the regression coefficients for a
given vector containing the averages of tip and branch
quantities.
Parameters
----------
Q : numpy.array
vector with
slope : None, optional
Description
Returns
---... |
def Cov(self):
"""
calculate the covariance matrix of the tips assuming variance
has accumulated along branches of the tree accoriding to the
the provided
Returns
-------
M : (np.array)
covariance matrix with tips arranged standard transersal order.
... |
def CovInv(self):
"""
Inverse of the covariance matrix
Returns
-------
H : (np.array)
inverse of the covariance matrix.
"""
self.recurse(full_matrix=True)
return self.tree.root.cinv |
def recurse(self, full_matrix=False):
"""
recursion to calculate inverse covariance matrix
Parameters
----------
full_matrix : bool, optional
if True, the entire inverse matrix is calculated. otherwise, only the weighing vector.
"""
for n in self.tree... |
def _calculate_averages(self):
"""
calculate the weighted sums of the tip and branch values and
their second moments.
"""
for n in self.tree.get_nonterminals(order='postorder'):
Q = np.zeros(6, dtype=float)
for c in n:
tv = self.tip_value(c... |
def propagate_averages(self, n, tv, bv, var, outgroup=False):
"""
This function implements the propagation of the means,
variance, and covariances along a branch. It operates
both towards the root and tips.
Parameters
----------
n : (node)
the branch... |
def explained_variance(self):
"""calculate standard explained variance
Returns
-------
float
r-value of the root-to-tip distance and time.
independent of regression model, but dependent on root choice
"""
self.tree.root._v=0
for n in self.... |
def regression(self, slope=None):
"""regress tip values against branch values
Parameters
----------
slope : None, optional
if given, the slope isn't optimized
Returns
-------
dict
regression parameters
"""
self._calculate_... |
def find_best_root(self, force_positive=True, slope=None):
"""
determine the position on the tree that minimizes the bilinear
product of the inverse covariance and the data vectors.
Returns
-------
best_root : (dict)
dictionary with the node, the fraction `x... |
def optimal_reroot(self, force_positive=True, slope=None):
"""
determine the best root and reroot the tree to this value.
Note that this can change the parent child relations of the tree
and values associated with branches rather than nodes
(e.g. confidence) might need to be re-e... |
def clock_plot(self, add_internal=False, ax=None, regression=None,
confidence=True, n_sigma = 2, fs=14):
"""Plot root-to-tip distance vs time as a basic time-tree diagnostic
Parameters
----------
add_internal : bool, optional
add internal nodes. this will ... |
def JC69 (mu=1.0, alphabet="nuc", **kwargs):
"""
Jukes-Cantor 1969 model. This model assumes equal concentrations
of the nucleotides and equal transition rates between nucleotide states.
For more info, see: Jukes and Cantor (1969). Evolution of Protein Molecules.
New York: Academ... |
def K80(mu=1., kappa=0.1, **kwargs):
"""
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. Ev... |
def F81(mu=1.0, pi=None, alphabet="nuc", **kwargs):
"""
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.
Cur... |
def HKY85(mu=1.0, pi=None, kappa=0.1, **kwargs):
"""
Hasegawa, Kishino and Yano 1985 model. Allows different concentrations of the
nucleotides (as in F81) + distinguishes between transition/transversionsubstitutions
(similar to K80). Link:
Hasegawa, Kishino, Yano (1985), J. Mol. Evol. 22 (2): 160–17... |
def T92(mu=1.0, pi_GC=0.5, kappa=0.1, **kwargs):
"""
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 acc... |
def TN93(mu=1.0, kappa1=1., kappa2=1., pi=None, **kwargs):
"""
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 ... |
def _create_transversion_transition_W(kappa):
"""
Alphabet = [A, C, G, T]
"""
W = np.ones((4,4))
W[0, 2]=W[1, 3]=W[2, 0]=W[3,1]=kappa
return W |
def set_Tc(self, Tc, T=None):
'''
initialize the merger model with a coalescent time
Args:
- Tc: a float or an iterable, if iterable another argument T of same shape is required
- T: an array like of same shape as Tc that specifies the time pivots corresponding to T... |
def calc_branch_count(self):
'''
calculates an interpolation object that maps time to the number of
concurrent branches in the tree. The result is stored in self.nbranches
'''
# make a list of (time, merger or loss event) by root first iteration
self.tree_events = np.arr... |
def calc_integral_merger_rate(self):
'''
calculates the integral int_0^t (k(t')-1)/2Tc(t') dt' and stores it as
self.integral_merger_rate. This differences of this quantity evaluated at
different times points are the cost of a branch.
'''
# integrate the piecewise constan... |
def cost(self, t_node, branch_length, multiplicity=2.0):
'''
returns the cost associated with a branch starting at t_node
t_node is time before present, the branch goes back in time
Args:
- t_node: time of the node
- branch_length: branch length, det... |
def attach_to_tree(self):
'''
attaches the the merger cost to each branch length interpolator in the tree.
'''
for clade in self.tree.find_clades():
if clade.up is not None:
clade.branch_length_interpolator.merger_cost = self.cost |
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()
... |
def optimize_skyline(self, n_points=20, stiffness=2.0, method = 'SLSQP',
tol=0.03, regularization=10.0, **kwarks):
'''
optimize the trajectory of the merger rate 1./T_c to maximize the
coalescent likelihood.
parameters:
n_points -- number of pivot... |
def skyline_empirical(self, gen=1.0, n_points = 20):
'''
returns the skyline, i.e., an estimate of the inverse rate of coalesence.
Here, the skyline is estimated from a sliding window average of the observed
mergers, i.e., without reference to the coalescence likelihood.
paramete... |
def skyline_inferred(self, gen=1.0, confidence=False):
'''
return the skyline, i.e., an estimate of the inverse rate of coalesence.
This function merely returns the merger rate self.Tc that was set or
estimated by other means. If it was determined using self.optimize_skyline,
the... |
def seq2array(seq, fill_overhangs=True, ambiguous_character='N'):
"""
Take the raw sequence, substitute the "overhanging" gaps with 'N' (missequenced),
and convert the sequence to the numpy array of chars.
Parameters
----------
seq : Biopython.SeqRecord, str, iterable
Sequence as an ob... |
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.
... |
def normalize_profile(in_profile, log=False, return_offset = True):
"""return a normalized version of a profile matrix
Parameters
----------
in_profile : np.array
shape Lxq, will be normalized to one across each row
log : bool, optional
treat the input as log probabilities
retur... |
def logger(self, msg, level, warn=False):
"""
Print log message *msg* to stdout.
Parameters
-----------
msg : str
String to print on the screen
level : int
Log-level. Only the messages with a level higher than the
current verbose l... |
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... |
def set_gtr(self, in_gtr, **kwargs):
"""
Create new GTR model if needed, and set the model as an attribute of the
TreeAnc class
Parameters
-----------
in_gtr : str, GTR
The gtr model to be assigned. If string is passed,
it is taken as the name o... |
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.... |
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
... |
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
"""
... |
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 ... |
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'),... |
def process_alignment_dict(self):
"""
prepare the dictionary specifying differences from a reference sequence
to construct the reduced alignment with variable sites only. NOTE:
- sites can be constant but different from the reference
- sites can be constant plus a ambiguo... |
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... |
def _prepare_nodes(self):
"""
Set auxilliary parameters to every node of the tree.
"""
self.tree.root.up = None
self.tree.root.bad_branch=self.tree.root.bad_branch if hasattr(self.tree.root, 'bad_branch') else False
internal_node_count = 0
for clade in self.tree.g... |
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:
... |
def infer_gtr(self, print_raw=False, marginal=False, normalized_rate=True,
fixed_pi=None, pc=5.0, **kwargs):
"""
Calculates a GTR model given the multiple sequence alignment and the tree.
It performs ancestral sequence inferrence (joint or marginal), followed by
the bra... |
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
... |
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
... |
def get_mutations(self, node, keep_var_ambigs=False):
"""
Get the mutations on a tree branch. Take compressed sequences from both sides
of the branch (attached to the node), compute mutations between them, and
expand these mutations to the positions in the real sequences.
Parame... |
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... |
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... |
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... |
def _fitch_anc(self, **kwargs):
"""
Reconstruct ancestral states using Fitch's algorithm. The method requires
sequences to be assigned to leaves. It implements the iteration from
leaves to the root constructing the Fitch profiles for each character of
the sequence, and then by pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.