code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
zeroed = matrix - matrix.min()
scaled = (scale - shift) * (zeroed / zeroed.max())
return scaled + shift | def shift_and_scale(matrix, shift, scale) | Shift and scale matrix so its minimum value is placed at `shift` and
its maximum value is scaled to `scale` | 5.696994 | 4.656066 | 1.223564 |
(vals, vecs) = np.linalg.eigh(matrix)
ind = vals.argsort()[::-1]
vals = vals[ind]
vecs = vecs[:, ind]
vals_ = vals.copy()
vals_[vals_ < 0] = 0.
cum_var_exp = np.cumsum(vals_ / vals_.sum())
return Decomp(matrix.copy(), vals, vecs, cum_var_exp) | def eigen(matrix) | Calculates the eigenvalues and eigenvectors of the input matrix.
Returns a tuple of (eigenvalues, eigenvectors, cumulative percentage of
variance explained). Eigenvalues and eigenvectors are sorted in order of
eigenvalue magnitude, high to low | 3.339748 | 3.217893 | 1.037868 |
if additive_correct:
dbc = double_centre(_additive_correct(matrix))
else:
dbc = double_centre(matrix)
decomp = eigen(dbc)
lambda_ = np.diag(np.sqrt(np.abs(decomp.vals[:dimensions])))
evecs = decomp.vecs[:, :dimensions]
coords = evecs.dot(lambda_)
return coords | def _embedding_classical_mds(matrix, dimensions=3, additive_correct=False) | Private method to calculate CMDS embedding
:param dimensions: (int)
:return: coordinate matrix (np.array) | 4.642013 | 4.589829 | 1.011369 |
if affinity_matrix is None:
aff = rbf(matrix, sigma=sigma)
else:
aff = affinity_matrix
coords = sklearn.manifold.spectral_embedding(aff, dimensions)
return normalise_rows(coords) if unit_length else coords | def _embedding_spectral(matrix, dimensions=3, unit_length=True,
affinity_matrix=None, sigma=1) | Private method to calculate Spectral embedding
:param dimensions: (int)
:return: coordinate matrix (np.array) | 3.487995 | 3.810806 | 0.915291 |
tsne = sklearn.manifold.TSNE(n_components=dimensions,
metric="precomputed",
early_exaggeration=early_exaggeration,
method=method,
perplexity=perplexity,
... | def _embedding_tsne(matrix, dimensions=3, early_exaggeration=12.0,
method='barnes_hut', perplexity=30, learning_rate=200,
n_iter=1000) | Private method to perform tSNE embedding
:param matrix: treeCl Distance Matrix
:param dimensions: Number of dimensions in which to embed points
:return: treeCl CoordinateMatrix | 1.70891 | 1.900939 | 0.898982 |
mds = sklearn.manifold.MDS(n_components=dimensions,
dissimilarity='precomputed',
metric=True)
mds.fit(matrix)
return mds.embedding_ | def _embedding_metric_mds(matrix, dimensions=3) | Private method to calculate MMDS embedding
:param dimensions: (int)
:return: coordinate matrix (np.array) | 2.475279 | 2.843037 | 0.870646 |
mds = sklearn.manifold.MDS(n_components=dimensions,
dissimilarity='precomputed',
metric=False)
if initial_coords is not None:
mds.fit(matrix, init=initial_coords)
else:
mds.fit(matrix)
return mds.embedding_ | def _embedding_nonmetric_mds(matrix, dimensions=3, initial_coords=None) | Private method to calculate NMMDS embedding
:param dimensions: (int)
:return: coordinate matrix (np.array) | 2.003649 | 2.316989 | 0.864764 |
if affinity_matrix is None:
aff = rbf(matrix, sigma)
else:
aff = affinity_matrix
kpca = sklearn.decomposition.KernelPCA(kernel='precomputed',
n_components=dimensions)
return kpca.fit_transform(aff) | def _embedding_kernel_pca(matrix, dimensions=3, affinity_matrix=None,
sigma=1) | Private method to calculate KPCA embedding
:param dimensions: (int)
:return: coordinate matrix (np.array) | 2.519902 | 2.824149 | 0.89227 |
i = np.where(self.cve >= cutoff)[0][0]
coords_matrix = self.vecs[:, :i + 1]
return coords_matrix, self.cve[i] | def coords_by_cutoff(self, cutoff=0.80) | Returns fitted coordinates in as many dimensions as are needed to
explain a given amount of variance (specified in the cutoff) | 7.37016 | 6.696079 | 1.100668 |
coords_matrix = self.vecs[:, :dimensions]
varexp = self.cve[dimensions - 1]
return coords_matrix, varexp | def coords_by_dimension(self, dimensions=3) | Returns fitted coordinates in specified number of dimensions, and
the amount of variance explained) | 13.141494 | 7.609388 | 1.727011 |
errors.optioncheck(method, ['cmds', 'kpca', 'mmds', 'nmmds', 'spectral', 'tsne'])
if method == 'cmds':
array = _embedding_classical_mds(self.to_array(), dimensions, **kwargs)
elif method == 'kpca':
array = _embedding_kernel_pca(self.to_array(), dimensions, **kwa... | def embedding(self, dimensions, method, **kwargs) | Embeds the distance matrix in a coordinate space. Implemented methods are:
cmds: Classical MultiDimensional Scaling
kpca: Kernel Principal Components Analysis
mmds: Metric MultiDimensional Scaling
nmmds: Non-Metric MultiDimensional Scaling
spectral: Spectral d... | 2.575459 | 1.97207 | 1.305967 |
columns = mapping.get('columns', [mapping.get('column')])
values = [data.get(c) for c in columns]
for transform in mapping.get('transforms', []):
# any added transforms must also be added to the schema.
values = list(TRANSFORMS[transform](mapping, bind, values))
format_str = mappi... | def extract_value(mapping, bind, data) | Given a mapping and JSON schema spec, extract a value from ``data``
and apply certain transformations to normalize the value. | 3.929186 | 3.828531 | 1.026291 |
types = bind.types + [bind.schema.get('format')]
for type_name in ('date-time', 'date', 'decimal', 'integer', 'boolean',
'number', 'string'):
if type_name in types:
return type_name
return 'string' | def get_type(bind) | Detect the ideal type for the data, either using the explicit type
definition or the format (for date, date-time, not supported by JSON). | 4.603847 | 3.896079 | 1.181662 |
type_name = get_type(bind)
try:
return typecast.cast(type_name, value)
except typecast.ConverterError:
return value | def convert_value(bind, value) | Type casting. | 5.364791 | 4.620689 | 1.161037 |
_max, _min = peakdetect(y, x, lookahead, delta)
x_peaks = [p[0] for p in _max]
y_peaks = [p[1] for p in _max]
x_valleys = [p[0] for p in _min]
y_valleys = [p[1] for p in _min]
_peaks = [x_peaks, y_peaks]
_valleys = [x_valleys, y_valleys]
return {"peaks": _peaks, "valleys": _val... | def peaks(x, y, lookahead=20, delta=0.00003) | A wrapper around peakdetect to pack the return values in a nicer format | 1.818478 | 1.781346 | 1.020845 |
if partition_1.num_elements() != partition_2.num_elements():
print('Partition lists are not the same length')
return 0
else:
total = partition_1.num_elements()
m1 = partition_1.get_membership()
m2 = partition_2.get_membership()
l1 = len(m1)
l2 = len(m2)
entropy... | def entropies(partition_1, partition_2) | parameters: partition_1 (list / array) - a partitioning of a dataset
according to some clustering method. Cluster labels are arbitrary.
partition_2 (list / array) - another partitioning of the same dataset.
Labels don't need to match, nor do the number of clusters.
subfunctions: get_membership( paramet... | 2.964777 | 2.584781 | 1.147013 |
list_length = len(l)
d = defaultdict(list)
for (i, element) in enumerate(l):
d[element].append(i)
l2 = [None] * list_length
for (name, index_list) in enumerate(sorted(d.values(), key=min)):
for index in index_list:
l2[index] = ... | def _restricted_growth_notation(l) | The clustering returned by the hcluster module gives group
membership without regard for numerical order This function preserves
the group membership, but sorts the labelling into numerical order | 3.353873 | 3.24746 | 1.032768 |
props = np.concatenate([[0], (scipy.stats.dirichlet.rvs(alpha) * size).cumsum().round().astype(int)])
indices = np.array(list(range(size)))
random.shuffle(indices)
x = []
for i in range(len(props)-1):
ix = indices[props[i]:props[i+1]]
x.append(ix)... | def random(cls, alpha, size) | Generate a random start using expected proportions, alpha.
These are used to parameterise a random draw from a Dirichlet
distribution.
An example, to split a dataset of 20 items into 3 groups of [10,
6, 4] items:
- alpha = [10, 6, 4],
- alpha = [100, 60, 40],
-... | 4.102501 | 3.906023 | 1.050301 |
result = defaultdict(list)
for (position, value) in enumerate(self.partition_vector):
result[value].append(position)
return sorted([tuple(x) for x in result.values()]) | def get_membership(self) | Alternative representation of group membership -
creates a list with one tuple per group; each tuple contains
the indices of its members
Example:
partition = (0,0,0,1,0,1,2,2)
membership = [(0,1,2,4), (3,5), (6,7)]
:return: list of tuples giving group memberships by in... | 5.715168 | 4.479198 | 1.275936 |
(entropy_1, entropy_2, mut_inf) = entropies(self, other)
return entropy_1 + entropy_2 - 2 * mut_inf | def variation_of_information(self, other) | calculates Variation of Information Metric between two clusterings
of the same data - SEE Meila, M. (2007). Comparing clusterings: an
information based distance. Journal of Multivariate Analysis, 98(5),
873-895. doi:10.1016/j.jmva.2006.11.013 | 5.178257 | 5.400386 | 0.958868 |
median_diff = np.median(np.diff(self.x))
bin_edges = [self.x[0] - median_diff/2.0]
bin_edges.extend(median_diff/2.0 + self.x)
self.y_raw = self.y_raw/(self.y_raw.sum()*np.diff(bin_edges))
self.smooth() | def normalize(self) | Normalizes the given data such that the area under the histogram/curve
comes to 1. Also re applies smoothing once done. | 3.91536 | 3.413189 | 1.147127 |
pickle.dump([self.x, self.y_raw], file(path, 'w')) | def serialize(self, path) | Saves the raw (read unsmoothed) histogram data to the given path using
pickle python module. | 7.981906 | 6.854086 | 1.164547 |
# octave propagation of the reference peaks
temp_peaks = [i + 1200 for i in self.peaks["peaks"][0]]
temp_peaks.extend([i - 1200 for i in self.peaks["peaks"][0]])
extended_peaks = []
extended_peaks.extend(self.peaks["peaks"][0])
for i in temp_peaks:
#... | def extend_peaks(self, prop_thresh=50) | Each peak in the peaks of the object is checked for its presence in
other octaves. If it does not exist, it is created.
prop_thresh is the cent range within which the peak in the other octave
is expected to be present, i.e., only if there is a peak within this
cent range in ... | 3.953813 | 3.66979 | 1.077395 |
import pylab as p
if new_fig:
p.figure()
#step 1: plot histogram
p.plot(self.x, self.y, ls='-', c='b', lw='1.5')
#step 2: plot peaks
first_peak = None
last_peak = None
if self.peaks:
first_peak = min(self.peaks["peaks"]... | def plot(self, intervals=None, new_fig=True) | This function plots histogram together with its smoothed
version and peak information if provided. Just intonation
intervals are plotted for a reference. | 2.649631 | 2.580434 | 1.026816 |
show_progress = bool(message)
njobs = get_njobs(nargs, args)
nproc = len(client)
logger.debug('parallel_map: len(client) = {}'.format(len(client)))
view = client.load_balanced_view()
if show_progress:
message += ' (IP:{}w:{}b)'.format(nproc, batchsize)
pbar = setup_progressb... | def parallel_map(client, task, args, message, batchsize=1, background=False, nargs=None) | Helper to map a function over a sequence of inputs, in parallel, with progress meter.
:param client: IPython.parallel.Client instance
:param task: Function
:param args: Must be a list of tuples of arguments that the task function will be mapped onto.
If the function takes a single argument,... | 3.724796 | 3.92915 | 0.94799 |
njobs = get_njobs(nargs, args)
show_progress = bool(message)
if show_progress:
pbar = setup_progressbar(message, njobs, simple_progress=True)
pbar.start()
map_result = []
for (i, arglist) in enumerate(tupleise(args), start=1):
map_result.append(task(*arglist))
if... | def sequential_map(task, args, message, nargs=None) | Helper to map a function over a sequence of inputs, sequentially, with progress meter.
:param client: IPython.parallel.Client instance
:param task: Function
:param args: Must be a list of tuples of arguments that the task function will be mapped onto.
If the function takes a single argument... | 3.244358 | 3.467556 | 0.935632 |
import concurrent.futures
njobs = get_njobs(nargs, args)
show_progress = bool(message)
batches = grouper(batchsize, tupleise(args))
batched_task = lambda batch: [task(*job) for job in batch]
if show_progress:
message += ' (TP:{}w:{}b)'.format(concurrency, batchsize)
pbar =... | def threadpool_map(task, args, message, concurrency, batchsize=1, nargs=None) | Helper to map a function over a range of inputs, using a threadpool, with a progress meter | 3.500815 | 3.489547 | 1.003229 |
njobs = get_njobs(nargs, args)
show_progress = bool(message)
batches = grouper(batchsize, tupleise(args))
def batched_task(*batch):
return [task(*job) for job in batch]
if show_progress:
message += ' (PP:{}w:{}b)'.format(concurrency, batchsize)
pbar = setup_progressbar(... | def processpool_map(task, args, message, concurrency, batchsize=1, nargs=None) | See http://stackoverflow.com/a/16071616 | 3.91542 | 3.894291 | 1.005426 |
# Get the full set of labels (i.e. sequence ids) for all the alignments
all_labels = set(seq.id for aln in alignments for seq in aln)
# Make a dictionary to store info as we go along
# (defaultdict is convenient -- asking for a missing key gives back an empty list)
tmp = defaultdict(list)
... | def concatenate(alignments) | Concatenates a list of Bio.Align.MultipleSeqAlignment objects.
If any sequences are missing the are padded with unknown data
(Bio.Seq.UnknownSeq).
Returns a single Bio.Align.MultipleSeqAlignment.
Limitations: any annotations in the sub-alignments are lost in
the concatenated alignment. | 4.687652 | 4.254463 | 1.10182 |
if tri == 'upper':
tri_fn = np.triu_indices
else:
tri_fn = np.tril_indices
size = matrix.shape[0]
matrix[tri_fn(size)[::-1]] = matrix[tri_fn(size)]
return matrix | def symmetrise(matrix, tri='upper') | Will copy the selected (upper or lower) triangle of a square matrix
to the opposite side, so that the matrix is symmetrical.
Alters in place. | 2.428761 | 2.529511 | 0.96017 |
iterable = iter(iterable)
return iter(lambda: list(itertools.islice(iterable, n)), []) | def grouper(n, iterable) | >>> list(grouper(3, 'ABCDEFG'))
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G']] | 2.874068 | 3.310653 | 0.868127 |
import bisect
ix = bisect.bisect_left(lst, item)
if lst[ix] != item:
lst[ix:ix] = [item] | def insort_no_dup(lst, item) | If item is not in lst, add item to list at its sorted position | 2.887918 | 2.863458 | 1.008542 |
partials_dict = {}
for (name, sequence) in alignment.get_sequences():
datatype = 'dna' if alignment.is_dna() else 'protein'
partials_dict[name] = seq_to_partials(sequence, datatype)
if missing_data is not None:
l = len(alignment)
for name in missing_data:
if... | def alignment_to_partials(alignment, missing_data=None) | Generate a partials dictionary from a treeCl.Alignment | 2.798216 | 2.728952 | 1.025381 |
partials_dict = {}
for seq in alignment:
partials_dict[seq.name] = seq_to_partials(seq, datatype)
return partials_dict | def biopython_to_partials(alignment, datatype) | Generate a partials dictionary from a treeCl.Alignment | 2.768105 | 2.734376 | 1.012335 |
model = alignment.parameters.partitions.model
freqs = alignment.parameters.partitions.frequencies
alpha = alignment.parameters.partitions.alpha
if model == 'LG':
subs_model = LG(freqs)
elif model == 'WAG':
subs_model = WAG(freqs)
elif model == 'GTR':
rates = alignmen... | def create_gamma_model(alignment, missing_data=None, ncat=4) | Create a phylo_utils.likelihood.GammaMixture for calculating
likelihood on a tree, from a treeCl.Alignment and its matching
treeCl.Parameters | 4.813728 | 4.693508 | 1.025614 |
arr = np.array(lst)
indices = np.random.randint(len(lst), size=len(lst))
sample = np.empty(arr.shape, dtype=arr.dtype)
for i, ix in enumerate(indices):
sample[i] = arr[ix]
return list(sample) | def sample_wr(lst) | Sample from lst, with replacement | 2.480435 | 2.358163 | 1.051851 |
if weights is None:
w_arr = np.ones(len(x))
else:
w_arr = np.array(weights)
x_arr = np.array(x)
if x_arr.ndim == 2:
if w_arr.ndim == 1:
w_arr = w_arr[:, np.newaxis]
return x_arr, w_arr | def _preprocess_inputs(x, weights) | Coerce inputs into compatible format | 2.064558 | 1.986348 | 1.039374 |
w_arr, x_arr = _preprocess_inputs(x, weights)
return (w_arr*x_arr).sum(axis=0) / w_arr.sum(axis=0) | def amean(x, weights=None) | Return the weighted arithmetic mean of x | 3.257466 | 3.188251 | 1.021709 |
w_arr, x_arr = _preprocess_inputs(x, weights)
return np.exp((w_arr*np.log(x_arr)).sum(axis=0) / w_arr.sum(axis=0)) | def gmean(x, weights=None) | Return the weighted geometric mean of x | 3.317666 | 3.237941 | 1.024622 |
w_arr, x_arr = _preprocess_inputs(x, weights)
return w_arr.sum(axis=0) / (w_arr/x_arr).sum(axis=0) | def hmean(x, weights=None) | Return the weighted harmonic mean of x | 3.995705 | 3.910789 | 1.021713 |
import numpy as np
simdict = dict(simseqs)
origdict = dict(origseqs)
for k in origdict:
origseq = np.array(list(origdict[k]))
gap_pos = np.where(origseq=='-')
simseq = np.array(list(simdict[k]))
simseq[gap_pos] = '-'
simdict[k] = ''.join(simseq)
return li... | def gapmask(simseqs, origseqs) | :param sims: list of (header, sequence) tuples of simulated sequences [no gaps]
:param aln: list of (header, sequence) tuples of original sequences
:return: | 2.399645 | 2.388682 | 1.004589 |
return [self._records[i] for i in range(len(self._records))] | def records(self) | Returns a list of records in SORT_KEY order | 4.752629 | 3.562036 | 1.334245 |
compression = ['', 'gz', 'bz2']
if file_format == 'fasta':
extensions = ['fa', 'fas', 'fasta']
elif file_format == 'phylip':
extensions = ['phy']
else:
extensions = []
extensions = list('.'.join([x,y]) if y else x for x,y in itert... | def read_alignments(self, input_dir, file_format, header_grep=None) | Get list of alignment files from an input directory *.fa, *.fas and
*.phy files only
Stores in self.files | 2.992526 | 2.982378 | 1.003403 |
if self.show_progress:
pbar = setup_progressbar("Loading trees", len(self.records))
pbar.start()
for i, rec in enumerate(self.records):
hook = os.path.join(input_dir, '{}.nwk*'.format(rec.name))
filename = glob.glob(hook)
try:
... | def read_trees(self, input_dir) | Read a directory full of tree files, matching them up to the
already loaded alignments | 4.02243 | 4.054135 | 0.992179 |
if self.show_progress:
pbar = setup_progressbar("Loading parameters", len(self.records))
pbar.start()
for i, rec in enumerate(self.records):
hook = os.path.join(input_dir, '{}.json*'.format(rec.name))
filename = glob.glob(hook)
try:
... | def read_parameters(self, input_dir) | Read a directory full of json parameter files, matching them up to the
already loaded alignments | 3.732001 | 3.710787 | 1.005717 |
if indices is None:
indices = list(range(len(self)))
if task_interface is None:
task_interface = tasks.MLDistanceTaskInterface()
records = [self[i] for i in indices]
# Assemble argument lists
args, to_delete = task_interface.scrape_args(records... | def calc_distances(self, indices=None, task_interface=None, jobhandler=default_jobhandler, batchsize=1,
show_progress=True) | Calculate fast approximate intra-alignment pairwise distances and variances using
ML (requires ML models to have been set up using `calc_trees`).
:return: None (all side effects) | 5.15298 | 4.896006 | 1.052487 |
if indices is None:
indices = list(range(len(self)))
if task_interface is None:
task_interface = tasks.RaxmlTaskInterface()
records = [self[i] for i in indices]
# Scrape args from records
args, to_delete = task_interface.scrape_args(records, **... | def calc_trees(self, indices=None, task_interface=None, jobhandler=default_jobhandler, batchsize=1,
show_progress=True, **kwargs) | Infer phylogenetic trees for the loaded Alignments
:param indices: Only run inference on the alignments at these given indices
:param task_interface: Inference tool specified via TaskInterface (default RaxmlTaskInterface)
:param jobhandler: Launch jobs via this JobHandler (default SequentialJob... | 5.420185 | 5.334483 | 1.016066 |
metrics = {'euc': tasks.EuclideanTreeDistance,
'geo': tasks.GeodesicTreeDistance,
'rf': tasks.RobinsonFouldsTreeDistance,
'wrf': tasks.WeightedRobinsonFouldsTreeDistance,
'fasteuc': tasks.EqualLeafSetEuclideanTreeDistance,
... | def get_inter_tree_distances(self, metric, jobhandler=default_jobhandler,
normalise=False, min_overlap=4, overlap_fail_value=0,
batchsize=1, show_progress=True) | Generate a distance matrix from a fully-populated Collection.
Can silence progressbars with show_progress=False option
:param metric: str. Tree distance metric to use. Choice of 'euc', 'geo', 'rf', 'wrf'.
:param jobhandler: treeCl.Jobhandler. Choice of SequentialJobHandler, ThreadpoolJobHand... | 4.035123 | 3.709116 | 1.087893 |
all_headers = reduce(lambda x, y: set(x) | set(y),
(rec.get_names() for rec in self.records))
return len(all_headers) | def num_species(self) | Returns the number of species found over all records | 5.362203 | 4.402472 | 1.217998 |
def take(n, iterable):
return [next(iterable) for _ in range(n)]
if partition is None:
partition = Partition([1] * len(self))
index_tuples = partition.get_membership()
alignments = []
for ix in index_tuples:
concat = Concatenation(s... | def permuted_copy(self, partition=None) | Return a copy of the collection with all alignment columns permuted | 4.412098 | 4.338976 | 1.016852 |
thehash = hex(hash(grp))
if ISPY3: # use default encoding to get bytes
thehash = thehash.encode()
return self.cache.get(grp, hashlib.sha1(thehash).hexdigest()) | def get_id(self, grp) | Return a hash of the tuple of indices that specify the group | 8.676089 | 8.744678 | 0.992156 |
id_ = self.get_id(grp)
concat_file = os.path.join(self.cache_dir, '{}.phy'.format(id_))
result_file = os.path.join(self.cache_dir, '{}.{}.json'.format(id_, self.task_interface.name))
return os.path.exists(concat_file), os.path.exists(result_file) | def check_work_done(self, grp) | Check for the existence of alignment and result files. | 3.568747 | 3.208928 | 1.112131 |
id_ = self.get_id(grp)
alignment_done, result_done = self.check_work_done(grp)
self.cache[grp] = id_
al_filename = os.path.join(self.cache_dir, '{}.phy'.format(id_))
qfile_filename = os.path.join(self.cache_dir, '{}.partitions.txt'.format(id_))
if overwrite or no... | def write_group(self, grp, overwrite=False, **kwargs) | Write the concatenated alignment to disk in the location specified by
self.cache_dir | 4.660198 | 4.144954 | 1.124306 |
id_ = self.get_id(grp)
self.cache[grp] = id_
# Check if this file is already processed
alignment_written, results_written = self.check_work_done(grp)
if not results_written:
if not alignment_written:
self.write_group(grp, **kwargs)
... | def get_group_result(self, grp, **kwargs) | Retrieve the results for a group. Needs this to already be calculated -
errors out if result not available. | 6.041694 | 5.846834 | 1.033327 |
if jobhandler is None:
jobhandler = SequentialJobHandler()
files = glob.glob(os.path.join(self.cache_dir, '*.phy'))
#logger.debug('Files - {}'.format(files))
records = []
outfiles = []
dna = self.collection[0].is_dna() # THIS IS ONLY A GUESS AT SEQ TY... | def analyse_cache_dir(self, jobhandler=None, batchsize=1, **kwargs) | Scan the cache directory and launch analysis for all unscored alignments
using associated task handler. KWargs are passed to the tree calculating
task managed by the TaskInterface in self.task_interface.
Example kwargs:
TreeCollectionTaskInterface: scale=1, guide_tree=None,
... | 4.690496 | 4.321498 | 1.085387 |
scores = []
for grp in p.get_membership():
try:
result = self.get_group_result(grp)
scores.append(result['likelihood'])
except ValueError:
scores.append(None)
return sum(scores) | def get_partition_score(self, p) | Assumes analysis is done and written to id.json! | 4.622142 | 4.235155 | 1.091375 |
trees = []
for grp in p.get_membership():
try:
result = self.get_group_result(grp)
trees.append(result['ml_tree'])
except ValueError:
trees.append(None)
logger.error('No tree found for group {}'.format(grp))... | def get_partition_trees(self, p) | Return the trees associated with a partition, p | 4.677061 | 4.456228 | 1.049556 |
results = self.get_partition_results(partition)
DEFAULT_DNA_MODEL = 'GTR'
DEFAULT_PROTEIN_MODEL = 'LG08'
# Collect argument list
args = [None] * len(self.collection)
for result in results:
if len(result['partitions']) > 1:
places = ... | def simulate(self, partition, outdir, jobhandler=default_jobhandler, batchsize=1, **kwargs) | Simulate a set of alignments from the parameters inferred on a partition
:param partition:
:return: | 3.236641 | 3.192796 | 1.013733 |
changed = self.get_changed(self.partition, self.prev_partition)
lk_table = self.generate_lktable(self.partition, changed, use_proportions)
self.table = self.likelihood_table_to_probs(lk_table) | def expect(self, use_proportions=True) | The Expectation step of the CEM algorithm | 7.253037 | 6.826966 | 1.06241 |
assert table.shape[1] == self.numgrp
if weighted_choice:
if transform is not None:
probs = transform_fn(table.copy(), transform) #
else:
probs = table.copy()
cmprobs = probs.cumsum(1)
logger.info('Probabilities\n{}... | def classify(self, table, weighted_choice=False, transform=None) | The Classification step of the CEM algorithm | 4.654364 | 4.685714 | 0.993309 |
self.scorer.write_partition(self.partition)
self.scorer.analyse_cache_dir(**kwargs)
self.likelihood = self.scorer.get_partition_score(self.partition)
self.scorer.clean_cache()
changed = self.get_changed(self.partition, self.prev_partition)
self.update_perlocus_li... | def maximise(self, **kwargs) | The Maximisation step of the CEM algorithm | 6.291899 | 6.481678 | 0.970721 |
assert len(partition) == self.numgrp
self.partition, self.prev_partition = partition, self.partition | def set_partition(self, partition) | Store the partition in self.partition, and
move the old self.partition into self.prev_partition | 8.846037 | 5.693382 | 1.55374 |
if p1 is None or p2 is None:
return list(range(len(self.insts)))
return set(flatten_list(set(p1) - set(p2))) | def get_changed(self, p1, p2) | Return the loci that are in clusters that have changed between
partitions p1 and p2 | 4.657456 | 4.929138 | 0.944882 |
# Build transition matrix from dict
model = partition_parameters['model']
freqs = partition_parameters.get('frequencies')
if model == 'LG':
subs_model = phylo_utils.models.LG(freqs)
elif model == 'WAG':
subs_model = phylo_utils.models.WAG(freqs)
... | def _update_likelihood_model(self, inst, partition_parameters, tree) | Set parameters of likelihood model - inst -
using values in dictionary - partition_parameters -,
and - tree - | 3.898211 | 3.927501 | 0.992542 |
m = lktable.max(1) # row max of lktable
shifted = lktable-m[:,np.newaxis] # shift lktable of log-likelihoods to a non-underflowing range
expsum = np.exp(shifted).sum(1) # convert logs to (scaled) normal space, and sum the rows
logexpsum = np.log(expsum)+m # convert back to l... | def likelihood_table_to_probs(self, lktable) | Calculates this formula (1), given the log of the numerator as input
p_k * f(x_i, a_k)
t_k(x_i) = -----------------------
---K
\ p_k * f(x_i, a_k)
/__k=1
x_i is data point i
P_k is c... | 6.50712 | 6.490102 | 1.002622 |
new_assignment = np.array(assignment.tolist())
for k in range(self.numgrp):
if np.count_nonzero(assignment==k) == 0:
logger.info('Group {} became empty'.format(k))
best = np.where(probs[:,k]==probs[:,k].max())[0][0]
new_assignment[best... | def _fill_empty_groups_old(self, probs, assignment) | Does the simple thing - if any group is empty, but needs to have at
least one member, assign the data point with highest probability of
membership | 3.168893 | 3.220491 | 0.983978 |
for grp in partition.get_membership():
grpid = self.scorer.get_id(grp)
cache_dir = self.scorer.cache_dir
prog = self.scorer.task_interface.name
filename = os.path.join(cache_dir, '{}.{}.json'.format(grpid, prog))
if os.path.exists(filename):
... | def wipe_partition(self, partition) | Deletes analysis result of partition, e.g. so a repeat
optimisation of the same partition can be done with a
different model | 4.72456 | 4.859281 | 0.972275 |
return np.sqrt(((x-a)**2).sum(1)) - c | def g(x,a,c) | Christophe's suggestion for residuals,
G[i] = Sqrt(Sum_j (x[j] - a[i,j])^2) - C[i] | 5.628194 | 5.278167 | 1.066316 |
v = g(x, a, c)
return v.dot(v) | def f(x, a, c) | Objective function (sum of squared residuals) | 6.343357 | 7.224421 | 0.878044 |
return (x-a) / np.sqrt(((x-a)**2).sum(1))[:,np.newaxis] | def jac(x,a) | Jacobian matrix given Christophe's suggestion of f | 4.078402 | 4.548913 | 0.896566 |
return jac(x, a).T.dot(g(x, a, c)) | def gradient(x, a, c) | J'.G | 8.224252 | 7.394874 | 1.112156 |
j = jac(x, a)
return j.T.dot(j) | def hessian(x, a) | J'.J | 4.541784 | 5.068149 | 0.896143 |
return x - step * gradient(x,a,c) | def grad_desc_update(x, a, c, step=0.01) | Given a value of x, return a better x
using gradient descent | 5.14845 | 6.733501 | 0.764602 |
return x - step*np.linalg.inv(hessian(x, a)).dot(gradient(x, a, c)) | def newton_update(x, a, c, step=1.0) | Given a value of x, return a better x
using newton-gauss | 4.350032 | 5.386932 | 0.807516 |
hess = hessian(x, a)
return x - np.linalg.inv(hess + damping*np.diag(hess)).dot(gradient(x, a, c)) | def levenberg_marquardt_update(x, a, c, damping=0.001) | Given a value of x, return a better x
using newton-gauss | 4.729728 | 5.231013 | 0.90417 |
c = b - GOLDEN*(b-a)
d = a + GOLDEN*(b-a)
while abs(c-d) > tolerance:
fc, fd = fn(c), fn(d)
if fc < fd:
b = d
d = c #fd=fc;fc=f(c)
c = b - GOLDEN*(b-a)
else:
a = c
c = d #fc=fd;fd=f(d)
d = a + GOLDEN*(b-a)... | def golden_section_search(fn, a, b, tolerance=1e-5) | WIKIPEDIA IMPLEMENTATION
golden section search
to find the minimum of f on [a,b]
f: a strictly unimodal function on [a,b]
example:
>>> f=lambda x:(x-2)**2
>>> x=gss(f,1,5)
>>> x
2.000009644875678 | 2.35972 | 2.828444 | 0.834282 |
x_new = x
x_old = x-1 # dummy value
while np.abs(x_new - x_old).sum() > tolerance:
x_old = x_new
x_new = newton_update(x_old, a, c)
return x_new | def optimise_newton(x, a, c, tolerance=0.001) | Optimise value of x using newton gauss | 3.058152 | 3.16231 | 0.967063 |
x_new = x
x_old = x-1 # dummy value
f_old = f(x_new, a, c)
while np.abs(x_new - x_old).sum() > tolerance:
x_old = x_new
x_tmp = levenberg_marquardt_update(x_old, a, c, damping)
f_new = f(x_tmp, a, c)
if f_new < f_old:
damping = np.max(damping/10., 1e-20)
... | def optimise_levenberg_marquardt(x, a, c, damping=0.001, tolerance=0.001) | Optimise value of x using levenberg-marquardt | 2.360446 | 2.413733 | 0.977923 |
x_new = x
x_old = x-1 # dummy value
while np.abs(x_new - x_old).sum() > tolerance:
x_old = x_new
step_size = golden_section_search(lambda step: f(grad_desc_update(x_old, a, c, step), a, c), -1.0, 1.0)
x_new = grad_desc_update(x_old, a, c, step_size)
return x_new | def optimise_gradient_descent(x, a, c, tolerance=0.001) | Optimise value of x using gradient descent | 3.071548 | 3.16189 | 0.971428 |
fit = np.empty((len(boot_collection), dimensions))
if ISPY3:
query_trees = [PhyloTree(tree.encode(), rooted) for tree in boot_collection.trees]
ref_trees = [PhyloTree(tree.encode(), rooted) for tree in ref_collection.trees]
else:
query_trees = [PhyloTree(tree, rooted) for tree i... | def run_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo, rooted=False, **kwargs) | index = index of the locus the bootstrap sample corresponds to - only important if
using recalc=True in kwargs | 2.475211 | 2.535764 | 0.97612 |
ref_dists = pdist(ref_cds)
est_dists = pdist(est_cds)
return np.sqrt(((ref_dists - est_dists)**2).sum() / (ref_dists**2).sum()) | def stress(ref_cds, est_cds) | Kruskal's stress | 2.552006 | 2.530995 | 1.008302 |
ref_dists = pdist(ref_cds)
est_dists = pdist(est_cds)
return np.sqrt(((ref_dists - est_dists)**2).mean()) | def rmsd(ref_cds, est_cds) | Root-mean-squared-difference | 2.529811 | 2.561018 | 0.987815 |
if start_x is None:
start_x = self._analytical_fitter.fit(self._c)
return optimise_newton(start_x, self._a, self._c, tolerance) | def newton(self, start_x=None, tolerance=1.0e-6) | Optimise value of x using newton gauss | 5.620931 | 5.036 | 1.11615 |
if start_x is None:
start_x = self._analytical_fitter.fit(self._c)
return optimise_gradient_descent(start_x, self._a, self._c, tolerance) | def gradient_descent(self, start_x=None, tolerance=1.0e-6) | Optimise value of x using gradient descent | 5.50702 | 4.873785 | 1.129927 |
if start_x is None:
start_x = self._analytical_fitter.fit(self._c)
return optimise_levenberg_marquardt(start_x, self._a, self._c, tolerance) | def levenberg_marquardt(self, start_x=None, damping=1.0e-3, tolerance=1.0e-6) | Optimise value of x using levenberg marquardt | 4.778834 | 4.517441 | 1.057863 |
brow = self.new_B_row(index, distvec**2, recalc)
return self.new_coords(brow)[:dimensions] | def fit(self, index, distvec, recalc=False, dimensions=3) | Replace distance matrix values at row/column index with
distances in distvec, and compute new coordinates.
Optionally use distvec to update means and (potentially)
get a better estimate.
distvec values should be plain distances, not squared
distances. | 12.372419 | 10.249098 | 1.207172 |
rot = self._rotate_rows(ref_crds)
A = 2*(rot - ref_crds)
partial_b = (rot**2 - ref_crds**2).sum(1)
return A, partial_b | def _make_A_and_part_of_b_adjacent(self, ref_crds) | Make A and part of b. See docstring of this class
for answer to "What are A and b?" | 5.430752 | 5.302416 | 1.024203 |
dists = ref_dists**2
rot_dists = self._rotate_rows(dists)
b = dists - rot_dists + self._partial_b
self._b = b
return self._pinvA.dot(b) | def _analytical_fit_adjacent(self, ref_dists) | Fit coords (x,y,[z]) so that distances from reference coordinates
match closest to reference distances | 8.942283 | 9.616509 | 0.929889 |
visitor = SchemaVisitor({'$ref': schema_uri}, resolver)
return _generate_schema_mapping(visitor, set(), depth) | def generate_schema_mapping(resolver, schema_uri, depth=1) | Try and recursively iterate a JSON schema and to generate an ES mapping
that encasulates it. | 6.611028 | 6.049356 | 1.092848 |
tree_a = Tree(newick_string_a)
tree_b = Tree(newick_string_b)
return treedist.eucdist(tree_a, tree_b, normalise, min_overlap, overlap_fail_value) | def eucdist_task(newick_string_a, newick_string_b, normalise, min_overlap=4, overlap_fail_value=0) | Distributed version of tree_distance.eucdist
Parameters: two valid newick strings and a boolean | 1.829034 | 2.244398 | 0.814933 |
tree_a = Tree(newick_string_a)
tree_b = Tree(newick_string_b)
return treedist.geodist(tree_a, tree_b, normalise, min_overlap, overlap_fail_value) | def geodist_task(newick_string_a, newick_string_b, normalise, min_overlap=4, overlap_fail_value=0) | Distributed version of tree_distance.geodist
Parameters: two valid newick strings and a boolean | 1.813294 | 2.221526 | 0.816238 |
tree_a = Tree(newick_string_a)
tree_b = Tree(newick_string_b)
return treedist.rfdist(tree_a, tree_b, normalise, min_overlap, overlap_fail_value) | def rfdist_task(newick_string_a, newick_string_b, normalise, min_overlap=4, overlap_fail_value=0) | Distributed version of tree_distance.rfdist
Parameters: two valid newick strings and a boolean | 1.863571 | 2.240075 | 0.831923 |
tree_a = Tree(newick_string_a)
tree_b = Tree(newick_string_b)
return treedist.wrfdist(tree_a, tree_b, normalise, min_overlap, overlap_fail_value) | def wrfdist_task(newick_string_a, newick_string_b, normalise, min_overlap=4, overlap_fail_value=0) | Distributed version of tree_distance.rfdist
Parameters: two valid newick strings and a boolean | 1.824542 | 2.293843 | 0.795408 |
import re
fl = os.path.abspath(alignment_file)
ph = Phyml(verbose=False)
if model in ['JC69', 'K80', 'F81', 'F84', 'HKY85', 'TN93', 'GTR']:
datatype = 'nt'
elif re.search('[01]{6}', model) is not None:
datatype = 'nt'
else:
datatype = 'aa'
cmd = '-i {} -m {} -d {... | def phyml_task(alignment_file, model, **kwargs) | Kwargs are passed to the Phyml process command line | 3.181602 | 3.101651 | 1.025777 |
args = []
to_delete = []
if partition_files is None:
partition_files = [None for rec in records]
if outfiles is None:
outfiles = [None for rec in records]
for (rec, qfile, ofile) in zip(records, partition_files, outfiles):
if model is ... | def scrape_args(self, records, executable='raxmlHPC-AVX', partition_files=None,
model=None, outfiles=None, threads=1, parsimony=False, fast_tree=False,
n_starts=1) | Examine a list of records and generate RAxML command line arguments for tree inference.
:param records: list of `Alignment` records
:param executable: name of the RAxML executable on the system to use. Must be in the user's path.
:param partition_files: List of RAxML partition files used to desc... | 3.271814 | 2.898979 | 1.128609 |
alf_dirs = {}
for k in range(self.num_classes):
dirname = fileIO.join_path(self.tmpdir, 'class{0:0>1}'.format(
k + 1))
alf_dirs[k + 1] = errors.directorymake(dirname)
self.alf_dirs = alf_dirs | def make_alf_dirs_(self) | DEPRECATED | 5.644715 | 5.438158 | 1.037983 |
if not hasattr(self, 'alf_dirs'):
self.make_alf_dirs()
if not hasattr(self, 'class_trees'):
self.generate_class_trees()
alf_params = {}
for k in range(self.num_classes):
alfdir = self.alf_dirs[k + 1]
tree = self.class_trees[k + 1... | def write_alf_params_(self) | DEPRECATED | 3.38298 | 3.333352 | 1.014888 |
all_records = []
for k in range(self.num_classes):
simulated_records = self.alf_params[k + 1].run()
names = ['class{0}_{1:0>{2}}'.format(k + 1, i,
len(str(self.class_list[k]))) for i in range(1,
... | def run_(self) | DEPRECATED | 4.14459 | 4.027823 | 1.02899 |
file_path = os.path.join(os.path.dirname(__file__),
'schemas', 'mapping.json')
with open(file_path, 'r') as fh:
validator = Draft4Validator(json.load(fh))
validator.validate(mapping)
return mapping | def validate_mapping(mapping) | Validate a mapping configuration file against the relevant schema. | 2.561954 | 2.2227 | 1.152632 |
if t1 ^ t2:
if len(t1 & t2) < min_overlap:
return overlap_fail_value
#raise AttributeError('Can\'t calculate tree distances when tree overlap is less than two leaves')
else:
t1, t2 = _equalise_leaf_sets(t1, t2, False)
return fn(t1.phylotree, t2.phylotree... | def _generic_distance_calc(fn, t1, t2, normalise, min_overlap=4, overlap_fail_value=0) | (fn, t1, t2, normalise)
Calculates the distance between trees t1 and t2. Can optionally be normalised to range [0, 1].
If the trees have different leaf sets, the distance is calculated on their intersection. This incurs
some overhead - if the trees are known to have the same leaves, then the underlying dis... | 5.851037 | 4.620672 | 1.266274 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.