code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
jobs = itertools.combinations(trees, 2)
results = []
if show_progress:
pbar = setup_progressbar('Calculating tree distances', 0.5 * len(trees) * (len(trees) - 1))
pbar.start()
for i, (t1, t2) in enumerate(jobs):
results.append(_generic_distance_calc(fn, t1, t2, normalise, mi... | def _generic_matrix_calc(fn, trees, normalise, min_overlap=4, overlap_fail_value=0, show_progress=True) | (fn, trees, normalise)
Calculates all pairwise distances between trees given in the parameter 'trees'.
Distance functions:
eucdist_matrix
geodist_matrix
rfdist_matrix
wrfdist_matrix
These wrap the leafset-checking functions. If the faster non-leafset-checking functions are... | 2.151952 | 2.294523 | 0.937865 |
assert isinstance(dm, DistanceMatrix)
datamax = float(np.abs(dm.values).max())
length = dm.shape[0]
if partition:
sorting = np.array(flatten_list(partition.get_membership()))
new_dm = dm.reorder(dm.df.columns[sorting])
else:
new_dm = dm
fig = plt.figure()
ax = ... | def heatmap(dm, partition=None, cmap=CM.Blues, fontsize=10) | heatmap(dm, partition=None, cmap=CM.Blues, fontsize=10)
Produce a 2D plot of the distance matrix, with values encoded by
coloured cells.
Args:
partition: treeCl.Partition object - if supplied, will reorder
rows and columns of the distance matrix to reflect
... | 2.610468 | 2.651875 | 0.984386 |
from plotly.graph_objs import Scatter3d, Data, Figure, Layout, Line, Margin, Marker
# auto sign-in with credentials or use py.sign_in()
colourmap = {
'A':'#1f77b4',
'B':'#ff7f0e',
'C':'#2ca02c',
'D':'#d62728',
'E':'#9467bd',
1:'#1f77b4',
2:'#f... | def _plotly_3d_scatter(coords, partition=None) | _plotly_3d_scatter(coords, partition=None)
Make a scatterplot of treeCl.CoordinateMatrix using the Plotly
plotting engine | 2.479476 | 2.535842 | 0.977772 |
(u, v) = np.mgrid[0:2 * np.pi:20j, 0:np.pi:10j]
x = np.cos(u) * np.sin(v)
y = np.sin(u) * np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color='grey', linewidth=0.2)
return ax | def _add_sphere(ax) | _add_sphere(ax)
Add a wireframe unit sphere onto matplotlib 3D axes
Args:
ax - matplotlib 3D axes object
Returns:
updated matplotlib 3D axes | 1.524902 | 1.814333 | 0.840475 |
if isinstance(coordinates, CoordinateMatrix):
coordinates = coordinates.values
dimensions = min(3, coordinates.shape[1])
partition = (partition or
Partition(tuple([0] * len(coordinates))))
ngrp = partition.num_groups()
if colours is None:
colours = SET2
eli... | def plot_embedding(coordinates, partition=None, add_sphere=False, point_size=8,
colours=None, labels=None, legend=True, outfile=False, **kwargs) | plot_embedding(coordinates, partition=None, add_sphere=False, point_size=8,
colours=None, labels=None, legend=True, outfile=False, **kwargs):
Plot a 2D / 3D scatterplot of coordinates, optionally
coloured by group membership.
Args:
coordinates: numpy array or treeCl.CoordinateMatrix -
... | 2.765766 | 2.55731 | 1.081514 |
if isinstance(self.dm, DistanceMatrix):
length = self.dm.values.shape[0]
else:
length = self.dm.shape[0]
datamax = float(np.abs(self.dm).max())
fig = plt.figure()
ax = fig.add_subplot(111)
ticks_at = [0, 0.5 * datamax, datamax]
if... | def heatmap(self, partition=None, cmap=CM.Blues) | Plots a visual representation of a distance matrix | 3.016983 | 2.942586 | 1.025283 |
records = [self.collection[i] for i in self.indices]
return TreeCollectionTaskInterface().scrape_args(records) | def get_tree_collection_strings(self, scale=1, guide_tree=None) | Function to get input strings for tree_collection
tree_collection needs distvar, genome_map and labels -
these are returned in the order above | 26.547909 | 23.422039 | 1.133458 |
buffer = to_bytes(buffer)
view_out = _ffi.new('lsm_view_t **')
index_out = _ffi.new('lsm_index_t **')
buffer = to_bytes(buffer)
rv = rustcall(
_lib.lsm_view_or_index_from_json,
buffer, len(buffer), view_out, index_out)
if rv == 1:
return View._from_ptr(view_out[0])... | def from_json(buffer, auto_flatten=True, raise_for_index=True) | Parses a JSON string into either a view or an index. If auto flatten
is enabled a sourcemap index that does not contain external references is
automatically flattened into a view. By default if an index would be
returned an `IndexedSourceMap` error is raised instead which holds the
index. | 4.208173 | 3.919822 | 1.073562 |
buffer = to_bytes(buffer)
return View._from_ptr(rustcall(
_lib.lsm_view_from_json,
buffer, len(buffer))) | def from_json(buffer) | Creates a sourcemap view from a JSON string. | 9.464088 | 8.744939 | 1.082236 |
buffer = to_bytes(buffer)
return View._from_ptr(rustcall(
_lib.lsm_view_from_memdb,
buffer, len(buffer))) | def from_memdb(buffer) | Creates a sourcemap view from MemDB bytes. | 9.49467 | 7.601966 | 1.248976 |
path = to_bytes(path)
return View._from_ptr(rustcall(_lib.lsm_view_from_memdb_file, path)) | def from_memdb_file(path) | Creates a sourcemap view from MemDB at a given file. | 11.477553 | 9.050686 | 1.268142 |
len_out = _ffi.new('unsigned int *')
buf = rustcall(
_lib.lsm_view_dump_memdb,
self._get_ptr(), len_out,
with_source_contents, with_names)
try:
rv = _ffi.unpack(buf, len_out[0])
finally:
_lib.lsm_buffer_free(buf)
... | def dump_memdb(self, with_source_contents=True, with_names=True) | Dumps a sourcemap in MemDB format into bytes. | 4.700698 | 4.507793 | 1.042794 |
# Silently ignore underflows
if line < 0 or col < 0:
return None
tok_out = _ffi.new('lsm_token_t *')
if rustcall(_lib.lsm_view_lookup_token, self._get_ptr(),
line, col, tok_out):
return convert_token(tok_out[0]) | def lookup_token(self, line, col) | Given a minified location, this tries to locate the closest
token that is a match. Returns `None` if no match can be found. | 6.767307 | 6.867098 | 0.985468 |
# Silently ignore underflows
if line < 0 or col < 0:
return None
minified_name = minified_name.encode('utf-8')
sout = _ffi.new('const char **')
try:
slen = rustcall(_lib.lsm_view_get_original_function_name,
self._get_pt... | def get_original_function_name(self, line, col, minified_name,
minified_source) | Given a token location and a minified function name and the
minified source file this returns the original function name if it
can be found of the minified function in scope. | 7.093966 | 7.235851 | 0.980391 |
len_out = _ffi.new('unsigned int *')
must_free = _ffi.new('int *')
rv = rustcall(_lib.lsm_view_get_source_contents,
self._get_ptr(), src_id, len_out, must_free)
if rv:
try:
return _ffi.unpack(rv, len_out[0])
finally:
... | def get_source_contents(self, src_id) | Given a source ID this returns the embedded sourcecode if there
is. The sourcecode is returned as UTF-8 bytes for more efficient
processing. | 4.245072 | 4.020792 | 1.05578 |
return bool(rustcall(_lib.lsm_view_has_source_contents,
self._get_ptr(), src_id)) | def has_source_contents(self, src_id) | Checks if some sources exist. | 16.797361 | 14.638842 | 1.147452 |
len_out = _ffi.new('unsigned int *')
rv = rustcall(_lib.lsm_view_get_source_name,
self._get_ptr(), src_id, len_out)
if rv:
return decode_rust_str(rv, len_out[0]) | def get_source_name(self, src_id) | Returns the name of the given source. | 7.351928 | 6.683564 | 1.100001 |
for src_id in xrange(self.get_source_count()):
yield src_id, self.get_source_name(src_id) | def iter_sources(self) | Iterates over all source names and IDs. | 3.882912 | 2.946509 | 1.317801 |
buffer = to_bytes(buffer)
return Index._from_ptr(rustcall(
_lib.lsm_index_from_json,
buffer, len(buffer))) | def from_json(buffer) | Creates an index from a JSON string. | 9.293966 | 5.888753 | 1.578257 |
try:
return View._from_ptr(rustcall(
_lib.lsm_index_into_view,
self._get_ptr()))
finally:
self._ptr = None | def into_view(self) | Converts the index into a view | 9.129258 | 7.940708 | 1.149678 |
buffer = to_bytes(buffer)
return ProguardView._from_ptr(rustcall(
_lib.lsm_proguard_mapping_from_bytes,
buffer, len(buffer))) | def from_bytes(buffer) | Creates a sourcemap view from a JSON string. | 13.470891 | 11.493444 | 1.17205 |
filename = to_bytes(filename)
if NULL_BYTE in filename:
raise ValueError('null byte in path')
return ProguardView._from_ptr(rustcall(
_lib.lsm_proguard_mapping_from_path,
filename + b'\x00')) | def from_path(filename) | Creates a sourcemap view from a file path. | 10.949898 | 9.405971 | 1.164143 |
rv = None
try:
rv = rustcall(
_lib.lsm_proguard_mapping_convert_dotted_path,
self._get_ptr(),
dotted_path.encode('utf-8'), lineno or 0)
return _ffi.string(rv).decode('utf-8', 'replace')
finally:
if rv is... | def lookup(self, dotted_path, lineno=None) | Given a dotted path in the format ``class_name`` or
``class_name:method_name`` this performs an alias lookup. For
methods the line number must be supplied or the result is
unreliable. | 5.90177 | 6.308271 | 0.935561 |
if self.visitor.is_object:
obj = {}
if self.visitor.parent is None:
obj['$schema'] = self.visitor.path
obj_empty = True
for child in self.children:
empty, value = child.apply(data)
if empty and child.optiona... | def apply(self, data) | Apply the given mapping to ``data``, recursively. The return type
is a tuple of a boolean and the resulting data element. The boolean
indicates whether any values were mapped in the child nodes of the
mapping. It is used to skip optional branches of the object graph. | 3.168386 | 3.13049 | 1.012106 |
mapper = cls(mapping, resolver, scope=scope)
for row in rows:
_, data = mapper.apply(row)
yield data | def apply_iter(cls, rows, mapping, resolver, scope=None) | Given an iterable ``rows`` that yield data records, and a
``mapping`` which is to be applied to them, return a tuple of
``data`` (the generated object graph) and ``err``, a validation
exception if the resulting data did not match the expected schema. | 4.168531 | 4.613099 | 0.903629 |
# Reset substitution counter
self.count = 0
# Process text
return self._make_regex().sub(self, text) | def translate(self, text) | Translate text, returns the modified text. | 10.890523 | 11.685753 | 0.931949 |
matrix = self.get_dm(noise)
# get local scale estimate
est_scale = None
# ADJUST MASK
if self._pruning_option == options.PRUNING_NONE:
# Set kp to max value
kp = len(matrix) - 1
mask = np.ones(matrix.shape, dtype=bool)
elif... | def decompose(self,
noise=False,
verbosity=0,
logic='or',
**kwargs) | Use prune to remove links between distant points:
prune is None: no pruning
prune={int > 0}: prunes links beyond `prune` nearest neighbours
prune='estimate': searches for the smallest value that retains a fully
connected graph | 3.9171 | 3.981822 | 0.983746 |
if n == 1:
return Partition([1] * len(self.get_dm(False)))
if embed_dim is None:
embed_dim = n
if algo == spectral.SPECTRAL:
self._coords = self.spectral_embedding(embed_dim)
elif algo == spectral.KPCA:
self._coords = self.kpca_e... | def cluster(self, n, embed_dim=None, algo=spectral.SPECTRAL, method=methods.KMEANS) | Cluster the embedded coordinates using spectral clustering
Parameters
----------
n: int
The number of clusters to return
embed_dim: int
The dimensionality of the underlying coordinates
... | 3.595902 | 2.914519 | 1.233789 |
coords = spectral_embedding(self._affinity, n)
return CoordinateMatrix(normalise_rows(coords)) | def spectral_embedding(self, n) | Embed the points using spectral decomposition of the laplacian of
the affinity matrix
Parameters
----------
n: int
The number of dimensions | 23.529716 | 49.585072 | 0.474532 |
aff = self._affinity.copy()
aff.flat[::aff.shape[0]+1] = 0
laplacian = laplace(aff)
decomp = eigen(laplacian)
return CoordinateMatrix(normalise_rows(decomp.vecs[:,:n])) | def spectral_embedding_(self, n) | Old method for generating coords, used on original analysis
of yeast data. Included to reproduce yeast result from paper.
Reason for difference - switched to using spectral embedding
method provided by scikit-learn (mainly because it spreads
points over a sphere, rather than a half sphe... | 7.969263 | 6.670038 | 1.194785 |
return self.dm.embedding(n, 'kpca', affinity_matrix=self._affinity) | def kpca_embedding(self, n) | Embed the points using kernel PCA of the affinity matrix
Parameters
----------
n: int
The number of dimensions | 18.511173 | 22.492579 | 0.82299 |
if n == 1:
return Partition([1] * len(self.get_dm(False)))
if embed_dim is None:
embed_dim = n
if algo == mds.CLASSICAL:
self._coords = self.dm.embedding(embed_dim, 'cmds')
elif algo == mds.METRIC:
self._coords = self.dm.embeddin... | def cluster(self, n, embed_dim=None, algo=mds.CLASSICAL, method=methods.KMEANS) | Cluster the embedded coordinates using multidimensional scaling
Parameters
----------
n: int
The number of clusters to return
embed_dim int
The dimensionality of the underlying coordinates
... | 3.548616 | 3.423917 | 1.03642 |
if linkage_method == linkage.SINGLE:
return self._hclust(nclusters, 'single', **kwargs)
elif linkage_method == linkage.COMPLETE:
return self._hclust(nclusters, 'complete', **kwargs)
elif linkage_method == linkage.AVERAGE:
return self._hclust(ncluster... | def cluster(self, nclusters, linkage_method=linkage.WARD, **kwargs) | Do hierarchical clustering on a distance matrix using one of the methods:
methods.SINGLE = single-linkage clustering
methods.COMPLETE = complete-linkage clustering
methods.AVERAGE = average-linkage clustering
methods.WARD = Ward's minimum variance method | 1.372905 | 1.360564 | 1.009071 |
matrix = self.get_dm(noise)
linkmat = fastcluster.linkage(squareform(matrix), method)
self.nclusters = nclusters # Store these in case we want to plot
self.linkmat = linkmat #
return _hclust(linkmat, nclusters) | def _hclust(self, nclusters, method, noise=False) | :param nclusters: Number of clusters to return
:param linkage_method: single, complete, average, ward, weighted, centroid or median
(http://docs.scipy.org/doc/scipy/reference/cluster.hierarchy.html)
:param noise: Add Gaussian noise to the distance matrix prior to clusterin... | 7.723025 | 9.112922 | 0.847481 |
if not hasattr(self, 'nclusters') and not hasattr(self, 'linkmat'):
raise ValueError("This instance has no plottable information.")
if nclusters is None:
nclusters = self.nclusters
threshold = _get_threshold(self.linkmat, nclusters)
import matplotlib.... | def plot_dendrogram(self, nclusters=None, leaf_font_size=8, leaf_rotation=90, names=None,
title_font_size=16, ) | Plots the dendrogram of the most recently generated partition
:param nclusters: Override the plot default number of clusters
:return: matplotlib.pyplot.figure | 3.108653 | 3.121955 | 0.995739 |
est = DBSCAN(metric='precomputed', eps=eps, min_samples=min_samples)
est.fit(self.get_dm(False))
return Partition(est.labels_) | def dbscan(self, eps=0.75, min_samples=3) | :param kwargs: key-value arguments to pass to DBSCAN
(eps: max dist between points in same neighbourhood,
min_samples: number of points in a neighbourhood)
:return: | 4.590135 | 6.434031 | 0.713415 |
if ISPY3:
sep = bytes(sep, DEFAULT_ENCODING)
joined = sep.join(joinable)
return joined.decode(DEFAULT_ENCODING) if ISPY3 else joined | def _py2_and_3_joiner(sep, joinable) | Allow '\n'.join(...) statements to work in Py2 and Py3.
:param sep:
:param joinable:
:return: | 3.803146 | 4.291421 | 0.886221 |
# thread function to log subprocess output (LOG is a queue)
def enqueue_output(out, q):
for line in iter(out.readline, b''):
q.put(line.rstrip())
out.close()
# start thread
t = threading.Thread(target=enqueue_output,
... | def _log_thread(self, pipe, queue) | Start a thread logging output from pipe | 3.519856 | 3.414315 | 1.030912 |
if os.path.isfile(executable):
return os.path.abspath(executable)
else:
envpath = os.getenv('PATH')
if envpath is None:
return
for path in envpath.split(os.pathsep):
exe = os.path.join(path, executable)
... | def _search_for_executable(self, executable) | Search for file give in "executable". If it is not found, we try the environment PATH.
Returns either the absolute path to the found executable, or None if the executable
couldn't be found. | 1.81235 | 1.666529 | 1.0875 |
if self.finished():
self.join_threads()
while not self.stderr_q.empty():
self.stderr_l.append(self.stderr_q.get_nowait())
if tail is None:
tail = len(self.stderr_l)
return _py2_and_3_joiner('\n', self.stderr_l[:tail]) | def get_stderr(self, tail=None) | Returns current total output written to standard error.
:param tail: Return this number of most-recent lines.
:return: copy of stderr stream | 4.26833 | 4.445822 | 0.960077 |
if self.finished():
self.join_threads()
while not self.stdout_q.empty():
self.stdout_l.append(self.stdout_q.get_nowait())
if tail is None:
tail = len(self.stdout_l)
return _py2_and_3_joiner('\n', self.stdout_l[:tail]) | def get_stdout(self, tail=None) | Returns current total output written to standard output.
:param tail: Return this number of most-recent lines.
:return: copy of stdout stream | 4.234401 | 4.414129 | 0.959283 |
if self.running():
if self.verbose:
print('Killing {} with PID {}'.format(self.exe, self.process.pid))
self.process.kill()
# Threads *should* tidy up after themselves, but we do it explicitly
self.join_threads() | def kill(self) | Kill the running process (if there is one)
:return: void | 6.901236 | 6.676747 | 1.033622 |
command = ["java", "-jar", self.file_jar, "-eUTF-8"]
if self.memory_allocation:
command.append("-Xmx{}".format(self.memory_allocation))
command.extend(switches)
if not objectInput:
objectInput = subprocess.PIPE
log.debug("Subprocess command: {}"... | def _command_template(self, switches, objectInput=None) | Template for Tika app commands
Args:
switches (list): list of switches to Tika app Jar
objectInput (object): file object/standard input to analyze
Return:
Standard output data (unicode Python 2, str Python 3) | 2.642954 | 2.557392 | 1.033457 |
# From Python detection content type from stdin doesn't work TO FIX
if objectInput:
message = "Detection content type with file object is not stable."
log.exception(message)
raise TikaAppError(message)
f = file_path(path, payload, objectInput)
... | def detect_content_type(self, path=None, payload=None, objectInput=None) | Return the content type of passed file or payload.
Args:
path (string): Path of file to analyze
payload (string): Payload base64 to analyze
objectInput (object): file object/standard input to analyze
Returns:
content type of file (string) | 17.93133 | 18.138018 | 0.988605 |
if objectInput:
switches = ["-t"]
result = self._command_template(switches, objectInput)
return result, True, None
else:
f = file_path(path, payload)
switches = ["-t", f]
result = self._command_template(switches)
... | def extract_only_content(self, path=None, payload=None, objectInput=None) | Return only the text content of passed file.
These parameters are in OR. Only one of them can be analyzed.
Args:
path (string): Path of file to analyze
payload (string): Payload base64 to analyze
objectInput (object): file object/standard input to analyze
Re... | 5.704831 | 6.287196 | 0.907373 |
f = file_path(path, payload, objectInput)
switches = ["-J", "-t", "-r", f]
if not pretty_print:
switches.remove("-r")
result = self._command_template(switches)
if result and convert_to_obj:
result = json.loads(result, encoding="utf-8")
r... | def extract_all_content(
self,
path=None,
payload=None,
objectInput=None,
pretty_print=False,
convert_to_obj=False,
) | This function returns a JSON of all contents and
metadata of passed file
Args:
path (string): Path of file to analyze
payload (string): Payload base64 to analyze
objectInput (object): file object/standard input to analyze
pretty_print (boolean): If True a... | 5.389287 | 6.488965 | 0.830531 |
def wrapper(*args, **kwargs):
return normalize('NFC', func(*args, **kwargs))
return wrapper | def sanitize(func) | NFC is the normalization form recommended by W3C. | 5.438988 | 4.097136 | 1.32751 |
def wrapper(*args, **kwargs):
# tuple: output command, path given from command line,
# path of templ file when you give the payload
out, given_path, path = func(*args, **kwargs)
try:
if not given_path:
os.remove(path)
except OSError:
... | def clean(func) | This decorator removes the temp file from disk. This is the case where
you want to analyze from a payload. | 8.365708 | 7.357136 | 1.137088 |
f = path if path else write_payload(payload, objectInput)
if not os.path.exists(f):
msg = "File {!r} does not exist".format(f)
log.exception(msg)
raise TikaAppFilePathError(msg)
return f | def file_path(path=None, payload=None, objectInput=None) | Given a file path, payload or file object, it writes file on disk and
returns the temp path.
Args:
path (string): path of real file
payload(string): payload in base64 of file
objectInput (object): file object/standard input to analyze
Returns:
Path of file | 5.458083 | 7.184263 | 0.759728 |
temp = tempfile.mkstemp()[1]
log.debug("Write payload in temp file {!r}".format(temp))
with open(temp, 'wb') as f:
if payload:
payload = base64.b64decode(payload)
elif objectInput:
if six.PY3:
payload = objectInput.buffer.read()
elif... | def write_payload(payload=None, objectInput=None) | This function writes a base64 payload or file object on disk.
Args:
payload (string): payload in base64
objectInput (object): file object/standard input to analyze
Returns:
Path of file | 2.926318 | 2.879941 | 1.016103 |
if not isinstance(data, Mapping):
return None
if data.get(self.subject):
return data.get(self.subject)
return uuid.uuid4().urn | def get_subject(self, data) | Try to get a unique ID from the object. By default, this will be
the 'id' field of any given object, or a field specified by the
'rdfSubject' property. If no other option is available, a UUID will be
generated. | 4.644497 | 3.924314 | 1.183518 |
name = self.schema.get('rdfReverse')
if name is not None:
return name
if self.parent is not None and self.parent.is_array:
return self.parent.reverse | def reverse(self) | Reverse links make sense for object to object links where we later
may want to also query the reverse of the relationship, e.g. when obj1
is a child of obj2, we want to infer that obj2 is a parent of obj1. | 6.148985 | 6.441741 | 0.954553 |
if data is None:
return
if self.is_object:
for res in self._triplify_object(data, parent):
yield res
elif self.is_array:
for item in data:
for res in self.items.triplify(item, parent):
yield res
... | def triplify(self, data, parent=None) | Recursively generate statements from the data supplied. | 4.443321 | 4.441955 | 1.000308 |
subject = self.get_subject(data)
if self.path:
yield (subject, TYPE_SCHEMA, self.path, TYPE_SCHEMA)
if parent is not None:
yield (parent, self.predicate, subject, TYPE_LINK)
if self.reverse is not None:
yield (subject, self.reverse, p... | def _triplify_object(self, data, parent) | Create bi-directional statements for object relationships. | 3.843882 | 3.504061 | 1.096979 |
if path is None:
path = set()
if self.is_object:
if depth < 1:
return
return self._objectify_object(load, node, depth, path)
elif self.is_array:
if depth < 1:
return
return [self.items.objectify... | def objectify(self, load, node, depth=2, path=None) | Given a node ID, return an object the information available about
this node. This accepts a loader function as it's first argument, which
is expected to return all tuples of (predicate, object, source) for
the given subject. | 2.996125 | 3.253893 | 0.920782 |
result = []
searchtext = request.GET['q']
if len(searchtext) >= 3:
pickled = _simple_autocomplete_queryset_cache.get(token, None)
if pickled is not None:
app_label, model_name, query = pickle.loads(pickled)
model = apps.get_model(app_label, model_name)
... | def get_json(request, token) | Return matching results as JSON | 2.914148 | 2.894168 | 1.006903 |
with open(info_filename) as fl:
models, likelihood, partition_params = self._dash_f_e_parser.parseFile(fl).asList()
with open(tree_filename) as fl:
tree = fl.read()
d = {'likelihood': likelihood, 'ml_tree': tree, 'partitions': {}}
for model, params in ... | def _dash_f_e_to_dict(self, info_filename, tree_filename) | Raxml provides an option to fit model params to a tree,
selected with -f e.
The output is different and needs a different parser. | 4.088688 | 3.852766 | 1.061234 |
logger.debug('info_filename: {} {}'
.format(info_filename, '(FOUND)' if os.path.exists(info_filename) else '(NOT FOUND)'))
logger.debug('tree_filename: {} {}'
.format(tree_filename, '(FOUND)' if os.path.exists(tree_filename) else '(NOT FOUND)'))
... | def to_dict(self, info_filename, tree_filename, dash_f_e=False) | Parse raxml output and return a dict
Option dash_f_e=True will parse the output of a raxml -f e run,
which has different output | 1.877282 | 1.902389 | 0.986802 |
filecheck(filename)
if filename.endswith('.gz'):
gz = True
elif filename.endswith('.bz2'):
bz = True
if gz:
return gzip.open(filename, 'rb')
elif bz:
return bz2.BZ2File(filename, 'rb')
else:
return io.open(filename, 'rb') | def freader(filename, gz=False, bz=False) | Returns a filereader object that can handle gzipped input | 2.12564 | 2.163529 | 0.982487 |
if filename.endswith('.gz'):
gz = True
elif filename.endswith('.bz2'):
bz = True
if gz:
if not filename.endswith('.gz'):
filename += '.gz'
return gzip.open(filename, 'wb')
elif bz:
if not filename.endswith('.bz2'):
filename += '.bz2'... | def fwriter(filename, gz=False, bz=False) | Returns a filewriter object that can write plain or gzipped output.
If gzip or bzip2 compression is asked for then the usual filename extension will be added. | 1.573732 | 1.549757 | 1.015471 |
directorycheck(directory)
files = []
xt = files.extend
for ex in extensions:
xt(glob.glob('{0}/*.{1}'.format(directory, ex)))
return files | def glob_by_extensions(directory, extensions) | Returns files matched by all extensions in the extensions list | 6.058529 | 5.24255 | 1.155645 |
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip()) | def head(filename, n=10) | prints the top `n` lines of a file | 5.631372 | 5.801888 | 0.97061 |
f = locate_by_env(filename, env_var) or locate_by_dir(filename, directory)
return os.path.abspath(f) if can_locate(f) else None | def locate_file(filename, env_var='', directory='') | Locates a file given an environment variable or directory
:param filename: filename to search for
:param env_var: environment variable to look under
:param directory: directory to look in
:return: (string) absolute path to filename or None if not found | 3.809402 | 4.630264 | 0.822718 |
chans = []
chans_names = []
# default channels
if role == "public":
if ENABLE_PUBLIC_CHANNEL is True:
chan = dict(slug=PUBLIC_CHANNEL, path=None)
chans.append(chan)
chans_names.append(PUBLIC_CHANNEL)
elif role == "users":
if ENABLE_USERS_CHANN... | def channels_for_role(role) | Get the channels for a role | 1.564043 | 1.570122 | 0.996128 |
try:
assert 0 <= length <= edge.length
except AssertionError:
if length < 0:
raise TreeError('Negative edge-lengths are disallowed')
raise TreeError(
'This edge isn\'t long enough to prune at length {0}\n'
'(Edge length = {1})'.format(length, edge... | def edge_length_check(length, edge) | Raises error if length is not in interval [0, edge.length] | 5.858196 | 5.192699 | 1.12816 |
if autocorrel_param <= 0:
raise Exception('Autocorrelation parameter must be greater than 0')
variance = branch_length * autocorrel_param
stdev = np.sqrt(variance)
ln_descendant_rate = np.random.normal(np.log(parent_rate) - 0.5 * variance,
scale=st... | def logn_correlated_rate(parent_rate, branch_length, autocorrel_param, size=1) | The log of the descendent rate, ln(Rd), is ~ N(mu, bl*ac), where
the variance = bl*ac = branch_length * autocorrel_param, and mu is set
so that E[Rd] = Rp:
E[X] where ln(X) ~ N(mu, sigma^2) = exp(mu+(1/2)*sigma_sq)
so Rp = exp(mu+(1/2)*bl*ac),
ln(Rp) = mu + (1/2)*bl*ac,
ln(Rp) - (1/2)*bl*ac = mu... | 2.641647 | 2.710421 | 0.974626 |
root_child_nodes = self.tree._tree.seed_node.child_nodes()
not_leaves = np.logical_not([n.is_leaf() for n in root_child_nodes])
if not_leaves[not_leaves].size <= 1:
return [root_child_nodes[np.where(not_leaves)[0]].edge]
return [] | def _check_single_outgroup(self) | If only one (or none) of the seed node children is not a leaf node
it is not possible to prune that edge and make a topology-changing
regraft. | 5.222407 | 4.2119 | 1.239917 |
length = length or edge.length
edge_length_check(length, edge)
n = edge.head_node
self.tree._tree.prune_subtree(n, suppress_unifurcations=False)
n.edge_length = length
self.tree._dirty = True
return n | def prune(self, edge, length=None) | Prunes a subtree from the main Tree, retaining an edge length
specified by length (defaults to entire length). The length is sanity-
checked by edge_length_check, to ensure it is within the bounds
[0, edge.length].
Returns the basal node of the pruned subtree. | 7.424417 | 5.550691 | 1.337566 |
rootcheck(edge, 'SPR regraft is not allowed on the root edge')
length = length or edge.length / 2. # Length measured from head to tail
edge_length_check(length, edge)
t = edge.tail_node
h = edge.head_node
new = t.new_child(edge_length=edge.length - length)
... | def regraft(self, edge, node, length=None) | Grafts a node onto an edge of the Tree, at a point specified by
length (defaults to middle of edge). | 7.734809 | 7.719629 | 1.001966 |
starting_length = self.tree._tree.length()
excl = [self.tree._tree.seed_node.edge] # exclude r
if disallow_sibling_sprs:
excl.extend(self._check_single_outgroup())
prune_edge, l1 = self.tree.map_event_onto_tree(excl)
if keep_entire_edge:
l1 = p... | def rspr(self, disallow_sibling_sprs=False,
keep_entire_edge=False, rescale=False) | Random SPR, with prune and regraft edges chosen randomly, and
lengths drawn uniformly from the available edge lengths.
N1: disallow_sibling_sprs prevents sprs that don't alter the topology
of the tree | 4.280246 | 4.18072 | 1.023806 |
parent = n.parent_node
a, b = random.sample(n.child_nodes(), 2)
if parent.parent_node is None:
if self.tree.rooted:
c, d = random.sample(n.sister_nodes()[0].child_nodes(), 2)
else:
c, d = random.sample(n.sister_nodes(), 2)
... | def get_exchangeable_nodes(self, n) | A C | Subtrees A, B, C and D are the exchangeable nodes
\ / | around the edge headed by n
-->n | The NNI exchanges either A or B with either C or D
/ \
B D
A C C A | Subtree A is exchanged
... | 2.822326 | 2.804065 | 1.006512 |
h = inner_edge.head_node
t = inner_edge.tail_node
if not self.tree._tree.seed_node == t:
original_seed = self.tree._tree.seed_node
self.tree._tree.reseed_at(t)
else:
original_seed = None
head_children = h.child_nodes()
tail_ch... | def get_children(self, inner_edge) | Given an edge in the tree, returns the child nodes of the head and
the tail nodes of the edge, for instance:
A C | A, B, C and D are the children of the edge --->,
\ / | C and D are the head node children, and A and B
t--->h | are the tail node children.... | 3.484279 | 2.727756 | 1.277343 |
# This implementation works on unrooted Trees. If the input Tree is
# rooted, the ReversibleDeroot decorator will temporarily unroot the
# tree while the NNI is carried out
original_seed = self.tree._tree.seed_node
head = edge.head_node
tail = edge.tail_node
... | def nni(
self,
edge,
head_subtree,
tail_subtree,
) | *Inplace* Nearest-neighbour interchange (NNI) operation.
An edge in the tree has two or more subtrees at each end (ends are
designated 'head' and 'tail'). The NNI operation exchanges one of the
head subtrees for one of the tail subtrees, as follows:
A C ... | 4.183029 | 4.04843 | 1.033247 |
if use_weighted_choice:
leaves = list(self.tree._tree.leaf_edge_iter())
e, _ = self.tree.map_event_onto_tree(excluded_edges=leaves, invert_weights=invert_weights)
else:
e = random.choice(self.tree.get_inner_edges())
children = self.get_children(e)
... | def rnni(self, use_weighted_choice=False, invert_weights=False) | Apply a random NNI operation at a randomly selected edge
The edge can be chosen uniformly, or weighted by length --
invert_weights favours short edges. | 5.570932 | 4.819007 | 1.156033 |
return set([n.taxon.label for n in self._tree.leaf_nodes()]) | def labels(self) | Returns the taxon set of the tree (same as the label- or
leaf-set) | 13.493636 | 7.363043 | 1.832617 |
if n >= len(self):
return self.labels
sample = random.sample(self.labels, n)
return set(sample) | def sample_labels(self, n) | Returns a set of n labels sampled from the labels of the tree
:param n: Number of labels to sample
:return: set of randomly sampled labels | 4.061958 | 3.681751 | 1.103268 |
n = self._tree.as_string('newick',
suppress_rooting=True,
suppress_internal_node_labels=True)
if n:
return n.strip(';\n') + ';'
return n | def newick(self) | For more control the dendropy method self.as_string('newick', **kwargs)
can be used.
KWargs include:
suppress_internal_node_labels [True/False]
- turn on/off bootstrap labels
suppress_rooting [True/False]
- turn on/off [&U] or [&R] rooting
state labe... | 6.349108 | 5.538936 | 1.146268 |
if not self._phylotree or self._dirty:
try:
if ISPY3:
self._phylotree = PhyloTree(self.newick.encode(), self.rooted)
else:
self._phylotree = PhyloTree(self.newick, self.rooted)
except ValueError:
... | def phylotree(self) | Get the c++ PhyloTree object corresponding to this tree.
:return: PhyloTree instance | 4.200437 | 3.953089 | 1.062571 |
t = cls(newick)
t._tree.resolve_polytomies()
return t.newick | def bifurcate_base(cls, newick) | Rewrites a newick string so that the base is a bifurcation
(rooted tree) | 8.265765 | 7.478138 | 1.105324 |
t = cls(newick)
t._tree.deroot()
return t.newick | def trifurcate_base(cls, newick) | Rewrites a newick string so that the base is a trifurcation
(usually means an unrooted tree) | 10.352251 | 7.976802 | 1.297795 |
inner_edges = [e for e in self._tree.preorder_edge_iter() if e.is_internal()
and e.head_node and e.tail_node]
return inner_edges | def get_inner_edges(self) | Returns a list of the internal edges of the tree. | 4.772995 | 3.834603 | 1.244717 |
taxa1 = self.labels
taxa2 = other.labels
return taxa1 & taxa2 | def intersection(self, other) | Returns the intersection of the taxon sets of two Trees | 6.271435 | 5.217233 | 1.202061 |
for node in self._tree.postorder_node_iter():
if skip_seed and node is self._tree.seed_node:
continue
yield node | def postorder(self, skip_seed=False) | Return a generator that yields the nodes of the tree in postorder.
If skip_seed=True then the root node is not included. | 3.085161 | 3.111044 | 0.99168 |
for node in self._tree.preorder_node_iter():
if skip_seed and node is self._tree.seed_node:
continue
yield node | def preorder(self, skip_seed=False) | Return a generator that yields the nodes of the tree in preorder.
If skip_seed=True then the root node is not included. | 2.999037 | 3.036474 | 0.987671 |
if not subset.issubset(self.labels):
print('"subset" is not a subset')
return
if not inplace:
t = self.copy()
else:
t = self
t._tree.retain_taxa_with_labels(subset)
t._tree.encode_bipartitions()
t._dirty = True
... | def prune_to_subset(self, subset, inplace=False) | Prunes the Tree to just the taxon set given in `subset` | 4.896031 | 4.31602 | 1.134386 |
if not inplace:
t = self.copy()
else:
t = self
for n in t._tree.preorder_node_iter():
if n.is_internal():
n.edge.length = max(0, distribution_func(*i))
else:
n.edge.length = max(0, distribution_func(*l))
... | def randomise_branch_lengths(
self,
i=(1, 1),
l=(1, 1),
distribution_func=random.gammavariate,
inplace=False,
) | Replaces branch lengths with values drawn from the specified
distribution_func. Parameters of the distribution are given in the
tuples i and l, for interior and leaf nodes respectively. | 3.007371 | 2.900739 | 1.03676 |
if not inplace:
t = self.copy()
else:
t = self
names = list(t.labels)
random.shuffle(names)
for l in t._tree.leaf_node_iter():
l.taxon._label = names.pop()
t._dirty = True
return t | def randomise_labels(
self,
inplace=False,
) | Shuffles the leaf labels, but doesn't alter the tree structure | 4.299678 | 3.943172 | 1.090411 |
root_edge = self._tree.seed_node.edge
lengths = dict([(edge, edge.length) for edge
in self._tree.seed_node.incident_edges() if edge is not root_edge])
self._tree.deroot()
reroot_edge = (set(self._tree.seed_node.incident_edges())
& s... | def reversible_deroot(self) | Stores info required to restore rootedness to derooted Tree. Returns
the edge that was originally rooted, the length of e1, and the length
of e2.
Dendropy Derooting Process:
In a rooted tree the root node is bifurcating. Derooting makes it
trifurcating.
Call the two edg... | 4.588434 | 3.66779 | 1.251008 |
optioncheck(distribution, ['exponential', 'lognormal'])
if autocorrel == 0:
for node in self._tree.preorder_node_iter():
node.rate = root_rate
return
for node in self._tree.preorder_node_iter():
if node == self._tree.seed_node:
... | def autocorrelated_relaxed_clock(self, root_rate, autocorrel,
distribution='lognormal') | Attaches rates to each node according to autocorrelated lognormal
model from Kishino et al.(2001), or autocorrelated exponential | 3.114812 | 3.096878 | 1.005791 |
lgt = LGT(self.copy())
for _ in range(times):
lgt.rlgt(time, disallow_sibling_lgts)
return lgt.tree | def rlgt(self, time=None, times=1,
disallow_sibling_lgts=False) | Uses class LGT to perform random lateral gene transfer on
ultrametric tree | 4.26963 | 3.879405 | 1.100589 |
nni = NNI(self.copy())
for _ in range(times):
nni.rnni(**kwargs)
# nni.reroot_tree()
return nni.tree | def rnni(self, times=1, **kwargs) | Applies a NNI operation on a randomly chosen edge.
keyword args: use_weighted_choice (True/False) weight the random edge selection by edge length
transform (callable) transforms the edges using this function, prior to weighted selection | 7.798404 | 6.433982 | 1.212065 |
spr = SPR(self.copy())
for _ in range(times):
spr.rspr(**kwargs)
return spr.tree | def rspr(self, times=1, **kwargs) | Random SPR, with prune and regraft edges chosen randomly, and
lengths drawn uniformly from the available edge lengths.
N1: disallow_sibling_sprs prevents sprs that don't alter the topology
of the tree | 9.13732 | 6.037372 | 1.51346 |
if not inplace:
t = self.copy()
else:
t = self
t._tree.scale_edges(factor)
t._dirty = True
return t | def scale(self, factor, inplace=True) | Multiplies all branch lengths by factor. | 4.513902 | 4.166991 | 1.083252 |
if not inplace:
t = self.copy()
else:
t = self
for e in t._tree.preorder_edge_iter():
e.length = None
t._dirty = True
return t | def strip(self, inplace=False) | Sets all edge lengths to None | 4.760118 | 3.57218 | 1.332553 |
new_tree = self.copy()
for leaf in new_tree._tree.leaf_node_iter():
curr_name = leaf.taxon.label
leaf.taxon.label = dct.get(curr_name, curr_name)
return new_tree | def translate(self, dct) | Translate leaf names using a dictionary of names
:param dct: Dictionary of current names -> updated names
:return: Copy of tree with names changed | 4.262433 | 3.413692 | 1.248628 |
edges = {}
nodes = {None: 'root'}
for n in self._tree.postorder_node_iter():
nodes[n] = '.'.join([str(x.taxon) for x in n.leaf_nodes()])
for e in self._tree.preorder_edge_iter():
edges[e] = ' ---> '.join([nodes[e.tail_node], nodes[e.head_node]])
... | def _name_things(self) | Easy names for debugging | 3.121778 | 2.954391 | 1.056657 |
tree = self.template or self.yule()
for leaf in tree._tree.leaf_node_iter():
leaf.num_genes = 1
dfr = tree._tree.seed_node.distance_from_root()
dft = tree._tree.seed_node.distance_from_tip()
tree_height = dfr + dft
if scale_to:
populat... | def gene_tree(
self,
scale_to=None,
population_size=1,
trim_names=True,
) | Using the current tree object as a species tree, generate a gene
tree using the constrained Kingman coalescent process from dendropy. The
species tree should probably be a valid, ultrametric tree, generated by
some pure birth, birth-death or coalescent process, but no checks are
made. Op... | 5.949423 | 4.915515 | 1.210336 |
self.fit_params['ini_betas'] = ini_betas
self.fit_params['tol'] = tol
self.fit_params['max_iter'] = max_iter
self.fit_params['solve'] = solve
if solve.lower() == 'iwls':
params, predy, w, n_iter = iwls(
self.y, self.X, self.family, self.offset... | def fit(self, ini_betas=None, tol=1.0e-6, max_iter=200, solve='iwls') | Method that fits a model with a particular estimation routine.
Parameters
----------
ini_betas : array
k*1, initial coefficient values, including constant.
Default is None, which calculates initial values during
estima... | 3.043572 | 3.373633 | 0.902164 |
from statsmodels.tools.numdiff import approx_fprime_cs
# TODO: workaround proplem with numdiff for 1d
return np.diag(approx_fprime_cs(p, self.deriv)) | def deriv2(self, p) | Second derivative of the link function g''(p)
implemented through numerical differentiation | 8.430303 | 8.617054 | 0.978328 |
z = np.asarray(z)
t = np.exp(-z)
return 1. / (1. + t) | def inverse(self, z) | Inverse of the logit transform
Parameters
----------
z : array-like
The value of the logit transform at `p`
Returns
-------
p : array
Probabilities
Notes
-----
g^(-1)(z) = exp(z)/(1+exp(z)) | 4.314579 | 4.980416 | 0.866309 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.