INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Add or update a node s feature. | def add_feature(self, pr_name, pr_value):
""" Add or update a node's feature. """
setattr(self, pr_name, pr_value)
self.features.add(pr_name) |
Add or update several features. | def add_features(self, **features):
""" Add or update several features. """
for fname, fvalue in six.iteritems(features):
setattr(self, fname, fvalue)
self.features.add(fname) |
Permanently deletes a node s feature. | def del_feature(self, pr_name):
""" Permanently deletes a node's feature."""
if hasattr(self, pr_name):
delattr(self, pr_name)
self.features.remove(pr_name) |
Adds a new child to this node. If child node is not suplied as an argument a new node instance will be created. Parameters ---------- | def add_child(self, child=None, name=None, dist=None, support=None):
"""
Adds a new child to this node. If child node is not suplied
as an argument, a new node instance will be created.
Parameters
----------
child:
the node instance to be added as a... |
Removes a child from this node ( parent and child nodes still exit but are no longer connected ). | def remove_child(self, child):
"""
Removes a child from this node (parent and child
nodes still exit but are no longer connected).
"""
try:
self.children.remove(child)
except ValueError as e:
raise TreeError("child not found")
else:
... |
Adds a sister to this node. If sister node is not supplied as an argument a new TreeNode instance will be created and returned. | def add_sister(self, sister=None, name=None, dist=None):
"""
Adds a sister to this node. If sister node is not supplied
as an argument, a new TreeNode instance will be created and
returned.
"""
if self.up == None:
raise TreeError("A parent node is required to ... |
Removes a sister node. It has the same effect as ** TreeNode. up. remove_child ( sister ) ** | def remove_sister(self, sister=None):
"""
Removes a sister node. It has the same effect as
**`TreeNode.up.remove_child(sister)`**
If a sister node is not supplied, the first sister will be deleted
and returned.
:argument sister: A node instance
:return: The nod... |
Deletes node from the tree structure. Notice that this method makes disappear the node from the tree structure. This means that children from the deleted node are transferred to the next available parent. | def delete(self, prevent_nondicotomic=True, preserve_branch_length=False):
"""
Deletes node from the tree structure. Notice that this method
makes 'disappear' the node from the tree structure. This means
that children from the deleted node are transferred to the
next available pa... |
Detachs this node ( and all its descendants ) from its parent and returns the referent to itself. | def detach(self):
"""
Detachs this node (and all its descendants) from its parent
and returns the referent to itself.
Detached node conserves all its structure of descendants, and can
be attached to another node through the 'add_child' function. This
mechanism can be see... |
Prunes the topology of a node to conserve only a selected list of leaf internal nodes. The minimum number of nodes that conserve the topological relationships among the requested nodes will be retained. Root node is always conserved. | def prune(self, nodes, preserve_branch_length=False):
"""
Prunes the topology of a node to conserve only a selected list of leaf
internal nodes. The minimum number of nodes that conserve the
topological relationships among the requested nodes will be
retained. Root node is always... |
Returns an indepent list of sister nodes. | def get_sisters(self):
""" Returns an indepent list of sister nodes."""
if self.up != None:
return [ch for ch in self.up.children if ch != self]
else:
return [] |
Returns an iterator over the leaves under this node. | def iter_leaves(self, is_leaf_fn=None):
""" Returns an iterator over the leaves under this node."""
for n in self.traverse(strategy="preorder", is_leaf_fn=is_leaf_fn):
if not is_leaf_fn:
if n.is_leaf():
yield n
else:
if is_leaf_... |
Returns an iterator over the leaf names under this node. | def iter_leaf_names(self, is_leaf_fn=None):
"""Returns an iterator over the leaf names under this node."""
for n in self.iter_leaves(is_leaf_fn=is_leaf_fn):
yield n.name |
Returns an iterator over all descendant nodes. | def iter_descendants(self, strategy="levelorder", is_leaf_fn=None):
""" Returns an iterator over all descendant nodes."""
for n in self.traverse(strategy=strategy, is_leaf_fn=is_leaf_fn):
if n is not self:
yield n |
Returns a list of all ( leaves and internal ) descendant nodes. | def get_descendants(self, strategy="levelorder", is_leaf_fn=None):
""" Returns a list of all (leaves and internal) descendant nodes."""
return [n for n in self.iter_descendants(
strategy=strategy, is_leaf_fn=is_leaf_fn)] |
Returns an iterator to traverse tree under this node. Parameters: ----------- strategy: set the way in which tree will be traversed. Possible values are: preorder ( first parent and then children ) postorder ( first children and the parent ) and levelorder ( nodes are visited in order from root to leaves ) | def traverse(self, strategy="levelorder", is_leaf_fn=None):
""" Returns an iterator to traverse tree under this node.
Parameters:
-----------
strategy:
set the way in which tree will be traversed. Possible
values are: "preorder" (first parent and then c... |
Iterate over all nodes in a tree yielding every node in both pre and post order. Each iteration returns a postorder flag ( True if node is being visited in postorder ) and a node instance. | def iter_prepostorder(self, is_leaf_fn=None):
"""
Iterate over all nodes in a tree yielding every node in both
pre and post order. Each iteration returns a postorder flag
(True if node is being visited in postorder) and a node
instance.
"""
to_visit = [self]
... |
Iterate over all desdecendant nodes. | def _iter_descendants_levelorder(self, is_leaf_fn=None):
""" Iterate over all desdecendant nodes."""
tovisit = deque([self])
while len(tovisit) > 0:
node = tovisit.popleft()
yield node
if not is_leaf_fn or not is_leaf_fn(node):
tovisit.extend(n... |
Iterator over all descendant nodes. | def _iter_descendants_preorder(self, is_leaf_fn=None):
""" Iterator over all descendant nodes. """
to_visit = deque()
node = self
while node is not None:
yield node
if not is_leaf_fn or not is_leaf_fn(node):
to_visit.extendleft(reversed(node.childr... |
Iterates over the list of all ancestor nodes from current node to the current tree root. | def iter_ancestors(self):
"""
Iterates over the list of all ancestor nodes from
current node to the current tree root.
"""
node = self
while node.up is not None:
yield node.up
node = node.up |
Returns the newick representation of current node. Several arguments control the way in which extra data is shown for every node: | def write(self,
features=None,
outfile=None,
format=0,
is_leaf_fn=None,
format_root_node=False,
dist_formatter=None,
support_formatter=None,
name_formatter=None):
"""
Returns the newick representation of current node. Several
... |
Returns the absolute root node of current tree structure. | def get_tree_root(self):
""" Returns the absolute root node of current tree structure."""
root = self
while root.up is not None:
root = root.up
return root |
Returns the first common ancestor between this node and a given list of target_nodes. | def get_common_ancestor(self, *target_nodes, **kargs):
"""
Returns the first common ancestor between this node and a given
list of 'target_nodes'.
**Examples:**
t = tree.Tree("(((A:0.1, B:0.01):0.001, C:0.0001):1.0[&&NHX:name=common], (D:0.00001):0.000001):2.0[&&NHX:name=root]... |
Search nodes in an interative way. Matches are being yield as they are being found. This avoids to scan the full tree topology before returning the first matches. Useful when dealing with huge trees. | def iter_search_nodes(self, **conditions):
"""
Search nodes in an interative way. Matches are being yield as
they are being found. This avoids to scan the full tree
topology before returning the first matches. Useful when
dealing with huge trees.
"""
for n in self... |
Returns the list of nodes matching a given set of conditions. ** Example: ** tree. search_nodes ( dist = 0. 0 name = human ) | def search_nodes(self, **conditions):
"""
Returns the list of nodes matching a given set of conditions.
**Example:**
tree.search_nodes(dist=0.0, name="human")
"""
matching_nodes = []
for n in self.iter_search_nodes(**conditions):
matching_nodes.append(... |
Returns the distance between two nodes. If only one target is specified it returns the distance bewtween the target and the current node. Parameters: ----------- target: a node within the same tree structure. | def get_distance(self, target, target2=None, topology_only=False):
"""
Returns the distance between two nodes. If only one target is
specified, it returns the distance bewtween the target and the
current node.
Parameters:
-----------
target:
a no... |
Returns the node s farthest descendant or ancestor node and the distance to it. | def get_farthest_node(self, topology_only=False):
"""
Returns the node's farthest descendant or ancestor node, and the
distance to it.
:argument False topology_only: If set to True, distance
between nodes will be referred to the number of nodes
between them. In other... |
Returns node s farthest descendant node ( which is always a leaf ) and the distance to it. | def get_farthest_leaf(self, topology_only=False, is_leaf_fn=None):
"""
Returns node's farthest descendant node (which is always a leaf), and the
distance to it.
:argument False topology_only: If set to True, distance
between nodes will be referred to the number of nodes
... |
Returns the node that divides the current tree into two distance - balanced partitions. | def get_midpoint_outgroup(self):
"""
Returns the node that divides the current tree into two
distance-balanced partitions.
"""
# Gets the farthest node to the current root
root = self.get_tree_root()
nA, r2A_dist = root.get_farthest_leaf()
nB, A2B_dist = ... |
Generates a random topology by populating current node. | def populate(self,
size,
names_library=None,
reuse_names=False,
random_branches=False,
branch_range=(0, 1),
support_range=(0, 1)):
"""
Generates a random topology by populating current node.
:argument None names_library: If provided, names lib... |
Sets a descendant node as the outgroup of a tree. This function can be used to root a tree or even an internal node. | def set_outgroup(self, outgroup):
"""
Sets a descendant node as the outgroup of a tree. This function
can be used to root a tree or even an internal node.
Parameters:
-----------
outgroup:
a node instance within the same tree structure that will be
... |
Unroots current node. This function is expected to be used on the absolute tree root node but it can be also be applied to any other internal node. It will convert a split into a multifurcation. | def unroot(self):
"""
Unroots current node. This function is expected to be used on
the absolute tree root node, but it can be also be applied to
any other internal node. It will convert a split into a
multifurcation.
"""
if len(self.children)==2:
if n... |
Returns the ASCII representation of the tree. Code based on the PyCogent GPL project. | def _asciiArt(self, char1='-', show_internal=True, compact=False, attributes=None):
"""
Returns the ASCII representation of the tree.
Code based on the PyCogent GPL project.
"""
if not attributes:
attributes = ["name"]
# toytree edit:
# remove... |
Returns a string containing an ascii drawing of the tree. Parameters: ----------- show_internal: include internal edge names. compact: use exactly one line per tip. attributes: A list of node attributes to shown in the ASCII representation. | def get_ascii(self, show_internal=True, compact=False, attributes=None):
"""
Returns a string containing an ascii drawing of the tree.
Parameters:
-----------
show_internal:
include internal edge names.
compact:
use exactly one line per ... |
Sort the branches of a given tree ( swapping children nodes ) according to the size of each partition. | def ladderize(self, direction=0):
"""
Sort the branches of a given tree (swapping children nodes)
according to the size of each partition.
"""
if not self.is_leaf():
n2s = {}
for n in self.get_children():
s = n.ladderize(direction=direction... |
This function sort the branches of a given tree by considerening node names. After the tree is sorted nodes are labeled using ascendent numbers. This can be used to ensure that nodes in a tree with the same node names are always labeled in the same way. Note that if duplicated names are present extra criteria should be... | def sort_descendants(self, attr="name"):
"""
This function sort the branches of a given tree by
considerening node names. After the tree is sorted, nodes are
labeled using ascendent numbers. This can be used to ensure
that nodes in a tree with the same node names are always
... |
Returns a dictionary pointing to the preloaded content of each internal node under this tree. Such a dictionary is intended to work as a cache for operations that require many traversal operations. Parameters: ----------- store_attr: Specifies the node attribute that should be cached ( i. e. name distance etc. ). When ... | def get_cached_content(self, store_attr=None, container_type=set, _store=None):
"""
Returns a dictionary pointing to the preloaded content of each
internal node under this tree. Such a dictionary is intended
to work as a cache for operations that require many traversal
operations... |
Returns the Robinson - Foulds symmetric distance between current tree and a different tree instance. | def robinson_foulds(self,
t2,
attr_t1="name",
attr_t2="name",
unrooted_trees=False,
expand_polytomies=False,
polytomy_size_limit=5,
skip_large_polytomies=False,
correct_by_polytomy_size=False,
min_support_t1=0.0,
min_support_t2=0.0):
... |
Iterate over the list of edges of a tree. Each egde is represented as a tuple of two elements each containing the list of nodes separated by the edge. | def iter_edges(self, cached_content=None):
"""
Iterate over the list of edges of a tree. Each egde is represented as a
tuple of two elements, each containing the list of nodes separated by
the edge.
"""
if not cached_content:
cached_content = self.get_cached_c... |
Returns the unique ID representing the topology of the current tree. Two trees with the same topology will produce the same id. If trees are unrooted make sure that the root node is not binary or use the tree. unroot () function before generating the topology id. | def get_topology_id(self, attr="name"):
"""
Returns the unique ID representing the topology of the current tree.
Two trees with the same topology will produce the same id. If trees are
unrooted, make sure that the root node is not binary or use the
tree.unroot() function before ... |
Returns True if a given target attribute is monophyletic under this node for the provided set of values. | def check_monophyly(self,
values,
target_attr,
ignore_missing=False,
unrooted=False):
"""
Returns True if a given target attribute is monophyletic under
this node for the provided set of values.
If not all values are represented in the current tree
... |
Returns a list of nodes matching the provided monophyly criteria. For a node to be considered a match all target_attr values within and node and exclusively them should be grouped. | def get_monophyletic(self, values, target_attr):
"""
Returns a list of nodes matching the provided monophyly
criteria. For a node to be considered a match, all
`target_attr` values within and node, and exclusively them,
should be grouped.
:param values: a set of values f... |
Given a tree with one or more polytomies this functions returns the list of all trees ( in newick format ) resulting from the combination of all possible solutions of the multifurcated nodes. | def expand_polytomies(self,
map_attr="name",
polytomy_size_limit=5,
skip_large_polytomies=False):
"""
Given a tree with one or more polytomies, this functions returns the
list of all trees (in newick format) resulting from the combination of
all possible solutio... |
Resolve all polytomies under current node by creating an arbitrary dicotomic structure among the affected nodes. This function randomly modifies current tree topology and should only be used for compatibility reasons ( i. e. programs rejecting multifurcated node in the newick representation ). | def resolve_polytomy(self,
default_dist=0.0,
default_support=0.0,
recursive=True):
"""
Resolve all polytomies under current node by creating an
arbitrary dicotomic structure among the affected nodes. This
function randomly modifies current tree topology and shou... |
Removes all empty lines from above and below the text. | def truncate_empty_lines(lines):
"""
Removes all empty lines from above and below the text.
We can't just use text.strip() because that would remove the leading
space for the table.
Parameters
----------
lines : list of str
Returns
-------
lines : list of str
The text ... |
Convert a date or datetime object into a javsacript timestamp | def jstimestamp_slow(dte):
'''Convert a date or datetime object into a javsacript timestamp'''
year, month, day, hour, minute, second = dte.timetuple()[:6]
days = date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
hours = days*24 + hour
minutes = hours*60 + minute
seconds = minutes*60... |
Convert a date or datetime object into a javsacript timestamp. | def jstimestamp(dte):
'''Convert a date or datetime object into a javsacript timestamp.'''
days = date(dte.year, dte.month, 1).toordinal() - _EPOCH_ORD + dte.day - 1
hours = days*24
if isinstance(dte,datetime):
hours += dte.hour
minutes = hours*60 + dte.minute
second... |
Convert a string or html file to an rst table string. | def html2rst(html_string, force_headers=False, center_cells=False,
center_headers=False):
"""
Convert a string or html file to an rst table string.
Parameters
----------
html_string : str
Either the html string, or the filepath to the html
force_headers : bool
Make ... |
Create a list of rows and columns that will make up a span | def make_span(row, column, extra_rows, extra_columns):
"""
Create a list of rows and columns that will make up a span
Parameters
----------
row : int
The row of the first cell in the span
column : int
The column of the first cell in the span
extra_rows : int
The numb... |
Convert the contents of a span of the table to a grid table cell | def make_cell(table, span, widths, heights, use_headers):
"""
Convert the contents of a span of the table to a grid table cell
Parameters
----------
table : list of lists of str
The table of rows containg strings to convert to a grid table
span : list of lists of int
list of [ro... |
Initialize application object. | def init_app(self, app, **kwargs):
"""Initialize application object."""
self.init_db(app, **kwargs)
app.config.setdefault('ALEMBIC', {
'script_location': pkg_resources.resource_filename(
'invenio_db', 'alembic'
),
'version_locations': [
... |
Initialize Flask - SQLAlchemy extension. | def init_db(self, app, entry_point_group='invenio_db.models', **kwargs):
"""Initialize Flask-SQLAlchemy extension."""
# Setup SQLAlchemy
app.config.setdefault(
'SQLALCHEMY_DATABASE_URI',
'sqlite:///' + os.path.join(app.instance_path, app.name + '.db')
)
ap... |
Initialize the versioning support using SQLAlchemy - Continuum. | def init_versioning(self, app, database, versioning_manager=None):
"""Initialize the versioning support using SQLAlchemy-Continuum."""
try:
pkg_resources.get_distribution('sqlalchemy_continuum')
except pkg_resources.DistributionNotFound: # pragma: no cover
default_versio... |
Convert an html string to data table | def extract_table(html_string, row_count, column_count):
"""
Convert an html string to data table
Parameters
----------
html_string : str
row_count : int
column_count : int
Returns
-------
data_table : list of lists of str
"""
try:
from bs4 import BeautifulSoup
... |
Ensure SQLite checks foreign key constraints. | def do_sqlite_connect(dbapi_connection, connection_record):
"""Ensure SQLite checks foreign key constraints.
For further details see "Foreign key support" sections on
https://docs.sqlalchemy.org/en/latest/dialects/sqlite.html#foreign-key-support
"""
# Enable foreign key constraint checking
curs... |
Call before engine creation. | def apply_driver_hacks(self, app, info, options):
"""Call before engine creation."""
# Don't forget to apply hacks defined on parent object.
super(SQLAlchemy, self).apply_driver_hacks(app, info, options)
if info.drivername == 'sqlite':
connect_args = options.setdefault('conn... |
Create tables. | def create(verbose):
"""Create tables."""
click.secho('Creating all tables!', fg='yellow', bold=True)
with click.progressbar(_db.metadata.sorted_tables) as bar:
for table in bar:
if verbose:
click.echo(' Creating table {0}'.format(table))
table.create(bind=_db... |
Drop tables. | def drop(verbose):
"""Drop tables."""
click.secho('Dropping all tables!', fg='red', bold=True)
with click.progressbar(reversed(_db.metadata.sorted_tables)) as bar:
for table in bar:
if verbose:
click.echo(' Dropping table {0}'.format(table))
table.drop(bind=_d... |
Create database. | def init():
"""Create database."""
click.secho('Creating database {0}'.format(_db.engine.url),
fg='green')
if not database_exists(str(_db.engine.url)):
create_database(str(_db.engine.url)) |
Drop database. | def destroy():
"""Drop database."""
click.secho('Destroying database {0}'.format(_db.engine.url),
fg='red', bold=True)
if _db.engine.name == 'sqlite':
try:
drop_database(_db.engine.url)
except FileNotFoundError as e:
click.secho('Sqlite database has no... |
Fast rolling operation with O ( log n ) updates where n is the window size | def rolling(self, op):
"""Fast rolling operation with O(log n) updates where n is the
window size
"""
missing = self.missing
ismissing = self.ismissing
window = self.window
it = iter(self.iterable)
queue = deque(islice(it, window))
ol = self.skip... |
Find the length of a colspan. | def get_span_column_count(span):
"""
Find the length of a colspan.
Parameters
----------
span : list of lists of int
The [row, column] pairs that make up the span
Returns
-------
columns : int
The number of columns included in the span
Example
-------
Consi... |
returns self as a dictionary with _underscore subdicts corrected. | def to_dict(self):
"returns self as a dictionary with _underscore subdicts corrected."
ndict = {}
for key, val in self.__dict__.items():
if key[0] == "_":
ndict[key[1:]] = val
else:
ndict[key] = val
return ndict |
Sum the widths of the columns that make up the span plus the extra. | def get_span_char_width(span, column_widths):
"""
Sum the widths of the columns that make up the span, plus the extra.
Parameters
----------
span : list of lists of int
list of [row, column] pairs that make up the span
column_widths : list of int
The widths of the columns that m... |
Rebuild a model s EncryptedType properties when the SECRET_KEY is changed. | def rebuild_encrypted_properties(old_key, model, properties):
"""Rebuild a model's EncryptedType properties when the SECRET_KEY is changed.
:param old_key: old SECRET_KEY.
:param model: the affected db model.
:param properties: list of properties to rebuild.
"""
inspector = reflection.Inspector... |
Create alembic_version table. | def create_alembic_version_table():
"""Create alembic_version table."""
alembic = current_app.extensions['invenio-db'].alembic
if not alembic.migration_context._has_version_table():
alembic.migration_context._ensure_version_table()
for head in alembic.script_directory.revision_map._real_head... |
Drop alembic_version table. | def drop_alembic_version_table():
"""Drop alembic_version table."""
if _db.engine.dialect.has_table(_db.engine, 'alembic_version'):
alembic_version = _db.Table('alembic_version', _db.metadata,
autoload_with=_db.engine)
alembic_version.drop(bind=_db.engine) |
Get the name of the versioned model class. | def versioning_model_classname(manager, model):
"""Get the name of the versioned model class."""
if manager.options.get('use_module_name', True):
return '%s%sVersion' % (
model.__module__.title().replace('.', ''), model.__name__)
else:
return '%sVersion' % (model.__name__,) |
Return True if all versioning models have been registered. | def versioning_models_registered(manager, base):
"""Return True if all versioning models have been registered."""
declared_models = base._decl_class_registry.keys()
return all(versioning_model_classname(manager, c) in declared_models
for c in manager.pending_classes) |
Convert an iterable into a symmetric matrix. | def vector_to_symmetric(v):
'''Convert an iterable into a symmetric matrix.'''
np = len(v)
N = (int(sqrt(1 + 8*np)) - 1)//2
if N*(N+1)//2 != np:
raise ValueError('Cannot convert vector to symmetric matrix')
sym = ndarray((N,N))
iterable = iter(v)
for r in range(N):
f... |
The covariance matrix from the aggregate sample. It accepts an optional parameter for the degree of freedoms.: parameter ddof: If not None normalization is by ( N - ddof ) where N is the number of observations ; this overrides the value implied by bias. The default value is None. | def cov(self, ddof=None, bias=0):
'''The covariance matrix from the aggregate sample. It accepts an
optional parameter for the degree of freedoms.
:parameter ddof: If not ``None`` normalization is by (N - ddof), where N is
the number of observations; this overrides the value im... |
The correlation matrix | def corr(self):
'''The correlation matrix'''
cov = self.cov()
N = cov.shape[0]
corr = ndarray((N,N))
for r in range(N):
for c in range(r):
corr[r,c] = corr[c,r] = cov[r,c]/sqrt(cov[r,r]*cov[c,c])
corr[r,r] = 1.
return corr |
Calculate the Calmar ratio for a Weiner process | def calmar(sharpe, T = 1.0):
'''
Calculate the Calmar ratio for a Weiner process
@param sharpe: Annualized Sharpe ratio
@param T: Time interval in years
'''
x = 0.5*T*sharpe*sharpe
return x/qp(x) |
Multiplicator for normalizing calmar ratio to period tau | def calmarnorm(sharpe, T, tau = 1.0):
'''
Multiplicator for normalizing calmar ratio to period tau
'''
return calmar(sharpe,tau)/calmar(sharpe,T) |
Upgrade database. | def upgrade():
"""Upgrade database."""
op.execute('COMMIT') # See https://bitbucket.org/zzzeek/alembic/issue/123
ctx = op.get_context()
metadata = ctx.opts['target_metadata']
metadata.naming_convention = NAMING_CONVENTION
metadata.bind = ctx.connection.engine
insp = Inspector.from_engine(ct... |
Convert table data to a simple rst table | def data2simplerst(table, spans=[[[0, 0]]], use_headers=True, headers_row=0):
"""
Convert table data to a simple rst table
Parameters
----------
table : list of lists of str
A table of strings.
spans : list of lists of lists of int
A list of spans. A span is a list of [Row, Colu... |
Add the links to the bottom of the text | def add_links(converted_text, html):
"""
Add the links to the bottom of the text
"""
soup = BeautifulSoup(html, 'html.parser')
link_exceptions = [
'footnote-reference',
'fn-backref',
'citation-reference'
]
footnotes = {}
citations = {}
backrefs = {}
lin... |
Load symbols data.: keyword providers: Dictionary of registered data providers.: keyword symbols: list of symbols to load.: keyword start: start date.: keyword end: end date.: keyword logger: instance of: class: logging. Logger or None.: keyword backend:: class: dynts. TimeSeries backend name. There is no need to overr... | def load(self, providers, symbols, start, end, logger, backend, **kwargs):
'''Load symbols data.
:keyword providers: Dictionary of registered data providers.
:keyword symbols: list of symbols to load.
:keyword start: start date.
:keyword end: end date.
:keyword lo... |
Internal function which perform pre - conditioning on dates:: keyword start: start date.: keyword end: end date. This function makes sure the * start * and * end * date are consistent. It * never fails * and always return a two - element tuple containing * start * * end * with * start * less or equal * end * and * end ... | def dates(self, start, end):
'''Internal function which perform pre-conditioning on dates:
:keyword start: start date.
:keyword end: end date.
This function makes sure the *start* and *end* date are consistent.
It *never fails* and always return a two-element tuple
containing *start*, *end* with *star... |
Parse a symbol to obtain information regarding ticker field and provider. Must return an instance of: attr: symboldata.: keyword symbol: string associated with market data to load.: keyword providers: dictionary of: class: dynts. data. DataProvider instances available. For example:: intc intc: open intc: volume: google... | def parse_symbol(self, symbol, providers):
'''Parse a symbol to obtain information regarding ticker,
field and provider. Must return an instance of :attr:`symboldata`.
:keyword symbol: string associated with market data to load.
:keyword providers: dictionary of :class:`dynts.data.... |
Return an instance of * symboldata * containing information about the data provider the data provider ticker name and the data provider field. | def symbol_for_ticker(self, ticker, field, provider, providers):
'''Return an instance of *symboldata* containing
information about the data provider, the data provider ticker name
and the data provider field.'''
provider = provider or settings.default_provider
if provider:
pro... |
Preprocess ** hook **. This is first loading hook and it is ** called before requesting data ** from a dataprovider. It must return an instance of: attr: TimeSerieLoader. preprocessdata. By default it returns:: self. preprocessdata ( intervals = (( start end ) )) It could be overritten to modify the intervals. If the i... | def preprocess(self, ticker, start, end, logger, backend, **kwargs):
'''Preprocess **hook**. This is first loading hook and it is
**called before requesting data** from a dataprovider.
It must return an instance of :attr:`TimeSerieLoader.preprocessdata`.
By default it returns::
self.preprocessdata(in... |
Register a new data provider. * provider * must be an instance of DataProvider. If provider name is already available it will be replaced. | def register(self, provider):
'''Register a new data provider. *provider* must be an instance of
DataProvider. If provider name is already available, it will be replaced.'''
if isinstance(provider,type):
provider = provider()
self[provider.code] = provider |
Unregister an existing data provider. * provider * must be an instance of DataProvider. If provider name is already available it will be replaced. | def unregister(self, provider):
'''Unregister an existing data provider.
*provider* must be an instance of DataProvider.
If provider name is already available, it will be replaced.
'''
if isinstance(provider, type):
provider = provider()
if isinstance... |
Function for parsing: ref: timeseries expressions <dsl - script >. If succesful it returns an instance of: class: dynts. dsl. Expr which can be used to to populate timeseries or scatters once data is available. Parsing is implemented using the ply_ module an implementation of lex and yacc parsing tools for Python.: par... | def parse(timeseries_expression, method=None, functions=None, debug=False):
'''Function for parsing :ref:`timeseries expressions <dsl-script>`.
If succesful, it returns an instance of :class:`dynts.dsl.Expr` which
can be used to to populate timeseries or scatters once data is available.
Parsing is... |
Evaluate a timeseries expression into an instance of: class: dynts. dsl. dslresult which can be used to obtain timeseries and/ or scatters. This is probably the most used function of the library.: parameter expression: A timeseries expression string or an instance of: class: dynts. dsl. Expr obtained using the: func: ~... | def evaluate(expression, start=None, end=None, loader=None, logger=None,
backend=None, **kwargs):
'''Evaluate a timeseries ``expression`` into
an instance of :class:`dynts.dsl.dslresult` which can be used
to obtain timeseries and/or scatters.
This is probably the most used function of ... |
Convert Grid table to data ( the kind used by Dashtable ) | def grid2data(text):
"""
Convert Grid table to data (the kind used by Dashtable)
Parameters
----------
text : str
The text must be a valid rst table
Returns
-------
table : list of lists of str
spans : list of lists of lists of int
A span is a list of [row, column] p... |
Returns an extended majority rule consensus tree as a Toytree object. Node labels include support values showing the occurrence of clades in the consensus tree across trees in the input treelist. Clades with support below cutoff are collapsed into polytomies. If you enter an optional best_tree then support values from ... | def get_consensus_tree(self, cutoff=0.0, best_tree=None):
"""
Returns an extended majority rule consensus tree as a Toytree object.
Node labels include 'support' values showing the occurrence of clades
in the consensus tree across trees in the input treelist.
Clades with suppor... |
Draw a slice of x * y trees into a x y grid non - overlapping. | def draw_tree_grid(self,
nrows=None,
ncols=None,
start=0,
fixed_order=False,
shared_axis=False,
**kwargs):
"""
Draw a slice of x*y trees into a x,y grid non-overlapping.
Parameters:
-----------
x (int):
N... |
Draw a series of trees overlapping each other in coordinate space. The order of tip_labels is fixed in cloud trees so that trees with discordant relationships can be seen in conflict. To change the tip order use the fixed_order argument in toytree. mtree () when creating the MultiTree object. | def draw_cloud_tree(self,
axes=None,
html=False,
fixed_order=True,
**kwargs):
"""
Draw a series of trees overlapping each other in coordinate space.
The order of tip_labels is fixed in cloud trees so that trees with
discordant relationships can be seen ... |
hash ladderized tree topologies | def hash_trees(self):
"hash ladderized tree topologies"
observed = {}
for idx, tree in enumerate(self.treelist):
nwk = tree.write(tree_format=9)
hashed = md5(nwk.encode("utf-8")).hexdigest()
if hashed not in observed:
observed[hashed] = ... |
Count clade occurrences. | def find_clades(self):
"Count clade occurrences."
# index names from the first tree
ndict = {j: i for i, j in enumerate(self.names)}
namedict = {i: j for i, j in enumerate(self.names)}
# store counts
clade_counts = {}
for tidx, ncopies in self.treedict.items():
... |
Remove conflicting clades and those < cutoff to get majority rule | def filter_clades(self):
"Remove conflicting clades and those < cutoff to get majority rule"
passed = []
carrs = np.array([list(i[0]) for i in self.clade_counts], dtype=int)
freqs = np.array([i[1] for i in self.clade_counts])
for idx in range(carrs.shape[0]):
conflic... |
Build an unrooted consensus tree from filtered clade counts. | def build_trees(self):
"Build an unrooted consensus tree from filtered clade counts."
# storage
nodes = {}
idxarr = np.arange(len(self.fclade_counts[0][0]))
queue = []
## create dict of clade counts and set keys
countdict = defaultdict(int)
for clade, co... |
Compare the phonetic representations of 2 words and return a boolean value. | def sounds_like(self, word1, word2):
"""Compare the phonetic representations of 2 words, and return a boolean value."""
return self.phonetics(word1) == self.phonetics(word2) |
Get the similarity of the words using the supported distance metrics. | def distance(self, word1, word2, metric='levenshtein'):
"""Get the similarity of the words, using the supported distance metrics."""
if metric in self.distances:
distance_func = self.distances[metric]
return distance_func(self.phonetics(word1), self.phonetics(word2))
else... |
Get the heights of the rows of the output table. | def get_output_row_heights(table, spans):
"""
Get the heights of the rows of the output table.
Parameters
----------
table : list of lists of str
spans : list of lists of int
Returns
-------
heights : list of int
The heights of each row in the output table
"""
heigh... |
Generalised media for odd and even number of samples | def smedian(olist,nobs):
'''Generalised media for odd and even number of samples'''
if nobs:
rem = nobs % 2
midpoint = nobs // 2
me = olist[midpoint]
if not rem:
me = 0.5 * (me + olist[midpoint-1])
return me
else:
return NaN |
Apply a rolling mean function to an array. This is a simple rolling aggregation. | def roll_mean(input, window):
'''Apply a rolling mean function to an array.
This is a simple rolling aggregation.'''
nobs, i, j, sum_x = 0,0,0,0.
N = len(input)
if window > N:
raise ValueError('Out of bound')
output = np.ndarray(N-window+1,dtype=input.dtype)
for val in inpu... |
Apply a rolling standard deviation function to an array. This is a simple rolling aggregation of squared sums. | def roll_sd(input, window, scale = 1.0, ddof = 0):
'''Apply a rolling standard deviation function
to an array. This is a simple rolling aggregation of squared
sums.'''
nobs, i, j, sx, sxx = 0,0,0,0.,0.
N = len(input)
sqrt = np.sqrt
if window > N:
raise ValueError('Out of bound')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.