code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
myarr = np.array(arr)
if myarr.ndim == 1:
return list(range(len(myarr)))
elif myarr.ndim == 2:
return tuple(itertools.product(list(range(arr.shape[0])),
list(range(arr.shape[1]))))
else:
raise NotImplementedError('Only supporting arrays... | def _indexes(arr) | Returns the list of all indexes of the given array.
Currently works for one and two-dimensional arrays | 2.880217 | 2.879566 | 1.000226 |
if arr.ndim == 2 and types.is_int(indexes):
return arr[:, indexes]
elif arr.ndim == 3 and len(indexes) == 2:
return arr[:, indexes[0], indexes[1]]
else:
raise NotImplementedError('Only supporting arrays of dimension 2 and 3 as yet.') | def _column(arr, indexes) | Returns a column with given indexes from a deep array
For example, if the array is a matrix and indexes is a single int, will
return arr[:,indexes]. If the array is an order 3 tensor and indexes is a
pair of ints, will return arr[:,indexes[0],indexes[1]], etc. | 3.547207 | 3.40229 | 1.042594 |
r
if conf < 0 or conf > 1:
raise ValueError('Not a meaningful confidence level: '+str(conf))
try:
data = types.ensure_ndarray(data, kind='numeric')
except:
# if 1D array of arrays try to fuse it
if isinstance(data, np.ndarray) and np.ndim(data) == 1:
newshape... | def confidence_interval(data, conf=0.95) | r""" Computes element-wise confidence intervals from a sample of ndarrays
Given a sample of arbitrarily shaped ndarrays, computes element-wise
confidence intervals
Parameters
----------
data : array-like of dimension 1 to 3
array of numbers or arrays. The first index is used as the sample
... | 3.231281 | 3.294691 | 0.980754 |
N = 0
for x in X:
if len(x) > N:
N = len(x)
return N | def _maxlength(X) | Returns the maximum length of signal trajectories X | 2.426736 | 2.414571 | 1.005038 |
# check input
assert np.ndim(X[0]) == 1, 'Data must be 1-dimensional'
N = _maxlength(X) # length
# mean-free data
xflat = np.concatenate(X)
Xmean = np.mean(xflat)
X0 = [x-Xmean for x in X]
# moments
x2m = np.mean(xflat ** 2)
# integrate damped autocorrelation
corrsum =... | def statistical_inefficiency(X, truncate_acf=True) | Estimates the statistical inefficiency from univariate time series X
The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal.
Given a signal :math:`{x_t}` with :math:`N` samples and statistical inefficiency :math:`I \in (0,1]`, there are
only :math:`I \cdot N` effective ... | 4.640713 | 4.485591 | 1.034582 |
if not self.filename:
return None
from pyemma.util.files import mkdir_p
hash_value_long = int(key, 16)
# bin hash to one of either 10 different databases
# TODO: make a configuration parameter out of this number
db_name = str(hash_value_long)[-1] + '... | def _database_from_key(self, key) | gets the database name for the given key. Should ensure a uniform spread
of keys over the databases in order to minimize waiting times. Since the
database has to be locked for updates and multiple processes want to write,
each process has to wait until the lock has been released.
By def... | 7.613529 | 5.782474 | 1.316656 |
db_name = self._database_from_key(hash_value)
if not db_name:
db_name=':memory:'
def _update():
import sqlite3
try:
with sqlite3.connect(db_name, timeout=self.lru_timeout) as conn:
conn.execute... | def _update_time_stamp(self, hash_value) | timestamps are being stored distributed over several lru databases.
The timestamp is a time.time() snapshot (float), which are seconds since epoch. | 3.776768 | 3.598637 | 1.0495 |
# delete the n % oldest entries in the database
import sqlite3
num_delete = int(self.num_entries / 100.0 * n)
logger.debug("removing %i entries from db" % num_delete)
lru_dbs = self._database.execute("select hash, lru_db from traj_info").fetchall()
lru_dbs.sort(k... | def _clean(self, n) | obtain n% oldest entries by looking into the usage databases. Then these entries
are deleted first from the traj_info db and afterwards from the associated LRU dbs.
:param n: delete n% entries in traj_info db [and associated LRU (usage) dbs]. | 3.959072 | 3.576398 | 1.107 |
return super(TRAM, self).estimate(X, **params) | def estimate(self, X, **params) | Parameters
----------
X : tuple of (ttrajs, dtrajs, btrajs)
Simulation trajectories. ttrajs contain the indices of the thermodynamic state, dtrajs
contains the indices of the configurational states and btrajs contain the biases.
ttrajs : list of numpy.ndarray(X_i, dt... | 8.808737 | 12.63728 | 0.697044 |
r
# TODO: check that we are estimated...
return _tram.log_likelihood_lower_bound(
self.log_lagrangian_mult, self.biased_conf_energies,
self.count_matrices, self.btrajs, self.dtrajs, self.state_counts,
None, None, None, None, None) | def log_likelihood(self) | r"""
Returns the value of the log-likelihood of the converged TRAM estimate. | 17.977228 | 13.862996 | 1.296778 |
r
assert self.therm_energies is not None, \
'MEMM has to be estimate()\'d before pointwise free energies can be calculated.'
if therm_state is not None:
assert therm_state<=self.nthermo
mu = [_np.zeros(d.shape[0], dtype=_np.float64) for d in self.dtrajs+self.equil... | def pointwise_free_energies(self, therm_state=None) | r"""
Computes the pointwise free energies :math:`-\log(\mu^k(x))` for all points x.
:math:`\mu^k(x)` is the optimal estimate of the Boltzmann distribution
of the k'th ensemble defined on the set of all samples.
Parameters
----------
therm_state : int or None, default=No... | 4.260817 | 3.996864 | 1.06604 |
return self._is_random_accessible and \
not isinstance(self.ra_itraj_cuboid, NotImplementedRandomAccessStrategy) and \
not isinstance(self.ra_linear, NotImplementedRandomAccessStrategy) and \
not isinstance(self.ra_itraj_jagged, NotImplementedRandomAccessStr... | def is_random_accessible(self) | Check if self._is_random_accessible is set to true and if all the random access strategies are implemented.
Returns
-------
bool : Returns True if random accessible via strategies and False otherwise. | 5.588647 | 4.834115 | 1.156085 |
'''Computes the N-dimensional histogram of the transformed data.
Parameters
----------
transform : pyemma.coordinates.transfrom.Transformer object
transform that provides the input data
dimensions : tuple of indices
indices of the dimensions you want to examine
nbins : tuple of ... | def histogram(transform, dimensions, nbins) | Computes the N-dimensional histogram of the transformed data.
Parameters
----------
transform : pyemma.coordinates.transfrom.Transformer object
transform that provides the input data
dimensions : tuple of indices
indices of the dimensions you want to examine
nbins : tuple of ints
... | 3.000589 | 1.54345 | 1.94408 |
if not config.check_version:
class _dummy:
def start(self): pass
return _dummy()
import json
import platform
import os
from distutils.version import LooseVersion as parse
from contextlib import closing
import threading
import uuid
import sys
if ... | def _version_check(current, testing=False) | checks latest version online from http://emma-project.org.
Can be disabled by setting config.check_version = False.
>>> from unittest.mock import patch
>>> import warnings, pyemma
>>> with warnings.catch_warnings(record=True) as cw, patch('pyemma.version', '0.1'):
... warnings.simplefilter('al... | 3.633722 | 3.314691 | 1.096248 |
if not filename:
filename = self.default_config_file
files = self._cfgs_to_read()
# insert last, so it will override all values,
# which have already been set in previous files.
files.insert(-1, filename)
try:
config = self.__read_cfg(fi... | def load(self, filename=None) | load runtime configuration from given filename.
If filename is None try to read from default file from
default location. | 8.188965 | 8.095915 | 1.011493 |
if not filename:
filename = self.DEFAULT_CONFIG_FILE_NAME
else:
filename = str(filename)
# try to extract the path from filename and use is as cfg_dir
head, tail = os.path.split(filename)
if head:
self._cfg_dir = head
... | def save(self, filename=None) | Saves the runtime configuration to disk.
Parameters
----------
filename: str or None, default=None
writeable path to configuration filename.
If None, use default location and filename. | 4.222887 | 4.251883 | 0.99318 |
import os.path as p
import pyemma
return p.join(pyemma.__path__[0], Config.DEFAULT_CONFIG_FILE_NAME) | def default_config_file(self) | default config file living in PyEMMA package | 5.85488 | 3.84176 | 1.52401 |
import os.path as p
import pyemma
return p.join(pyemma.__path__[0], Config.DEFAULT_LOGGING_FILE_NAME) | def default_logging_file(self) | default logging configuration | 6.551111 | 6.211342 | 1.054701 |
if not os.path.exists(pyemma_cfg_dir):
try:
mkdir_p(pyemma_cfg_dir)
except NotADirectoryError: # on Python 3
raise ConfigDirectoryException("pyemma cfg dir (%s) is not a directory" % pyemma_cfg_dir)
except EnvironmentError:
... | def cfg_dir(self, pyemma_cfg_dir) | Sets PyEMMAs configuration directory.
Also creates it with some default files, if does not exists. | 3.234183 | 3.121443 | 1.036118 |
cfg = self._conf_values.get('pyemma', 'logging_config')
if cfg == 'DEFAULT':
cfg = os.path.join(self.cfg_dir, Config.DEFAULT_LOGGING_FILE_NAME)
return cfg | def logging_config(self) | currently used logging configuration file. Can not be changed during runtime. | 6.394603 | 5.615376 | 1.138767 |
# use these files to extend/overwrite the conf_values.
# Last red file always overwrites existing values!
cfg = Config.DEFAULT_CONFIG_FILE_NAME
filenames = [
self.default_config_file,
cfg, # conf_values in current directory
os.path.join(os.pa... | def _cfgs_to_read(self) | reads config files from various locations to build final config. | 7.598351 | 7.332644 | 1.036236 |
fragment_indices = []
for idx, cumlen in enumerate(self._cumulative_lengths):
cumlen_prev = self._cumulative_lengths[idx - 1] if idx > 0 else 0
fragment_indices.append([np.argwhere(
np.logical_and(self.ra_indices >= cumlen_prev, self.ra_indices < cumlen)
... | def __get_ra_index_indices(self) | Returns a list containing indices of the ra_index array, which correspond to the separate trajectory fragments,
i.e., ra_indices[fragment_indices[itraj]] are the ra indices for itraj (plus some offset by
cumulative length) | 3.613947 | 3.015137 | 1.198601 |
overlap = stride * ((traj_len - skip - 1) // stride + 1) - traj_len + skip
return overlap | def _calculate_new_overlap(stride, traj_len, skip) | Given two trajectories T_1 and T_2, this function calculates for the first trajectory an overlap, i.e.,
a skip parameter for T_2 such that the trajectory fragments T_1 and T_2 appear as one under the given stride.
Idea for deriving the formula: It is
K = ((traj_len - skip - 1) // stride + 1) =... | 4.550787 | 5.289504 | 0.860343 |
'''Command line options.'''
if argv is None:
argv = sys.argv
else:
sys.argv.extend(argv)
parser = ArgumentParser()
parser.add_argument('-u', '--url', dest='url', required=True, help="base url (has to contain versions json)")
parser.add_argument('-o', '--output', dest='output')
... | def main(argv=None) | Command line options. | 2.931106 | 2.933722 | 0.999108 |
if TrajectoryInfoCache._instance is None:
# if we do not have a configuration director yet, we do not want to store
if not config.cfg_dir:
filename = None
else:
filename = os.path.join(config.cfg_dir, "traj_info.sqlite3")
T... | def instance() | :returns the TrajectoryInfoCache singleton instance | 5.266457 | 3.996515 | 1.317762 |
r
return assert_allclose_np(actual, desired, rtol=rtol, atol=atol,
err_msg=err_msg, verbose=verbose) | def assert_allclose(actual, desired, rtol=1.e-5, atol=1.e-8,
err_msg='', verbose=True) | r"""wrapper for numpy.testing.allclose with default tolerances of
numpy.allclose. Needed since testing method has different values. | 3.251642 | 4.200879 | 0.774039 |
data = [(atom.serial, atom.name, atom.element.symbol,
atom.residue.resSeq, atom.residue.name,
atom.residue.chain.index, atom.segment_id) for atom in top.atoms]
atoms = np.array(data,
dtype=[("serial", 'i4'), ("name", 'S4'), ("element", 'S3'),
... | def topology_to_numpy(top) | Convert this topology into a pandas dataframe
Returns
-------
atoms : np.ndarray dtype=[("serial", 'i4'), ("name", 'S4'), ("element", 'S3'),
("resSeq", 'i4'), ("resName",'S4'), ("chainID", 'i4'), ("segmentID", 'S4')]
The atoms in the topology, represented as a data fra... | 2.36836 | 1.996249 | 1.186405 |
if bonds is None:
bonds = np.zeros((0, 2))
for col in ["name", "element", "resSeq",
"resName", "chainID", "serial"]:
if col not in atoms.dtype.names:
raise ValueError('dataframe must have column %s' % col)
if "segmentID" not in atoms.dtype.names:
at... | def topology_from_numpy(atoms, bonds=None) | Create a mdtraj topology from numpy arrays
Parameters
----------
atoms : np.ndarray
The atoms in the topology, represented as a data frame. This data
frame should have columns "serial" (atom index), "name" (atom name),
"element" (atom's element), "resSeq" (index of the residue)
... | 3.043821 | 2.960037 | 1.028305 |
with open(filename, "r") as f:
lines=f.read()
dtraj=np.fromstring(lines, dtype=int, sep="\n")
return dtraj | def read_discrete_trajectory(filename) | Read discrete trajectory from ascii file.
The ascii file containing a single column with integer entries is
read into an array of integers.
Parameters
----------
filename : str
The filename of the discrete state trajectory file.
The filename can either contain the full or the
... | 3.47603 | 3.430975 | 1.013132 |
r
dtraj=np.asarray(dtraj)
with open(filename, 'w') as f:
dtraj.tofile(f, sep='\n', format='%d') | def write_discrete_trajectory(filename, dtraj) | r"""Write discrete trajectory to ascii file.
The discrete trajectory is written to a
single column ascii file with integer entries
Parameters
----------
filename : str
The filename of the discrete state trajectory file.
The filename can either contain the full or the
relati... | 3.558721 | 4.923258 | 0.722839 |
r
dtraj=np.asarray(dtraj)
np.save(filename, dtraj) | def save_discrete_trajectory(filename, dtraj) | r"""Write discrete trajectory to binary file.
The discrete trajectory is stored as ndarray of integers
in numpy .npy format.
Parameters
----------
filename : str
The filename of the discrete state trajectory file.
The filename can either contain the full or the
relative pat... | 5.995241 | 7.531191 | 0.796055 |
r
# format input
dtrajs = _ensure_dtraj_list(dtrajs)
# make bincounts for each input trajectory
nmax = 0
bcs = []
for dtraj in dtrajs:
if ignore_negative:
dtraj = dtraj[np.where(dtraj >= 0)]
bc = np.bincount(dtraj)
nmax = max(nmax, bc.shape[0])
bcs... | def count_states(dtrajs, ignore_negative=False) | r"""returns a histogram count
Parameters
----------
dtrajs : array_like or list of array_like
Discretized trajectory or list of discretized trajectories
ignore_negative, bool, default=False
Ignore negative elements. By default, a negative element will cause an
exception
Ret... | 3.129639 | 3.388032 | 0.923734 |
r
dtrajs = _ensure_dtraj_list(dtrajs)
if only_used:
# only states with counts > 0 wanted. Make a bincount and count nonzeros
bc = count_states(dtrajs)
return np.count_nonzero(bc)
else:
# all states wanted, included nonpopulated ones. return max + 1
imax = 0
... | def number_of_states(dtrajs, only_used = False) | r"""returns the number of states in the given trajectories.
Parameters
----------
dtraj : array_like or list of array_like
Discretized trajectory or list of discretized trajectories
only_used = False : boolean
If False, will return max+1, where max is the largest index used.
If ... | 5.726165 | 6.876435 | 0.832723 |
N = len(sequence)
res = np.zeros((N,2), dtype=int)
for t in range(N):
s = sequence[t]
i = np.random.randint(indexes[s].shape[0])
res[t,:] = indexes[s][i,:]
return res | def sample_indexes_by_sequence(indexes, sequence) | Samples trajectory/time indexes according to the given sequence of states
Parameters
----------
indexes : list of ndarray( (N_i, 2) )
For each state, all trajectory and time indexes where this state occurs.
Each matrix has a number of rows equal to the number of occurrences of the correspon... | 2.841765 | 3.236538 | 0.878026 |
if fake:
yield
return
oldstdchannel = dest_file = None
try:
oldstdchannel = os.dup(stdchannel.fileno())
dest_file = open(dest_filename, 'w')
os.dup2(dest_file.fileno(), stdchannel.fileno())
yield
finally:
if oldstdchannel is not None:
... | def stdchannel_redirected(stdchannel, dest_filename, fake=False) | A context manager to temporarily redirect stdout or stderr
e.g.:
with stdchannel_redirected(sys.stderr, os.devnull):
if compiler.has_function('clock_gettime', libraries=['rt']):
libraries.append('rt') | 1.903476 | 1.952085 | 0.975099 |
with TemporaryDirectory() as tmpdir, \
stdchannel_redirected(sys.stderr, os.devnull), \
stdchannel_redirected(sys.stdout, os.devnull):
f = tempfile.mktemp(suffix='.cpp', dir=tmpdir)
with open(f, 'w') as fh:
fh.write('int main (int argc, char **argv) { return ... | def has_flag(compiler, flagname) | Return a boolean indicating whether a flag name is supported on
the specified compiler. | 2.233648 | 2.350173 | 0.950418 |
if self.dim > -1:
return self.dim
d = None
if self.dim != -1 and not self._estimated: # fixed parametrization
d = self.dim
elif self._estimated: # parametrization finished. Dimension is known
dim = len(self.eigenvalues)
if self.v... | def dimension(self) | output dimension | 7.278498 | 6.992815 | 1.040854 |
r
X_meanfree = X - self.mean
Y = np.dot(X_meanfree, self.eigenvectors[:, 0:self.dimension()])
return Y.astype(self.output_type()) | def _transform_array(self, X) | r"""Projects the data onto the dominant independent components.
Parameters
----------
X : ndarray(n, m)
the input data
Returns
-------
Y : ndarray(n,)
the projected data | 9.339293 | 11.280114 | 0.827943 |
r
return -self.lag / np.log(np.abs(self.eigenvalues)) | def timescales(self) | r"""Implied timescales of the TICA transformation
For each :math:`i`-th eigenvalue, this returns
.. math::
t_i = -\frac{\tau}{\log(|\lambda_i|)}
where :math:`\tau` is the :py:obj:`lag` of the TICA object and :math:`\lambda_i` is the `i`-th
:py:obj:`eigenvalue <eigenvalues... | 27.571701 | 14.830606 | 1.859108 |
r
feature_sigma = np.sqrt(np.diag(self.cov))
return np.dot(self.cov, self.eigenvectors[:, : self.dimension()]) / feature_sigma[:, np.newaxis] | def feature_TIC_correlation(self) | r"""Instantaneous correlation matrix between mean-free input features and TICs
Denoting the input features as :math:`X_i` and the TICs as :math:`\theta_j`, the instantaneous, linear correlation
between them can be written as
.. math::
\mathbf{Corr}(X_i - \mu_i, \mathbf{\theta}_j) ... | 6.785981 | 7.724016 | 0.878556 |
from pyemma._ext.variational.solvers.direct import spd_inv_sqrt
# reweight operator to empirical distribution
C0t_re = mdot(C00_train, K)
# symmetrized operator and SVD
K_sym = mdot(spd_inv_sqrt(C00_train), C0t_re, spd_inv_sqrt(Ctt_train))
U, S, Vt = np.linalg.svd(K_sym, compute_uv=True, fu... | def _svd_sym_koopman(K, C00_train, Ctt_train) | Computes the SVD of the symmetrized Koopman operator in the empirical distribution. | 4.845223 | 4.615211 | 1.049838 |
from pyemma._ext.variational.solvers.direct import spd_inv_sqrt
# SVD of symmetrized operator in empirical distribution
U, S, V = _svd_sym_koopman(K, C00_train, Ctt_train)
if k is not None:
U = U[:, :k]
# S = S[:k][:, :k]
V = V[:, :k]
A = spd_inv_sqrt(mdot(U.T, C00_test... | def vamp_1_score(K, C00_train, C0t_train, Ctt_train, C00_test, C0t_test, Ctt_test, k=None) | Computes the VAMP-1 score of a kinetic model.
Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt,
defined by:
:math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]`
:math:`C_{tt}^{train} = E_t[x_{t+\tau} x_{t+\tau}^T]`
These model covariances might have been subj... | 4.620828 | 4.681976 | 0.98694 |
# SVD of symmetrized operator in empirical distribution
U, s, V = _svd_sym_koopman(K, C00_train, Ctt_train)
if k is not None:
U = U[:, :k]
S = np.diag(s[:k])
V = V[:, :k]
score = np.trace(2.0 * mdot(V, S, U.T, C0t_test) - mdot(V, S, U.T, C00_test, U, S, V.T, Ctt_test))
r... | def vamp_e_score(K, C00_train, C0t_train, Ctt_train, C00_test, C0t_test, Ctt_test, k=None) | Computes the VAMP-E score of a kinetic model.
Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt,
defined by:
:math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]`
:math:`C_{tt}^{train} = E_t[x_{t+\tau} x_{t+\tau}^T]`
These model covariances might have been subj... | 3.783521 | 3.746537 | 1.009872 |
import inspect
public_undocumented_members = {name: func for name, func in inspect.getmembers(cls)
if not name.startswith('_') and func.__doc__ is None}
for name, func in public_undocumented_members.items():
for parent in cls.__mro__[1:]:
parfunc ... | def fix_docs(cls) | copies docstrings of derived attributes (methods, properties, attrs) from parent classes. | 2.604378 | 2.478634 | 1.050732 |
original_methods = aliased_class.__dict__.copy()
original_methods_set = set(original_methods)
for name, method in original_methods.items():
aliases = None
if isinstance(method, property) and hasattr(method.fget, '_aliases'):
aliases = method.fget._aliases
elif hasatt... | def aliased(aliased_class) | Decorator function that *must* be used in combination with @alias
decorator. This class will make the magic happen!
@aliased classes will have their aliased method (via @alias) actually
aliased.
This method simply iterates over the member attributes of 'aliased_class'
seeking for those which have an... | 2.757224 | 3.04681 | 0.904954 |
def wrap(f):
globals_ = f.__globals__
for name in names:
globals_[name] = f
if '__all__' in globals_ and name not in globals_['__all__']:
globals_['__all__'].append(name)
return f
return wrap | def shortcut(*names) | Add an shortcut (alias) to a decorated function, but not to class methods!
Use aliased/alias decorators for class members!
Calling the shortcut (alias) will call the decorated function. The shortcut name will be appended
to the module's __all__ variable and the shortcut function will inherit the function'... | 2.564869 | 3.750031 | 0.683959 |
try:
caller_stack = stack()[omit_top_frames:]
while len(caller_stack) > 0:
frame = caller_stack.pop(0)
filename = frame[1]
# skip callee frames if they are other decorators or this file(func)
if '<decorator' in filename or __file__ in filename:
... | def get_culprit(omit_top_frames=1) | get the filename and line number calling this.
Parameters
----------
omit_top_frames: int, default=1
omit n frames from top of stack stack. Purpose is to get the real
culprit and not intermediate functions on the stack.
Returns
-------
(filename: str, fileno: int)
filename a... | 7.049681 | 6.67684 | 1.055841 |
def _deprecated(func, *args, **kw):
filename, lineno = get_culprit()
user_msg = 'Call to deprecated function "%s". Called from %s line %i. %s' \
% (func.__name__, filename, lineno, msg)
warnings.warn_explicit(
user_msg,
category=PyEMMA_Depreca... | def deprecated(*optional_message) | This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
Parameters
----------
*optional_message : str
an optional user level hint which should indicate which feature to use otherwise. | 4.385829 | 4.524325 | 0.969389 |
r
from pyemma.thermo.extensions.util import (logsumexp as _logsumexp, logsumexp_pair as _logsumexp_pair)
nmax = int(_np.max([dtraj.max() for dtraj in dtrajs]))
if nstates is None:
nstates = nmax + 1
elif nstates < nmax + 1:
raise ValueError("nstates is smaller than the number of obs... | def get_averaged_bias_matrix(bias_sequences, dtrajs, nstates=None) | r"""
Computes a bias matrix via an exponential average of the observed frame wise bias energies.
Parameters
----------
bias_sequences : list of numpy.ndarray(T_i, num_therm_states)
A single reduced bias energy trajectory or a list of reduced bias energy trajectories.
For every simulatio... | 2.984479 | 3.036556 | 0.98285 |
r
ttrajs, umbrella_centers, force_constants, unbiased_state = _get_umbrella_sampling_parameters(
us_trajs, us_centers, us_force_constants, md_trajs=md_trajs, kT=kT)
if md_trajs is None:
md_trajs = []
if width is None:
width = _np.zeros(shape=(umbrella_centers.shape[1],), dtype=_n... | def get_umbrella_sampling_data(
us_trajs, us_centers, us_force_constants, md_trajs=None, kT=None, width=None) | r"""
Wraps umbrella sampling data or a mix of umbrella sampling and and direct molecular dynamics.
Parameters
----------
us_trajs : list of N arrays, each of shape (T_i, d)
List of arrays, each having T_i rows, one for each time step, and d columns where d is the
dimension in which umbr... | 2.737632 | 2.438393 | 1.12272 |
r
ttrajs, temperatures = _get_multi_temperature_parameters(temp_trajs)
if reference_temperature is None:
reference_temperature = temperatures.min()
else:
assert isinstance(reference_temperature, (int, float)), \
'reference_temperature must be numeric'
assert reference... | def get_multi_temperature_data(
energy_trajs, temp_trajs, energy_unit, temp_unit, reference_temperature=None) | r"""
Wraps data from multi-temperature molecular dynamics.
Parameters
----------
energy_trajs : list of N arrays, each of shape (T_i,)
List of arrays, each having T_i rows, one for each time step, containing the potential
energies time series in units of kT, kcal/mol or kJ/mol.
temp... | 2.662403 | 2.320606 | 1.147288 |
r
if unbiased_state is None:
return
for memm in memm_list:
assert 0 <= unbiased_state < len(memm.models), "invalid state: " + str(unbiased_state)
memm._unbiased_state = unbiased_state | def assign_unbiased_state_label(memm_list, unbiased_state) | r"""
Sets the msm label for the given list of estimated MEMM objects.
Parameters
----------
memm_list : list of estimated MEMM objects
The MEMM objects which shall have the msm label set.
unbiased_state : int or None
Index of the unbiased thermodynamic state (if present). | 3.249383 | 3.687364 | 0.881221 |
if x is None:
return True
if isinstance(x, numbers.Number):
return x == 0.0
if isinstance(x, np.ndarray):
return np.all(x == 0)
return False | def _is_zero(x) | Returns True if x is numerically 0 or an array with 0's. | 2.205777 | 1.884025 | 1.170779 |
if sparse_mode.lower() == 'sparse':
min_const_col_number = 0 # enforce sparsity. A single constant column will lead to sparse treatment
elif sparse_mode.lower() == 'dense':
min_const_col_number = X.shape[1] + 1 # never use sparsity
else:
if remove_mean and not modify_data: # ... | def _sparsify(X, remove_mean=False, modify_data=False, sparse_mode='auto', sparse_tol=0.0) | Determines the sparsity of X and returns a selected sub-matrix
Only conducts sparsification if the number of constant columns is at least
max(a N - b, min_const_col_number),
Parameters
----------
X : ndarray
data matrix
remove_mean : bool
True: remove column mean from the data,... | 3.695658 | 3.268835 | 1.130574 |
r
# determine type
dtype = np.float64 # default: convert to float64 in order to avoid cancellation errors
if X.dtype.kind == 'b' and X.shape[0] < 2**23 and not remove_mean:
dtype = np.float32 # convert to float32 if we can represent all numbers
# copy/convert if needed
if X.dtype not i... | def _copy_convert(X, const=None, remove_mean=False, copy=True) | r""" Makes a copy or converts the data type if needed
Copies the data and converts the data type if unsuitable for covariance
calculation. The standard data type for covariance computations is
float64, because the double precision (but not single precision) is
usually sufficient to compute the long sum... | 3.60809 | 3.304078 | 1.092011 |
r
T = X.shape[0]
# Check if weights are given:
if weights is not None:
X = weights[:, None] * X
if Y is not None:
Y = weights[:, None] * Y
# compute raw sums on variable data
sx_raw = X.sum(axis=0) # this is the mean before subtracting it.
sy_raw = 0
if Y is ... | def _sum(X, xmask=None, xconst=None, Y=None, ymask=None, yconst=None, symmetric=False, remove_mean=False,
weights=None) | r""" Computes the column sums and centered column sums.
If symmetric = False, the sums will be determined as
.. math:
sx &=& \frac{1}{2} \sum_t x_t
sy &=& \frac{1}{2} \sum_t y_t
If symmetric, the sums will be determined as
.. math:
sx = sy = \frac{1}{2T} \sum_t x_t + y_t
... | 2.327313 | 2.13795 | 1.088572 |
xmean = s / float(w)
if mask is None:
X = np.subtract(X, xmean, out=X if inplace else None)
else:
X = np.subtract(X, xmean[mask], out=X if inplace else None)
const = np.subtract(const, xmean[~mask], const if inplace else None)
return X, const | def _center(X, w, s, mask=None, const=None, inplace=True) | Centers the data.
Parameters
----------
w : float
statistical weight of s
inplace : bool
center in place
Returns
-------
sx : ndarray
uncentered row sum of X
sx_centered : ndarray
row sum of X after centering
optional returns (only if Y is given):
... | 2.72741 | 3.932558 | 0.693546 |
a = np.where(mask)[0]
b = column_selection[np.in1d(column_selection, a)]
return np.searchsorted(a, b) | def _filter_variable_indices(mask, column_selection) | Returns column indices restricted to the variable columns as determined by the given mask.
Parameters
----------
mask : ndarray(N, dtype=bool)
Array indicating the variable columns.
column_selection : ndarray(k, dtype=int)
Column indices to be filtered and mapped.
Returns
-----... | 3.576747 | 3.718704 | 0.961826 |
if weights is not None:
if diag_only:
return np.sum(weights[:, None] * X * Y, axis=0)
else:
return np.dot((weights[:, None] * X).T, Y)
else:
if diag_only:
return np.sum(X * Y, axis=0)
else:
return np.dot(X.T, Y) | def _M2_dense(X, Y, weights=None, diag_only=False) | 2nd moment matrix using dense matrix computations.
This function is encapsulated such that we can make easy modifications of the basic algorithms | 1.727301 | 1.972899 | 0.875514 |
r
C = np.zeros((len(mask_X), len(mask_Y)))
# Block 11
C[np.ix_(mask_X, mask_Y)] = _M2_dense(Xvar, Yvar, weights=weights)
# other blocks
xsum_is_0 = _is_zero(xvarsum)
ysum_is_0 = _is_zero(yvarsum)
xconst_is_0 = _is_zero(xconst)
yconst_is_0 = _is_zero(yconst)
# TODO: maybe we don't... | def _M2_const(Xvar, mask_X, xvarsum, xconst, Yvar, mask_Y, yvarsum, yconst, weights=None) | r""" Computes the unnormalized covariance matrix between X and Y, exploiting constant input columns
Computes the unnormalized covariance matrix :math:`C = X^\top Y`
(for symmetric=False) or :math:`C = \frac{1}{2} (X^\top Y + Y^\top X)`
(for symmetric=True). Suppose the data matrices can be column-permuted
... | 2.997052 | 3.132902 | 0.956638 |
C = np.zeros((len(mask_X), len(mask_Y)))
C[np.ix_(mask_X, mask_Y)] = _M2_dense(Xvar, Yvar, weights=weights)
return C | def _M2_sparse(Xvar, mask_X, Yvar, mask_Y, weights=None) | 2nd moment matrix exploiting zero input columns | 2.151654 | 2.198464 | 0.978708 |
assert len(mask_X) == len(mask_Y), 'X and Y need to have equal sizes for symmetrization'
if column_selection is None:
mask_Xk = mask_X
mask_Yk = mask_Y
Xvark = Xvar
Yvark = Yvar
else:
mask_Xk = mask_X[column_selection]
mask_Yk = mask_Y[column_selection]
... | def _M2_sparse_sym(Xvar, mask_X, Yvar, mask_Y, weights=None, column_selection=None) | 2nd self-symmetric moment matrix exploiting zero input columns
Computes X'X + Y'Y and X'Y + Y'X | 1.908651 | 1.932704 | 0.987555 |
if mask_X is None and mask_Y is None:
return _M2_dense(Xvar, Yvar, weights=weights, diag_only=diag_only)
else:
# Check if one of the masks is not None, modify it and also adjust the constant columns:
if mask_X is None:
mask_X = np.ones(Xvar.shape[1], dtype=np.bool)
... | def _M2(Xvar, Yvar, mask_X=None, mask_Y=None, xsum=0, xconst=0, ysum=0, yconst=0, weights=None, diag_only=False) | direct (nonsymmetric) second moment matrix. Decide if we need dense, sparse, const | 2.286806 | 2.222301 | 1.029026 |
if mask_X is None and mask_Y is None:
if column_selection is None:
Xvark = Xvar
Yvark = Yvar
else:
Xvark = Xvar[:, column_selection]
Yvark = Yvar[:, column_selection]
Cxxyy = _M2_dense(Xvar, Xvark, weights=weights, diag_only=diag_only) \
... | def _M2_symmetric(Xvar, Yvar, mask_X=None, mask_Y=None, xsum=0, xconst=0, ysum=0, yconst=0, weights=None,
column_selection=None, diag_only=False) | symmetric second moment matrices. Decide if we need dense, sparse, const | 1.746409 | 1.734558 | 1.006832 |
w, s, M = moments_XX(X, remove_mean=remove_mean, weights=weights, modify_data=modify_data,
sparse_mode=sparse_mode, sparse_tol=sparse_tol)
return M / float(w) | def covar(X, remove_mean=False, modify_data=False, weights=None, sparse_mode='auto', sparse_tol=0.0) | Computes the covariance matrix of X
Computes
.. math:
C_XX &=& X^\top X
while exploiting zero or constant columns in the data matrix.
WARNING: Directly use moments_XX if you can. This function does an additional
constant-matrix multiplication and does not return the mean.
Parameters
... | 3.714095 | 4.851028 | 0.76563 |
w, sx, sy, Mxx, Mxy = moments_XXXY(X, Y, remove_mean=remove_mean, modify_data=modify_data, weights=weights,
symmetrize=symmetrize, sparse_mode=sparse_mode, sparse_tol=sparse_tol)
return Mxx / float(w), Mxy / float(w) | def covars(X, Y, remove_mean=False, modify_data=False, symmetrize=False, weights=None, sparse_mode='auto',
sparse_tol=0.0) | Computes the covariance and cross-covariance matrix of X and Y
If symmetrize is False, computes
.. math:
C_XX &=& X^\top X
C_XY &=& X^\top Y
If symmetrize is True, computes
.. math:
C_XX &=& \frac{1}{2} (X^\top X + Y^\top Y)
C_XY &=& \frac{1}{2} (X^\top Y + ... | 2.890494 | 3.561651 | 0.81156 |
if not D:
import yaml
args = config.logging_config
default = False
if args.upper() == 'DEFAULT':
default = True
src = config.default_logging_file
else:
src = args
# first try to read configured file
try:
... | def setup_logging(config, D=None) | set up the logging system with the configured (in pyemma.cfg) logging config (logging.yml)
@param config: instance of pyemma.config module (wrapper) | 4.581655 | 4.497977 | 1.018603 |
import mdtraj
assert isinstance(self, mdtraj.Trajectory), type(self)
if not isinstance(value, mdtraj.Trajectory):
raise TypeError("value to assign is of incorrect type(%s). Should be mdtraj.Trajectory" % type(value))
idx = np.index_exp[idx]
frames, atoms = None, None
if isinstance(i... | def trajectory_set_item(self, idx, value) | :param self: mdtraj.Trajectory
:param idx: possible slices over frames,
:param value:
:return: | 2.722671 | 2.503459 | 1.087564 |
sig = inspect.signature(func)
args = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD
]
varargs = [
p.name for p in sig.parameters.values()
if p.kind == inspect.Parameter.VAR_POSITIONAL
]
varargs = varargs[0] if v... | def getargspec_no_self(func) | inspect.getargspec replacement using inspect.signature.
inspect.getargspec is deprecated in python 3. This is a replacement
based on the (new in python 3.3) `inspect.signature`.
Parameters
----------
func : callable
A callable to inspect
Returns
-------
argspec : ArgSpec(args,... | 1.573451 | 1.571708 | 1.001109 |
# get function name
if not isinstance(f, str):
fname = f.__func__.__name__
else:
fname = f
# get the method ref
method = getattr(obj, fname)
# handle cases
if inspect.ismethod(method):
return method(*args, **kwargs)
# attribute or property
return method | def call_member(obj, f, *args, **kwargs) | Calls the specified method, property or attribute of the given object
Parameters
----------
obj : object
The object that will be used
f : str or function
Name of or reference to method, property or attribute
failfast : bool
If True, will raise an exception when trying a meth... | 4.201854 | 4.308732 | 0.975195 |
args, varargs, keywords, defaults = getargspec_no_self(func)
return dict(zip(args[-len(defaults):], defaults)) | def get_default_args(func) | returns a dictionary of arg_name:default_values for the input function | 2.894202 | 2.961257 | 0.977356 |
dtrajs_new = []
for dtraj in dtrajs:
if len(dtraj) <= lag:
continue
if shift is None:
s = np.random.randint(min(lag, dtraj.size-lag))
else:
s = shift
if sliding:
if s > 0:
dtrajs_new.append(dtraj[0:lag+s])
... | def blocksplit_dtrajs(dtrajs, lag=1, sliding=True, shift=None) | Splits the discrete trajectories into approximately uncorrelated fragments
Will split trajectories into fragments of lengths lag or longer. These fragments
are overlapping in order to conserve the transition counts at given lag.
If sliding=True, the resulting trajectories will lead to exactly the same coun... | 1.966901 | 2.114579 | 0.930162 |
if len(dtrajs) == 1:
raise ValueError('Only have a single trajectory. Cannot be split into train and test set')
I0 = np.random.choice(len(dtrajs), int(len(dtrajs)/2), replace=False)
I1 = np.array(list(set(list(np.arange(len(dtrajs)))) - set(list(I0))))
dtrajs_train = [dtrajs[i] for i in I0]... | def cvsplit_dtrajs(dtrajs) | Splits the trajectories into a training and test set with approximately equal number of trajectories
Parameters
----------
dtrajs : list of ndarray(int)
Discrete trajectories | 2.046312 | 2.12954 | 0.960917 |
old_state = np.random.get_state()
np.random.seed(seed)
try:
yield
finally:
np.random.set_state(old_state) | def numpy_random_seed(seed=42) | sets the random seed of numpy within the context.
Example
-------
>>> import numpy as np
>>> with numpy_random_seed(seed=0):
... np.random.randint(1000)
684 | 1.813926 | 2.923895 | 0.62038 |
old_state = random.getstate()
random.seed(seed)
try:
yield
finally:
random.setstate(old_state) | def random_seed(seed=42) | sets the random seed of Python within the context.
Example
-------
>>> import random
>>> with random_seed(seed=0):
... random.randint(0, 1000) # doctest: +SKIP
864 | 2.367522 | 3.398164 | 0.696706 |
from pyemma import config
old_settings = {}
try:
# remember old setting, set new one. May raise ValueError, if invalid setting is given.
for k, v in kwargs.items():
old_settings[k] = getattr(config, k)
setattr(config, k, v)
yield
finally:
# r... | def settings(**kwargs) | apply given PyEMMA config values temporarily within the given context. | 3.640124 | 2.922138 | 1.245706 |
res = []
assignment = self.metastable_assignment
for i in range(self.m):
res.append(np.where(assignment == i)[0])
return res | def metastable_sets(self) | Crisp clustering using PCCA. This is only recommended for visualization purposes. You *cannot* compute any
actual quantity of the coarse-grained kinetics without employing the fuzzy memberships!
Returns
-------
A list of length equal to metastable states. Each element is an array with mi... | 4.740209 | 3.856747 | 1.229069 |
_warn(
'scatter_contour is deprected; use plot_contour instead'
' and manually add a scatter plot on top.',
DeprecationWarning)
ax = contour(
x, y, z, ncontours=ncontours, colorbar=colorbar,
fig=fig, ax=ax, cmap=cmap)
# scatter points
ax.scatter(x , y, marker... | def scatter_contour(
x, y, z, ncontours=50, colorbar=True, fig=None,
ax=None, cmap=None, outfile=None) | Contour plot on scattered data (x,y,z) and
plots the positions of the points (x,y) on top.
Parameters
----------
x : ndarray(T)
x-coordinates
y : ndarray(T)
y-coordinates
z : ndarray(T)
z-coordinates
ncontours : int, optional, default=50
number of contour lev... | 3.754243 | 4.651862 | 0.807041 |
z, xedge, yedge = _np.histogram2d(
xall, yall, bins=nbins, weights=weights)
x = 0.5 * (xedge[:-1] + xedge[1:])
y = 0.5 * (yedge[:-1] + yedge[1:])
if avoid_zero_count:
z = _np.maximum(z, _np.min(z[z.nonzero()]))
return x, y, z.T | def get_histogram(
xall, yall, nbins=100,
weights=None, avoid_zero_count=False) | Compute a two-dimensional histogram.
Parameters
----------
xall : ndarray(T)
Sample x-coordinates.
yall : ndarray(T)
Sample y-coordinates.
nbins : int, optional, default=100
Number of histogram bins used in each dimension.
weights : ndarray(T), optional, default=None
... | 1.978362 | 2.471346 | 0.80052 |
from scipy.interpolate import griddata
x, y = _np.meshgrid(
_np.linspace(xall.min(), xall.max(), nbins),
_np.linspace(yall.min(), yall.max(), nbins),
indexing='ij')
z = griddata(
_np.hstack([xall[:,None], yall[:,None]]),
zall, (x, y), method=method)
return x,... | def get_grid_data(xall, yall, zall, nbins=100, method='nearest') | Interpolate unstructured two-dimensional data.
Parameters
----------
xall : ndarray(T)
Sample x-coordinates.
yall : ndarray(T)
Sample y-coordinates.
zall : ndarray(T)
Sample z-coordinates.
nbins : int, optional, default=100
Number of histogram bins used in x/y-di... | 1.875537 | 2.008142 | 0.933967 |
pi = _to_density(z)
free_energy = _np.inf * _np.ones(shape=z.shape)
nonzero = pi.nonzero()
free_energy[nonzero] = -_np.log(pi[nonzero])
if minener_zero:
free_energy[nonzero] -= _np.min(free_energy[nonzero])
return free_energy | def _to_free_energy(z, minener_zero=False) | Compute free energies from histogram counts.
Parameters
----------
z : ndarray(T)
Histogram counts.
minener_zero : boolean, optional, default=False
Shifts the energy minimum to zero.
Returns
-------
free_energy : ndarray(T)
The free energy values in units of kT. | 2.764176 | 3.314395 | 0.833991 |
allowed_keys = [
'corner_mask', 'alpha', 'locator', 'extend', 'xunits',
'yunits', 'antialiased', 'nchunk', 'hatches', 'zorder']
ignored = [key for key in kwargs.keys() if key not in allowed_keys]
for key in ignored:
_warn(
'{}={} is not an allowed optional parameter ... | def _prune_kwargs(kwargs) | Remove non-allowed keys from a kwargs dictionary.
Parameters
----------
kwargs : dict
Named parameters to prune. | 5.822411 | 6.14963 | 0.94679 |
traj = None
for ff in file_list:
if traj is None:
traj = md.load(ff, top=top)
else:
traj = traj.join(md.load(ff, top=top))
return traj | def single_traj_from_n_files(file_list, top) | Creates a single trajectory object from a list of files | 1.985289 | 2.159769 | 0.919213 |
# The list of copied attributes can be extended here with time
# Or perhaps ask the mdtraj guys to implement something similar?
stop = start+origin.n_frames
target.xyz[start:stop] = origin.xyz
target.unitcell_lengths[start:stop] = origin.unitcell_lengths
target.unitcell_angles[start:stop]... | def copy_traj_attributes(target, origin, start) | Inserts certain attributes of origin into target
:param target: target trajectory object
:param origin: origin trajectory object
:param start: :py:obj:`origin` attributes will be inserted in :py:obj:`target` starting at this index
:return: target: the md trajectory with the attributes of :py:obj:`origin... | 4.626668 | 4.357095 | 1.06187 |
r
if not isinstance(e, Iterable):
raise TypeError("given element {} is not iterable in terms of "
"PyEMMAs coordinate pipeline.".format(e))
# only if we have more than one element
if not e.is_reader and len(self._chain) >= 1:
data_prod... | def add_element(self, e) | r""" Appends a pipeline stage.
Appends the given element to the end of the current chain. | 12.089456 | 11.292476 | 1.070576 |
r
if index > len(self._chain):
raise IndexError("tried to access element %i, but chain has only %i"
" elements" % (index, len(self._chain)))
if type(index) is not int:
raise ValueError(
"index is not a integer but '%s'" % str(... | def set_element(self, index, e) | r""" Replaces a pipeline stage.
Replace an element in chain and return replaced element. | 4.770247 | 4.652707 | 1.025263 |
r
for element in self._chain:
if not element.is_reader and not element._estimated:
element.estimate(element.data_producer, stride=self.param_stride, chunksize=self.chunksize)
self._estimated = True | def parametrize(self) | r"""
Reads all data and discretizes it into discrete trajectories. | 14.930443 | 14.869351 | 1.004109 |
r
result = self._estimated
for el in self._chain:
if not el.is_reader:
result &= el._estimated
return result | def _is_estimated(self) | r"""
Iterates through the pipeline elements and checks if every element is parametrized. | 15.441478 | 11.919847 | 1.295443 |
if not self._estimated:
self.logger.info("not yet parametrized, running now.")
self.parametrize()
return self._chain[-1].dtrajs | def dtrajs(self) | get discrete trajectories | 15.168825 | 12.585473 | 1.205265 |
r
clustering = self._chain[-1]
reader = self._chain[0]
from pyemma.coordinates.clustering.interface import AbstractClustering
assert isinstance(clustering, AbstractClustering)
trajfiles = None
if isinstance(reader, FeatureReader):
trajfiles = reader.... | def save_dtrajs(self, prefix='', output_dir='.',
output_format='ascii', extension='.dtraj') | r"""Saves calculated discrete trajectories. Filenames are taken from
given reader. If data comes from memory dtrajs are written to a default
filename.
Parameters
----------
prefix : str
prepend prefix to filenames.
output_dir : str (optional)
sav... | 6.366404 | 6.922686 | 0.919644 |
count = 0
for a in modifications:
if _debug:
assert a[0] in ('set', 'mv', 'map', 'rm')
logger.debug("processing rule: %s", str(a))
if len(a) == 3:
operation, name, value = a
if operation == 'set':
... | def apply(modifications, state) | applies modifications to given state
Parameters
----------
modifications: list of tuples
created by this class.list method.
state: dict
state dictionary | 3.410899 | 3.391048 | 1.005854 |
r
from pyemma._base.serialization.h5file import H5File
try:
with H5File(file_name=file_name, mode='a') as f:
f.add_serializable(model_name, obj=self, overwrite=overwrite, save_streaming_chain=save_streaming_chain)
except Exception as e:
msg = ('Dur... | def save(self, file_name, model_name='default', overwrite=False, save_streaming_chain=False) | r""" saves the current state of this object to given file and name.
Parameters
-----------
file_name: str
path to desired output file
model_name: str, default='default'
creates a group named 'model_name' in the given file, which will contain all of the data.
... | 4.124007 | 4.849933 | 0.850322 |
from .h5file import H5File
with H5File(file_name, model_name=model_name, mode='r') as f:
return f.model | def load(cls, file_name, model_name='default') | Loads a previously saved PyEMMA object from disk.
Parameters
----------
file_name : str or file like object (has to provide read method).
The file like object tried to be read for a serialized object.
model_name: str, default='default'
if multiple models are cont... | 3.877098 | 4.837276 | 0.801504 |
for field in SerializableMixIn._get_serialize_fields(klass):
# only try to get fields, we actually have.
if hasattr(self, field):
if _debug and field in state:
logger.debug('field "%s" already in state!', field)
state[field] = ... | def _get_state_of_serializeable_fields(self, klass, state) | :return a dictionary {k:v} for k in self.serialize_fields and v=getattr(self, k) | 7.29115 | 6.79051 | 1.073726 |
# klass may have been renamed, so we have to look this up in the class rename registry.
names = [_importable_name(klass)]
# lookup old names, handled by current klass.
from .util import class_rename_registry
names.extend(class_rename_registry.old_handled_by(klass))
... | def _get_version_for_class_from_state(state, klass) | retrieves the version of the current klass from the state mapping from old locations to new ones. | 9.076488 | 8.519446 | 1.065385 |
if _debug:
logger.debug("restoring state for class %s", klass)
for field in SerializableMixIn._get_serialize_fields(klass):
if field in state:
# ensure we can set attributes. Log culprits.
try:
setattr(self, field, sta... | def _set_state_from_serializeable_fields_and_state(self, state, klass) | set only fields from state, which are present in klass.__serialize_fields | 5.829688 | 5.374619 | 1.08467 |
return tuple(filter(lambda c:
SerializableMixIn._get_version(c, require=False) or
(SerializableMixIn._get_serialize_fields(c) or
SerializableMixIn._get_interpolation_map(c)),
self.__class__.__mro__)) | def _get_classes_to_inspect(self) | gets classes self derives from which
1. have custom fields: __serialize_fields
2. provide a modifications map | 10.477015 | 7.821851 | 1.339455 |
from pyemma.coordinates import source
self._estimate(source(X), partial_fit=True)
self._estimated = True
return self | def partial_fit(self, X) | incrementally update the estimates
Parameters
----------
X: array, list of arrays, PyEMMA reader
input data. | 14.463393 | 13.416581 | 1.078024 |
self._check_estimated()
return self._rc.cov_XX(bessel=self.bessel) | def C00_(self) | Instantaneous covariance matrix | 41.166298 | 31.981474 | 1.287192 |
self._check_estimated()
return self._rc.cov_XY(bessel=self.bessel) | def C0t_(self) | Time-lagged covariance matrix | 47.255703 | 33.77177 | 1.399266 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.