sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
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... | 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 | entailment |
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... | Call before engine creation. | entailment |
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... | Create tables. | entailment |
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... | Drop tables. | entailment |
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)) | Create database. | entailment |
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... | Drop database. | entailment |
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... | Fast rolling operation with O(log n) updates where n is the
window size | entailment |
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... | 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
-------
Consider this table::
+------+-----------... | entailment |
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 | returns self as a dictionary with _underscore subdicts corrected. | entailment |
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... | 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 make up the table
Returns
-------
total_width ... | entailment |
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... | 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. | entailment |
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... | Create alembic_version table. | entailment |
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) | Drop alembic_version table. | entailment |
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__,) | Get the name of the versioned model class. | entailment |
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) | Return True if all versioning models have been registered. | entailment |
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... | Convert an iterable into a symmetric matrix. | entailment |
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 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 ... | entailment |
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 | The correlation matrix | entailment |
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) | Calculate the Calmar ratio for a Weiner process
@param sharpe: Annualized Sharpe ratio
@param T: Time interval in years | entailment |
def calmarnorm(sharpe, T, tau = 1.0):
'''
Multiplicator for normalizing calmar ratio to period tau
'''
return calmar(sharpe,tau)/calmar(sharpe,T) | Multiplicator for normalizing calmar ratio to period tau | entailment |
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... | Upgrade database. | entailment |
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... | 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, Column] pairs of
table cells that are joined together.
use_headers : bool, optiona... | entailment |
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... | Add the links to the bottom of the text | entailment |
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... | 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: :clas... | entailment |
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... | 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* never a... | entailment |
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.... | 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 av... | entailment |
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... | Return an instance of *symboldata* containing
information about the data provider, the data provider ticker name
and the data provider field. | entailment |
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... | 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 ... | entailment |
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 | Register a new data provider. *provider* must be an instance of
DataProvider. If provider name is already available, it will be replaced. | entailment |
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... | Unregister an existing data provider.
*provider* must be an instance of DataProvider.
If provider name is already available, it will be replaced. | entailment |
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... | 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 t... | entailment |
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 ... | 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.E... | entailment |
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... | 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] pairs that define a group of
... | entailment |
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... | 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 option... | entailment |
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 slice of x*y trees into a x,y grid non-overlapping.
Parameters:
-----------
x (int):
Number of grid cells in x dimension. Default=automatically set.
y (int):
Number of grid cells in y dimension. Default=automatically set.
start (int):
... | entailment |
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 ... | 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 o... | entailment |
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] = ... | hash ladderized tree topologies | entailment |
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():
... | Count clade occurrences. | entailment |
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... | Remove conflicting clades and those < cutoff to get majority rule | entailment |
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... | Build an unrooted consensus tree from filtered clade counts. | entailment |
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) | Compare the phonetic representations of 2 words, and return a boolean value. | entailment |
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 similarity of the words, using the supported distance metrics. | entailment |
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... | 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 | entailment |
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 | Generalised media for odd and even number of samples | entailment |
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 mean function to an array.
This is a simple rolling aggregation. | entailment |
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')
... | Apply a rolling standard deviation function
to an array. This is a simple rolling aggregation of squared
sums. | entailment |
def check_span(span, table):
"""
Ensure the span is valid.
A span is a list of [row, column] pairs. These coordinates
must form a rectangular shape. For example, this span will cause an
error because it is not rectangular in shape.::
span = [[0, 1], [0, 2], [1, 0]]
Spans must be
... | Ensure the span is valid.
A span is a list of [row, column] pairs. These coordinates
must form a rectangular shape. For example, this span will cause an
error because it is not rectangular in shape.::
span = [[0, 1], [0, 2], [1, 0]]
Spans must be
* Rectanglular
* A list of li... | entailment |
def merge_all_cells(cells):
"""
Loop through list of cells and piece them together one by one
Parameters
----------
cells : list of dashtable.data2rst.Cell
Returns
-------
grid_table : str
The final grid table
"""
current = 0
while len(cells) > 1:
count = 0... | Loop through list of cells and piece them together one by one
Parameters
----------
cells : list of dashtable.data2rst.Cell
Returns
-------
grid_table : str
The final grid table | entailment |
def bpp2newick(bppnewick):
"converts bpp newick format to normal newick"
regex1 = re.compile(r" #[-+]?[0-9]*\.?[0-9]*[:]")
regex2 = re.compile(r" #[-+]?[0-9]*\.?[0-9]*[;]")
regex3 = re.compile(r": ")
new = regex1.sub(":", bppnewick)
new = regex2.sub(";", new)
new = regex3.sub(":", new)
r... | converts bpp newick format to normal newick | entailment |
def return_small_clade(treenode):
"used to produce balanced trees, returns a tip node from the smaller clade"
node = treenode
while 1:
if node.children:
c1, c2 = node.children
node = sorted([c1, c2], key=lambda x: len(x.get_leaves()))[0]
else:
return node | used to produce balanced trees, returns a tip node from the smaller clade | entailment |
def fuzzy_match_tipnames(ttree, names, wildcard, regex, mrca=True, mono=True):
"""
Used in multiple internal functions (e.g., .root()) and .drop_tips())
to select an internal mrca node, or multiple tipnames, using fuzzy matching
so that every name does not need to be written out by hand.
name: verb... | Used in multiple internal functions (e.g., .root()) and .drop_tips())
to select an internal mrca node, or multiple tipnames, using fuzzy matching
so that every name does not need to be written out by hand.
name: verbose list
wildcard: matching unique string
regex: regex expression
mrca: return ... | entailment |
def node_scale_root_height(self, treeheight=1):
"""
Returns a toytree copy with all nodes scaled so that the root
height equals the value entered for treeheight.
"""
# make tree height = 1 * treeheight
ctree = self._ttree.copy()
_height = ctree.treenode.height
... | Returns a toytree copy with all nodes scaled so that the root
height equals the value entered for treeheight. | entailment |
def node_slider(self, seed=None):
"""
Returns a toytree copy with node heights modified while retaining
the same topology but not necessarily node branching order.
Node heights are moved up or down uniformly between their parent
and highest child node heights in 'levelorder' f... | Returns a toytree copy with node heights modified while retaining
the same topology but not necessarily node branching order.
Node heights are moved up or down uniformly between their parent
and highest child node heights in 'levelorder' from root to tips.
The total tree height is ret... | entailment |
def node_multiplier(self, multiplier=0.5, seed=None):
"""
Returns a toytree copy with all nodes multiplied by a constant
sampled uniformly between (multiplier, 1/multiplier).
"""
random.seed(seed)
ctree = self._ttree.copy()
low, high = sorted([multiplier, 1. / mu... | Returns a toytree copy with all nodes multiplied by a constant
sampled uniformly between (multiplier, 1/multiplier). | entailment |
def make_ultrametric(self, strategy=1):
"""
Returns a tree with branch lengths transformed so that the tree is
ultrametric. Strategies include (1) tip-align: extend tips to the length
of the fartest tip from the root; (2) non-parametric rate-smoothing:
minimize ancestor-descend... | Returns a tree with branch lengths transformed so that the tree is
ultrametric. Strategies include (1) tip-align: extend tips to the length
of the fartest tip from the root; (2) non-parametric rate-smoothing:
minimize ancestor-descendant local rates on branches to align tips (
not yet ... | entailment |
def coaltree(ntips, ne=None, seed=None):
"""
Returns a coalescent tree with ntips samples and waiting times
between coalescent events drawn from the kingman coalescent:
(4N)/(k*(k-1)), where N is population size and k is sample size.
Edge lengths on the tree are in generations.
... | Returns a coalescent tree with ntips samples and waiting times
between coalescent events drawn from the kingman coalescent:
(4N)/(k*(k-1)), where N is population size and k is sample size.
Edge lengths on the tree are in generations.
If no Ne argument is entered then edge lengths are r... | entailment |
def unittree(ntips, treeheight=1.0, seed=None):
"""
Returns a random tree topology w/ N tips and a root height set to
1 or a user-entered treeheight value. Descendant nodes are evenly
spaced between the root and time 0.
Parameters
-----------
ntips (int):
... | Returns a random tree topology w/ N tips and a root height set to
1 or a user-entered treeheight value. Descendant nodes are evenly
spaced between the root and time 0.
Parameters
-----------
ntips (int):
The number of tips in the randomly generated tree
tre... | entailment |
def imbtree(ntips, treeheight=1.0):
"""
Return an imbalanced (comb-like) tree topology.
"""
rtree = toytree.tree()
rtree.treenode.add_child(name="0")
rtree.treenode.add_child(name="1")
for i in range(2, ntips):
# empty node
cherry = toytre... | Return an imbalanced (comb-like) tree topology. | entailment |
def baltree(ntips, treeheight=1.0):
"""
Returns a balanced tree topology.
"""
# require even number of tips
if ntips % 2:
raise ToytreeError("balanced trees must have even number of tips.")
# make first cherry
rtree = toytree.tree()
rtree.tree... | Returns a balanced tree topology. | entailment |
def get_span_char_height(span, row_heights):
"""
Get the height of a span in the number of newlines it fills.
Parameters
----------
span : list of list of int
A list of [row, column] pairs that make up the span
row_heights : list of int
A list of the number of newlines for each ... | Get the height of a span in the number of newlines it fills.
Parameters
----------
span : list of list of int
A list of [row, column] pairs that make up the span
row_heights : list of int
A list of the number of newlines for each row in the table
Returns
-------
total_heigh... | entailment |
def html2data(html_string):
"""
Convert an html table to a data table and spans.
Parameters
----------
html_string : str
The string containing the html table
Returns
-------
table : list of lists of str
spans : list of lists of lists of int
A span is a list of [row,... | Convert an html table to a data table and spans.
Parameters
----------
html_string : str
The string containing the html table
Returns
-------
table : list of lists of str
spans : list of lists of lists of int
A span is a list of [row, column] pairs that define what cells
... | entailment |
def newick(self, tree_format=0):
"Returns newick represenation of the tree in its current state."
# checks one of root's children for features and extra feats.
if self.treenode.children:
features = {"name", "dist", "support", "height", "idx"}
testnode = self.treenode.chil... | Returns newick represenation of the tree in its current state. | entailment |
def get_edge_values(self, feature='idx'):
"""
Returns edge values in the order they are plotted (see .get_edges())
"""
elist = []
for cidx in self._coords.edges[:, 1]:
node = self.treenode.search_nodes(idx=cidx)[0]
elist.append(
(node.__get... | Returns edge values in the order they are plotted (see .get_edges()) | entailment |
def get_edge_values_from_dict(self, node_value_dict=None, include_stem=True):
"""
Enter a dictionary mapping node 'idx' or tuple of tipnames to values
that you want mapped to the stem and descendant edges that node.
Edge values are returned in proper plot order to be entered to the
... | Enter a dictionary mapping node 'idx' or tuple of tipnames to values
that you want mapped to the stem and descendant edges that node.
Edge values are returned in proper plot order to be entered to the
edge_colors or edge_widths arguments to draw(). To see node idx values
use node_lab... | entailment |
def get_mrca_idx_from_tip_labels(self, names=None, wildcard=None, regex=None):
"""
Returns the node idx label of the most recent common ancestor node
for the clade that includes the selected tips. Arguments can use fuzzy
name matching: a list of tip names, wildcard selector, or regex st... | Returns the node idx label of the most recent common ancestor node
for the clade that includes the selected tips. Arguments can use fuzzy
name matching: a list of tip names, wildcard selector, or regex string. | entailment |
def get_node_values(
self,
feature=None,
show_root=False,
show_tips=False,
):
"""
Returns node values from tree object in node plot order. To modify
values you must modify the .treenode object directly by setting new
'features'. For example
... | Returns node values from tree object in node plot order. To modify
values you must modify the .treenode object directly by setting new
'features'. For example
for node in ttree.treenode.traverse():
node.add_feature("PP", 100)
By default node and tip values are hidden (set t... | entailment |
def get_node_dict(self, return_internal=False, return_nodes=False):
"""
Return node labels as a dictionary mapping {idx: name} where idx is
the order of nodes in 'preorder' traversal. Used internally by the
func .get_node_values() to return values in proper order.
return_inter... | Return node labels as a dictionary mapping {idx: name} where idx is
the order of nodes in 'preorder' traversal. Used internally by the
func .get_node_values() to return values in proper order.
return_internal: if True all nodes are returned, if False only tips.
return_nodes: if True r... | entailment |
def get_tip_coordinates(self, axis=None):
"""
Returns coordinates of the tip positions for a tree. If no argument
for axis then a 2-d array is returned. The first column is the x
coordinates the second column is the y-coordinates. If you enter an
argument for axis then a 1-d ar... | Returns coordinates of the tip positions for a tree. If no argument
for axis then a 2-d array is returned. The first column is the x
coordinates the second column is the y-coordinates. If you enter an
argument for axis then a 1-d array will be returned of just that axis. | entailment |
def get_tip_labels(self, idx=None):
"""
Returns tip labels in the order they will be plotted on the tree, i.e.,
starting from zero axis and counting up by units of 1 (bottom to top
in right-facing trees; left to right in down-facing). If 'idx' is
indicated then a list of tip la... | Returns tip labels in the order they will be plotted on the tree, i.e.,
starting from zero axis and counting up by units of 1 (bottom to top
in right-facing trees; left to right in down-facing). If 'idx' is
indicated then a list of tip labels descended from that node will be
returned,... | entailment |
def is_bifurcating(self, include_root=True):
"""
Returns False if there is a polytomy in the tree, including if the tree
is unrooted (basal polytomy), unless you use the include_root=False
argument.
"""
ctn1 = -1 + (2 * len(self))
ctn2 = -2 + (2 * len(self))
... | Returns False if there is a polytomy in the tree, including if the tree
is unrooted (basal polytomy), unless you use the include_root=False
argument. | entailment |
def ladderize(self, direction=0):
"""
Ladderize tree (order descendants) so that top child has fewer
descendants than the bottom child in a left to right tree plot.
To reverse this pattern use direction=1.
"""
nself = deepcopy(self)
nself.treenode.ladderize(dire... | Ladderize tree (order descendants) so that top child has fewer
descendants than the bottom child in a left to right tree plot.
To reverse this pattern use direction=1. | entailment |
def collapse_nodes(self, min_dist=1e-6, min_support=0):
"""
Returns a copy of the tree where internal nodes with dist <= min_dist
are deleted, resulting in a collapsed tree. e.g.:
newtre = tre.collapse_nodes(min_dist=0.001)
newtre = tre.collapse_nodes(min_support=50)
"""... | Returns a copy of the tree where internal nodes with dist <= min_dist
are deleted, resulting in a collapsed tree. e.g.:
newtre = tre.collapse_nodes(min_dist=0.001)
newtre = tre.collapse_nodes(min_support=50) | entailment |
def drop_tips(self, names=None, wildcard=None, regex=None):
"""
Returns a copy of the tree with the selected tips removed. The entered
value can be a name or list of names. To prune on an internal node to
create a subtree see the .prune() function instead.
Parameters:
ti... | Returns a copy of the tree with the selected tips removed. The entered
value can be a name or list of names. To prune on an internal node to
create a subtree see the .prune() function instead.
Parameters:
tips: list of tip names.
# example:
ptre = tre.drop_tips(['a', 'b... | entailment |
def rotate_node(
self,
names=None,
wildcard=None,
regex=None,
idx=None,
# modify_tree=False,
):
"""
Returns a ToyTree with the selected node rotated for plotting.
tip colors do not align correct currently if nodes are rotated...
... | Returns a ToyTree with the selected node rotated for plotting.
tip colors do not align correct currently if nodes are rotated... | entailment |
def resolve_polytomy(
self,
dist=1.0,
support=100,
recursive=True):
"""
Returns a copy of the tree with all polytomies randomly resolved.
Does not transform tree in-place.
"""
nself = self.copy()
nself.treenode.resolve_polytomy(
... | Returns a copy of the tree with all polytomies randomly resolved.
Does not transform tree in-place. | entailment |
def unroot(self):
"""
Returns a copy of the tree unrooted. Does not transform tree in-place.
"""
nself = self.copy()
nself.treenode.unroot()
nself.treenode.ladderize()
nself._coords.update()
return nself | Returns a copy of the tree unrooted. Does not transform tree in-place. | entailment |
def root(self, names=None, wildcard=None, regex=None):
"""
(Re-)root a tree by creating selecting a existing split in the tree,
or creating a new node to split an edge in the tree. Rooting location
is selected by entering the tips descendant from one child of the root
split (e.g.... | (Re-)root a tree by creating selecting a existing split in the tree,
or creating a new node to split an edge in the tree. Rooting location
is selected by entering the tips descendant from one child of the root
split (e.g., names='a' or names=['a', 'b']). You can alternatively
select a li... | entailment |
def draw(
self,
tree_style=None,
height=None,
width=None,
axes=None,
orient=None,
tip_labels=None,
tip_labels_colors=None,
tip_labels_style=None,
tip_labels_align=None,
node_labels=None,
node_labels_style=None,
... | Plot a Toytree tree, returns a tuple of Toyplot (Canvas, Axes) objects.
Parameters:
-----------
tree_style: str
One of several preset styles for tree plotting. The default is 'n'
(normal). Other options inlude 'c' (coalescent), 'd' (dark), and
'm' (multitree)... | entailment |
def get_merge_direction(cell1, cell2):
"""
Determine the side of cell1 that can be merged with cell2.
This is based on the location of the two cells in the table as well
as the compatability of their height and width.
For example these cells can merge::
cell1 cell2 merge "RIGHT"
... | Determine the side of cell1 that can be merged with cell2.
This is based on the location of the two cells in the table as well
as the compatability of their height and width.
For example these cells can merge::
cell1 cell2 merge "RIGHT"
+-----+ +------+ +-----+------+
... | entailment |
def parse_nhx(NHX_string):
"""
NHX format: [&&NHX:prop1=value1:prop2=value2]
MB format: ((a[&Z=1,Y=2], b[&Z=1,Y=2]):1.0[&L=1,W=0], ...
"""
# store features
ndict = {}
# parse NHX or MB features
if "[&&NHX:" in NHX_string:
NHX_string = NHX_string.replace("[&&NHX:", "")
... | NHX format: [&&NHX:prop1=value1:prop2=value2]
MB format: ((a[&Z=1,Y=2], b[&Z=1,Y=2]):1.0[&L=1,W=0], ... | entailment |
def get_data_from_intree(self):
"""
Load *data* from a file or string and return as a list of strings.
The data contents could be one newick string; a multiline NEXUS format
for one tree; multiple newick strings on multiple lines; or multiple
newick strings in a multiline NEXUS f... | Load *data* from a file or string and return as a list of strings.
The data contents could be one newick string; a multiline NEXUS format
for one tree; multiple newick strings on multiple lines; or multiple
newick strings in a multiline NEXUS format. In any case, we will read
in the data... | entailment |
def parse_nexus(self):
"get newick data from NEXUS"
if self.data[0].strip().upper() == "#NEXUS":
nex = NexusParser(self.data)
self.data = nex.newicks
self.tdict = nex.tdict | get newick data from NEXUS | entailment |
def get_treenodes(self):
"test format of intree nex/nwk, extra features"
if not self.multitree:
# get TreeNodes from Newick
extractor = Newick2TreeNode(self.data[0].strip(), fmt=self.fmt)
# extract one tree
self.treenodes.append(extractor.newick_... | test format of intree nex/nwk, extra features | entailment |
def newick_from_string(self):
"Reads a newick string in the New Hampshire format."
# split on parentheses to traverse hierarchical tree structure
for chunk in self.data.split("(")[1:]:
# add child to make this node a parent.
self.current_parent = (
self.r... | Reads a newick string in the New Hampshire format. | entailment |
def extract_tree_block(self):
"iterate through data file to extract trees"
lines = iter(self.data)
while 1:
try:
line = next(lines).strip()
except StopIteration:
break
# enter trees block
if line.lower(... | iterate through data file to extract trees | entailment |
def parse_command_line():
""" Parse CLI args."""
## create the parser
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
* Example command-line usage:
## push test branch to conda --label=conda-test for travis CI
./versioner.py -p toyt... | Parse CLI args. | entailment |
def get_git_status(self):
"""
Gets git and init versions and commits since the init version
"""
## get git branch
self._get_git_branch()
## get tag in the init file
self._get_init_release_tag()
## get log commits since <tag>
try:
self... | Gets git and init versions and commits since the init version | entailment |
def push_git_package(self):
"""
if no conflicts then write new tag to
"""
## check for conflicts, then write to local files
self._pull_branch_from_origin()
## log commits to releasenotes
if self.deploy:
self._write_commits_to_release_notes()
... | if no conflicts then write new tag to | entailment |
def _pull_branch_from_origin(self):
"""
Pulls from origin/master, if you have unmerged conflicts
it will raise an exception. You will need to resolve these.
"""
try:
## self.repo.git.pull()
subprocess.check_call(["git", "pull", "origin", self.branch])
... | Pulls from origin/master, if you have unmerged conflicts
it will raise an exception. You will need to resolve these. | entailment |
def _get_init_release_tag(self):
"""
parses init.py to get previous version
"""
self.init_version = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
open(self.init_file, "r").read(),
re.M).group(1) | parses init.py to get previous version | entailment |
def _get_log_commits(self):
"""
calls git log to complile a change list
"""
## check if update is necessary
cmd = "git log --pretty=oneline {}..".format(self.init_version)
cmdlist = shlex.split(cmd)
commits = subprocess.check_output(cmdlist)
## Sp... | calls git log to complile a change list | entailment |
def _write_commits_to_release_notes(self):
"""
writes commits to the releasenotes file by appending to the end
"""
with open(self.release_file, 'a') as out:
out.write("==========\n{}\n".format(self.tag))
for commit in self.commits:
try:
... | writes commits to the releasenotes file by appending to the end | entailment |
def _write_new_tag_to_init(self):
"""
Write version to __init__.py by editing in place
"""
for line in fileinput.input(self.init_file, inplace=1):
if line.strip().startswith("__version__"):
line = "__version__ = \"" + self.tag + "\""
print(line.str... | Write version to __init__.py by editing in place | entailment |
def _write_branch_and_tag_to_meta_yaml(self):
"""
Write branch and tag to meta.yaml by editing in place
"""
## set the branch to pull source from
with open(self.meta_yaml.replace("meta", "template"), 'r') as infile:
dat = infile.read()
newdat = dat.format(... | Write branch and tag to meta.yaml by editing in place | entailment |
def _revert_tag_in_init(self):
"""
Write version to __init__.py by editing in place
"""
for line in fileinput.input(self.init_file, inplace=1):
if line.strip().startswith("__version__"):
line = "__version__ = \"" + self.init_version + "\""
print(li... | Write version to __init__.py by editing in place | entailment |
def _push_new_tag_to_git(self):
"""
tags a new release and pushes to origin/master
"""
print("Pushing new version to git")
## stage the releasefile and initfileb
subprocess.call(["git", "add", self.release_file])
subprocess.call(["git", "add", self.in... | tags a new release and pushes to origin/master | entailment |
def build_conda_packages(self):
"""
Run the Linux build and use converter to build OSX
"""
## check if update is necessary
#if self.nversion == self.pversion:
# raise SystemExit("Exited: new version == existing version")
## tmp dir
bldir = "./tmp-bld"
... | Run the Linux build and use converter to build OSX | entailment |
def get_span_row_count(span):
"""
Gets the number of rows included in a span
Parameters
----------
span : list of lists of int
The [row, column] pairs that make up the span
Returns
-------
rows : int
The number of rows included in the span
Example
-------
C... | Gets the number of rows included in a span
Parameters
----------
span : list of lists of int
The [row, column] pairs that make up the span
Returns
-------
rows : int
The number of rows included in the span
Example
-------
Consider this table::
+--------+--... | entailment |
def asarray(x, dtype=None):
'''Convert ``x`` into a ``numpy.ndarray``.'''
iterable = scalarasiter(x)
if isinstance(iterable, ndarray):
return iterable
else:
if not hasattr(iterable, '__len__'):
iterable = list(iterable)
if dtype == object_type:
a ... | Convert ``x`` into a ``numpy.ndarray``. | entailment |
def ascolumn(x, dtype = None):
'''Convert ``x`` into a ``column``-type ``numpy.ndarray``.'''
x = asarray(x, dtype)
return x if len(x.shape) >= 2 else x.reshape(len(x),1) | Convert ``x`` into a ``column``-type ``numpy.ndarray``. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.