code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if (_np.shape(W)[0] == 1): if W[0,0] < epsilon: raise _ZeroRankError( 'All eigenvalues are smaller than %g, rank reduction would discard all dimensions.' % epsilon) Winv = 1./W[0,0] else: sm, Vm = spd_eig(W, epsilon=epsilon, method=method) Winv = ...
def spd_inv(W, epsilon=1e-10, method='QR')
Compute matrix inverse of symmetric positive-definite matrix :math:`W`. by first reducing W to a low-rank approximation that is truly spd (Moore-Penrose inverse). Parameters ---------- W : ndarray((m,m), dtype=float) Symmetric positive-definite (spd) matrix. epsilon : float Tru...
6.122593
6.345891
0.964812
if _np.shape(W)[0] == 1: if W[0,0] < epsilon: raise _ZeroRankError( 'All eigenvalues are smaller than %g, rank reduction would discard all dimensions.' % epsilon) Winv = 1./_np.sqrt(W[0, 0]) sm = _np.ones(1) else: sm, Vm = spd_eig(W, epsilon=epsil...
def spd_inv_sqrt(W, epsilon=1e-10, method='QR', return_rank=False)
Computes :math:`W^{-1/2}` of symmetric positive-definite matrix :math:`W`. by first reducing W to a low-rank approximation that is truly spd. Parameters ---------- W : ndarray((m,m), dtype=float) Symmetric positive-definite (spd) matrix. epsilon : float Truncation parameter. Eigenv...
4.371351
4.546438
0.961489
if (_np.shape(W)[0] == 1): if W[0,0] < epsilon: raise _ZeroRankError( 'All eigenvalues are smaller than %g, rank reduction would discard all dimensions.' % epsilon) L = 1./_np.sqrt(W[0,0]) else: sm, Vm = spd_eig(W, epsilon=epsilon, method=method, canonica...
def spd_inv_split(W, epsilon=1e-10, method='QR', canonical_signs=False)
Compute :math:`W^{-1} = L L^T` of the symmetric positive-definite matrix :math:`W`. by first reducing W to a low-rank approximation that is truly spd. Parameters ---------- W : ndarray((m,m), dtype=float) Symmetric positive-definite (spd) matrix. epsilon : float Truncation paramete...
4.932445
5.128781
0.961719
r L = spd_inv_split(C0, epsilon=epsilon, method=method, canonical_signs=True) Ct_trans = _np.dot(_np.dot(L.T, Ct), L) # solve the symmetric eigenvalue problem in the new basis if _np.allclose(Ct.T, Ct): from scipy.linalg import eigh l, R_trans = eigh(Ct_trans) else: from...
def eig_corr(C0, Ct, epsilon=1e-10, method='QR', sign_maxelement=False)
r""" Solve generalized eigenvalue problem with correlation matrices C0 and Ct Numerically robust solution of a generalized Hermitian (symmetric) eigenvalue problem of the form .. math:: \mathbf{C}_t \mathbf{r}_i = \mathbf{C}_0 \mathbf{r}_i l_i Computes :math:`m` dominant eigenvalues :math:`l_...
3.288053
3.364638
0.977238
if len(args) < 1: raise ValueError('need at least one argument') elif len(args) == 1: return args[0] elif len(args) == 2: return np.dot(args[0], args[1]) else: return np.dot(args[0], mdot(*args[1:]))
def mdot(*args)
Computes a matrix product of multiple ndarrays This is a convenience function to avoid constructs such as np.dot(A, np.dot(B, np.dot(C, D))) and instead use mdot(A, B, C, D). Parameters ---------- *args : an arbitrarily long list of ndarrays that must be compatible for multiplication, i.e....
1.778931
1.715572
1.036932
assert len(M.shape) == 2, 'M is not a matrix' assert M.shape[0] == M.shape[1], 'M is not quadratic' if scipy.sparse.issparse(M): C_cc = M.tocsr() else: C_cc = M C_cc = C_cc[sel, :] if scipy.sparse.issparse(M): C_cc = C_cc.tocsc() C_cc = C_cc[:, sel] ...
def submatrix(M, sel)
Returns a submatrix of the quadratic matrix M, given by the selected columns and row Parameters ---------- M : ndarray(n,n) symmetric matrix sel : int-array selection of rows and columns. Element i,j will be selected if both are in sel. Returns ------- S : ndarray(m,m) ...
2.377483
2.480908
0.958312
# norms evnorms = np.abs(evals) # sort I = np.argsort(evnorms)[::-1] # permute evals2 = evals[I] evecs2 = evecs[:, I] # done return evals2, evecs2
def _sort_by_norm(evals, evecs)
Sorts the eigenvalues and eigenvectors by descending norm of the eigenvalues Parameters ---------- evals: ndarray(n) eigenvalues evecs: ndarray(n,n) eigenvectors in a column matrix Returns ------- (evals, evecs) : ndarray(m), ndarray(n,m) the sorted eigenvalues and ...
3.072494
3.411066
0.900743
# !! PART OF ORIGINAL DOCSTRING INCOMPATIBLE WITH CLASS INTERFACE !! # Example # ------- # We set up multiple stationary models, one for a reference (ground) # state, and two for biased states, and group them in a # MultiStationaryModel. # >>> from pyemma...
def meval(self, f, *args, **kw)
Evaluates the given function call for all models Returns the results of the calls in a list
4.910733
4.88465
1.00534
r if isinstance(X, np.ndarray): if X.ndim == 2: mapped = self._transform_array(X) return mapped else: raise TypeError('Input has the wrong shape: %s with %i' ' dimensions. Expecting a matrix (2 dimens...
def transform(self, X)
r"""Maps the input data through the transformer to correspondingly shaped output data array/list. Parameters ---------- X : ndarray(T, n) or list of ndarray(T_i, n) The input data, where T is the number of time steps and n is the number of dimensions. ...
3.53283
3.587924
0.984645
M = K.shape[0] - 1 # Compute right and left eigenvectors: l, U = scl.eig(K.T) l, U = sort_by_norm(l, U) # Extract the eigenvector for eigenvalue one and normalize: u = np.real(U[:, 0]) v = np.zeros(M+1) v[M] = 1.0 u = u / np.dot(u, v) return u
def _compute_u(K)
Estimate an approximation of the ratio of stationary over empirical distribution from the basis. Parameters: ----------- K0, ndarray(M+1, M+1), time-lagged correlation matrix for the whitened and padded data set. Returns: -------- u : ndarray(M,) coefficients of the ratio station...
4.293242
4.573685
0.938683
'Koopman operator on the modified basis (PC|1)' self._check_estimated() if not self._estimation_finished: self._finish_estimation() return self._K
def K_pc_1(self)
Koopman operator on the modified basis (PC|1)
15.396499
6.370402
2.41688
'weights in the input basis' self._check_estimated() u_mod = self.u_pc_1 N = self._R.shape[0] u_input = np.zeros(N+1) u_input[0:N] = self._R.dot(u_mod[0:-1]) # in input basis u_input[N] = u_mod[-1] - self.mean.dot(self._R.dot(u_mod[0:-1])) return u_input
def u(self)
weights in the input basis
5.433008
4.729064
1.148855
'weights in the input basis (encapsulated in an object)' self._check_estimated() u_input = self.u return _KoopmanWeights(u_input[0:-1], u_input[-1])
def weights(self)
weights in the input basis (encapsulated in an object)
18.409477
9.214987
1.997776
'weightening transformation' self._check_estimated() if not self._estimation_finished: self._finish_estimation() return self._R
def R(self)
weightening transformation
14.081746
8.469083
1.662724
try: attr = getattr(obj, name) except AttributeError as e: if failfast: raise e else: return None try: if inspect.ismethod(attr): # call function return attr(*args, **kwargs) elif isinstance(attr, property): # call property ...
def _call_member(obj, name, failfast=True, *args, **kwargs)
Calls the specified method, property or attribute of the given object Parameters ---------- obj : object The object that will be used name : str Name of method, property or attribute failfast : bool If True, will raise an exception when trying a method that doesn't exist. If...
2.950366
3.058767
0.96456
# run estimation model = None try: # catch any exception estimator.estimate(X, **params) model = estimator.model except KeyboardInterrupt: # we want to be able to interactively interrupt the worker, no matter of failfast=False. raise except: e = sys.exc_...
def _estimate_param_scan_worker(estimator, params, X, evaluate, evaluate_args, failfast, return_exceptions)
Method that runs estimation for several parameter settings. Defined as a worker for parallelization
4.583011
4.636336
0.988498
# set params if params: self.set_params(**params) self._model = self._estimate(X) # ensure _estimate returned something assert self._model is not None self._estimated = True return self
def estimate(self, X, **params)
Estimates the model given the data X Parameters ---------- X : object A reference to the data from which the model will be estimated params : dict New estimation parameter values. The parameters must that have been announced in the __init__ method of ...
6.064334
8.458148
0.716981
signal.signal(SIGNAL_STACKTRACE, signal.SIG_IGN) signal.signal(SIGNAL_PDB, signal.SIG_IGN)
def unregister_signal_handlers()
set signal handlers to default
4.568816
4.188223
1.090872
strategy = strategy.lower() if strategy == 'random': return SelectionStrategyRandom(oasis_obj, strategy, nsel=nsel, neig=neig) elif strategy == 'oasis': return SelectionStrategyOasis(oasis_obj, strategy, nsel=nsel, neig=neig) elif strategy == 'spectral-oasis': return Selecti...
def selection_strategy(oasis_obj, strategy='spectral-oasis', nsel=1, neig=None)
Factory for selection strategy object Returns ------- selstr : SelectionStrategy Selection strategy object
1.870425
2.128595
0.878714
# err_i = sum_j R_{k,ij} A_{k,ji} - d_i self._err = np.sum(np.multiply(self._R_k, self._C_k.T), axis=0) - self._d
def _compute_error(self)
Evaluate the absolute error of the Nystroem approximation for each column
7.266706
6.594658
1.101908
self._selection_strategy = selection_strategy(self, strategy, nsel, neig)
def set_selection_strategy(self, strategy='spectral-oasis', nsel=1, neig=None)
Defines the column selection strategy Parameters ---------- strategy : str One of the following strategies to select new columns: random : randomly choose from non-selected columns oasis : maximal approximation error in the diagonal of :math:`A` s...
4.878883
6.478417
0.753098
# compute R_k and W_k_inv Wk = self._C_k[self._columns, :] self._W_k_inv = np.linalg.pinv(Wk) self._R_k = np.dot(self._W_k_inv, self._C_k.T)
def update_inverse(self)
Recomputes W_k_inv and R_k given the current column selection When computed, the block matrix inverse W_k_inv will be updated. This is useful when you want to compute eigenvalues or get an approximation for the full matrix or individual columns. Calling this function is not strictly necessary, ...
4.269194
3.174486
1.344846
# convenience access k = self._k d = self._d R = self._R_k Winv = self._W_k_inv b_new = col[self._columns][:, None] d_new = d[icol] q_new = R[:, icol][:, None] # calculate R_new schur_complement = d_new - np.dot(b_new.T, q_new) ...
def add_column(self, col, icol, update_error=True)
Attempts to add a single column of :math:`A` to the Nystroem approximation and updates the local matrices Parameters ---------- col : ndarray((N,), dtype=float) new column of :math:`A` icol : int index of new column within :math:`A` update_error : bool, o...
3.283329
3.291654
0.997471
r added = [] for (i, c) in enumerate(columns_new): if self.add_column(C_k_new[:, i], c, update_error=False): added.append(c) # update error only once self._compute_error() # return the columns that were successfully added return np.arra...
def add_columns(self, C_k_new, columns_new)
r""" Attempts to adds a set of new columns of :math:`A` to the Nystroem approximation and updates the local matrices Parameters ---------- C_k_new : ndarray((N,k), dtype=float) :math:`k` new columns of :math:`A` columns_new : int indices of new columns within :ma...
5.103094
5.014937
1.017579
r return np.dot(self._C_k, self._R_k[:, i])
def approximate_column(self, i)
r""" Computes the Nystroem approximation of column :math:`i` of matrix $A \in \mathbb{R}^{n \times n}$.
17.112984
14.197552
1.205348
r # compute the Eigenvalues of C0 using Schur factorization Wk = self._C_k[self._columns, :] L0 = spd_inv_split(Wk, epsilon=epsilon) L = np.dot(self._C_k, L0) return L
def approximate_cholesky(self, epsilon=1e-6)
r""" Compute low-rank approximation to the Cholesky decomposition of target matrix. The decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float, optional, default 1e-6 Cutoff for eigenvalue norms. If ...
15.623005
16.82412
0.928608
L = self.approximate_cholesky(epsilon=epsilon) LL = np.dot(L.T, L) s, V = np.linalg.eigh(LL) # sort s, V = sort_by_norm(s, V) # back-transform eigenvectors Linv = np.linalg.pinv(L.T) V = np.dot(Linv, V) # normalize eigenvectors n...
def approximate_eig(self, epsilon=1e-6)
Compute low-rank approximation of the eigenvalue decomposition of target matrix. If spd is True, the decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float, optional, default 1e-6 Cutoff for eigenval...
2.704237
2.759692
0.979905
err = self._oasis_obj.error if np.allclose(err, 0): return None nsel = self._check_nsel() if nsel is None: return None return self._select(nsel, err)
def select(self)
Selects next column indexes according to defined strategy Returns ------- cols : ndarray((nsel,), dtype=int) selected columns
7.477191
6.611041
1.131016
if not hasattr(self, '_n_jobs'): self._n_jobs = get_n_jobs(logger=getattr(self, 'logger')) return self._n_jobs
def n_jobs(self)
Returns number of jobs/threads to use during assignment of data. Returns ------- If None it will return the setting of 'PYEMMA_NJOBS' or 'SLURM_CPUS_ON_NODE' environment variable. If none of these environment variables exist, the number of processors /or cores is returned. ...
3.679451
4.027583
0.913563
if name not in self._parent: raise KeyError('model "{}" not present'.format(name)) del self._parent[name] if self._current_model_group == name: self._current_model_group = None
def delete(self, name)
deletes model with given name
4.150004
3.929052
1.056235
if name not in self._parent: raise KeyError('model "{}" not present'.format(name)) self._current_model_group = name
def select_model(self, name)
choose an existing model
7.422061
7.229014
1.026704
f = self._parent return {name: {a: f[name].attrs[a] for a in H5File.stored_attributes} for name in f.keys()}
def models_descriptive(self)
list all stored models in given file. Returns ------- dict: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...}
10.785359
13.964381
0.772348
from pyemma import config # no value yet, obtain from config if not hasattr(self, "_show_progress"): val = config.show_progress_bars self._show_progress = val # config disabled progress? elif not config.show_progress_bars: return False...
def show_progress(self)
whether to show the progress of heavy calculations on this object.
7.979916
7.342548
1.086805
if not self.show_progress: return if tqdm_args is None: tqdm_args = {} if not isinstance(amount_of_work, Integral): raise ValueError('amount_of_work has to be of integer type. But is {}'.format(type(amount_of_work))) # if we do not have eno...
def _progress_register(self, amount_of_work, description='', stage=0, tqdm_args=None)
Registers a progress which can be reported/displayed via a progress bar. Parameters ---------- amount_of_work : int Amount of steps the underlying algorithm has to perform. description : str, optional This string will be displayed in the progress bar widget. ...
3.767807
3.88283
0.970377
self.__check_stage_registered(stage) self._prog_rep_descriptions[stage] = description if self._prog_rep_progressbars[stage]: self._prog_rep_progressbars[stage].set_description(description, refresh=False)
def _progress_set_description(self, stage, description)
set description of an already existing progress
4.215308
4.116882
1.023908
if not self.show_progress: return self.__check_stage_registered(stage) if not self._prog_rep_progressbars[stage]: return pg = self._prog_rep_progressbars[stage] pg.update(int(numerator_increment))
def _progress_update(self, numerator_increment, stage=0, show_eta=True, **kw)
Updates the progress. Will update progress bars or other progress output. Parameters ---------- numerator : int numerator of partial work done already in current stage stage : int, nonnegative, default=0 Current stage of the algorithm, 0 or greater
5.501966
6.068234
0.906683
if not self.show_progress: return self.__check_stage_registered(stage) if not self._prog_rep_progressbars[stage]: return pg = self._prog_rep_progressbars[stage] pg.desc = description increment = int(pg.total - pg.n) if increment...
def _progress_force_finish(self, stage=0, description=None)
forcefully finish the progress for given stage
3.688817
3.567989
1.033864
r if not isinstance(xyzall, _np.ndarray): raise ValueError('Input data hast to be a numpy array. Did you concatenate your data?') if xyzall.shape[1] > 50 and not ignore_dim_warning: raise RuntimeError('This function is only useful for less than 50 dimensions. Turn-off this warning ' ...
def plot_feature_histograms(xyzall, feature_labels=None, ax=None, ylog=False, outfile=None, n_bins=50, ignore_dim_warning=False, ...
r"""Feature histogram plot Parameters ---------- xyzall : np.ndarray(T, d) (Concatenated list of) input features; containing time series data to be plotted. Array of T data points in d dimensions (features). feature_labels : iterable of str or pyemma.Featurizer, optional, default=None ...
2.902224
2.786741
1.04144
r old_state = self.in_memory if not old_state and op_in_mem: self._map_to_memory() elif not op_in_mem and old_state: self._clear_in_memory()
def in_memory(self, op_in_mem)
r""" If set to True, the output will be stored in memory.
4.556857
4.488949
1.015128
r self._mapping_to_mem_active = True try: self._Y = self.get_output(stride=stride) from pyemma.coordinates.data import DataInMemory self._Y_source = DataInMemory(self._Y) finally: self._mapping_to_mem_active = False self._in_memory...
def _map_to_memory(self, stride=1)
r"""Maps results to memory. Will be stored in attribute :attr:`_Y`.
6.902261
6.248493
1.104628
if dim is None or (isinstance(dim, float) and dim == 1.0): return min(rank0, rankt) if isinstance(dim, float): return np.searchsorted(VAMPModel._cumvar(singular_values), dim) + 1 else: return np.min([rank0, rankt, dim])
def _dimension(rank0, rankt, dim, singular_values)
output dimension
5.125017
4.88249
1.049673
if self.C00 is None: # no data yet if isinstance(self.dim, int): # return user choice warnings.warn('Returning user-input for dimension, since this model has not yet been estimated.') return self.dim raise RuntimeError('Please call set_model_par...
def dimension(self)
output dimension
11.90655
11.303652
1.053337
L0 = spd_inv_split(self.C00, epsilon=self.epsilon) self._rank0 = L0.shape[1] if L0.ndim == 2 else 1 Lt = spd_inv_split(self.Ctt, epsilon=self.epsilon) self._rankt = Lt.shape[1] if Lt.ndim == 2 else 1 W = np.dot(L0.T, self.C0t).dot(Lt) from scipy.linalg import sv...
def _diagonalize(self)
Performs SVD on covariance matrices and save left, right singular vectors and values in the model. Parameters ---------- scaling : None or string, default=None Scaling to be applied to the VAMP modes upon transformation * None: no scaling will be applied, variance of the...
5.324825
4.38531
1.214241
# TODO: implement for TICA too if test_model is None: test_model = self Uk = self.U[:, 0:self.dimension()] Vk = self.V[:, 0:self.dimension()] res = None if score_method == 'VAMP1' or score_method == 'VAMP2': A = spd_inv_sqrt(Uk.T.dot(test_...
def score(self, test_model=None, score_method='VAMP2')
Compute the VAMP score for this model or the cross-validation score between self and a second model. Parameters ---------- test_model : VAMPModel, optional, default=None If `test_model` is not None, this method computes the cross-validation score between self and `test_...
3.490217
3.585696
0.973373
import functools, numpy as np if array.ndim == 1: shape = (array.shape[0], 1) else: # hold first dimension, multiply the rest shape = (array.shape[0], functools.reduce(lambda x, y: x * y, array.shape[1:])) if not dry: array = np.re...
def _reshape(self, array, dry=False)
reshape given array to 2d. If dry is True, the actual reshaping is not performed. returns tuple (array, shape_2d)
3.231917
2.87535
1.124008
dws = _DWS() us_data = dws.us_sample( ntherm=ntherm, us_fc=us_fc, us_length=us_length, md_length=md_length, nmd=nmd) us_data.update(centers=dws.centers) return us_data
def get_umbrella_sampling_data(ntherm=11, us_fc=20.0, us_length=500, md_length=1000, nmd=20)
Continuous MCMC process in an asymmetric double well potential using umbrella sampling. Parameters ---------- ntherm: int, optional, default=11 Number of umbrella states. us_fc: double, optional, default=20.0 Force constant in kT/length^2 for each umbrella. us_length: int, optional,...
3.745337
4.171662
0.897805
dws = _DWS() mt_data = dws.mt_sample( kt0=kt0, kt1=kt1, length0=length0, length1=length1, n0=n0, n1=n1) mt_data.update(centers=dws.centers) return mt_data
def get_multi_temperature_data(kt0=1.0, kt1=5.0, length0=10000, length1=10000, n0=10, n1=10)
Continuous MCMC process in an asymmetric double well potential at multiple temperatures. Parameters ---------- kt0: double, optional, default=1.0 Temperature in kT for the first thermodynamic state. kt1: double, optional, default=5.0 Temperature in kT for the second thermodynamic state....
3.988498
4.845522
0.823131
r from .potentials import PrinzModel pw = PrinzModel(dt, kT, mass=mass, damping=damping) import warnings import numpy as np with warnings.catch_warnings(record=True) as w: trajs = [pw.sample(x0, nstep, nskip=nskip) for _ in range(ntraj)] if not np.all(tuple(np.isfinite(x) for x i...
def get_quadwell_data(ntraj=10, nstep=10000, x0=0., nskip=1, dt=0.001, kT=1.0, mass=1.0, damping=1.0)
r""" Performs a Brownian dynamics simulation in the Prinz potential (quad well). Parameters ---------- ntraj: int, default=10 how many realizations will be computed nstep: int, default=10000 number of time steps x0: float, default 0 starting point for sampling nskip: int...
5.567806
5.348135
1.041074
extensions = ["%s%s" % (x, suffix) for x in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']] if num == 0: return "0%s" % extensions[0] else: n_bytes = float(abs(num)) place = int(math.floor(math.log(n_bytes, 1024))) return "%.1f%s" % (np.sign(num) * (n_bytes / 1024** place)...
def bytes_to_string(num, suffix='B')
Returns the size of num (bytes) in a human readable form up to Yottabytes (YB). :param num: The size of interest in bytes. :param suffix: A suffix, default 'B' for 'bytes'. :return: a human readable representation of a size in bytes
2.653489
2.730047
0.971957
if string == '0': return 0 import re match = re.match('(\d+\.?\d?)\s?([bBkKmMgGtTpPeEzZyY])?(\D?)', string) if not match: raise RuntimeError('"{}" does not match "[integer] [suffix]"'.format(string)) if match.group(3): raise RuntimeError('unknown suffix: "{}"'.format(mat...
def string_to_bytes(string)
Returns the amount of bytes in a human readable form up to Yottabytes (YB). :param string: integer with suffix (b, k, m, g, t, p, e, z, y) :return: amount of bytes in string representation >>> string_to_bytes('1024') 1024 >>> string_to_bytes('1024k') 1048576 >>> string_to_bytes('4 G') 4...
3.10781
2.738618
1.13481
res = TimeUnit(self) res._factor = self._factor * factor res._unit = self._unit return res
def get_scaled(self, factor)
Get a new time unit, scaled by the given factor
7.472986
6.49289
1.150949
if self._unit == self._UNIT_STEP: return times, 'step' # nothing to do m = np.mean(times) mult = 1.0 cur_unit = self._unit # numbers are too small. Making them larger and reducing the unit: if (m < 0.001): while mult*m < 0.001 and cur_un...
def rescale_around1(self, times)
Suggests a rescaling factor and new physical time unit to balance the given time multiples around 1. Parameters ---------- times : float array array of times in multiple of the present elementary unit
3.147119
3.172415
0.992026
from .h5file import H5File with H5File(filename, mode='r') as f: return f.models_descriptive
def list_models(filename)
Lists all models in given filename. Parameters ---------- filename: str path to filename, where the model has been stored. Returns ------- obj: dict A mapping by name and a comprehensive description like this: {model_name: {'repr' : 'string representation, 'created': 'h...
6.276388
7.666292
0.818699
r if not is_iterable(l): return False return all(is_int(value) for value in l)
def is_iterable_of_int(l)
r""" Checks if l is iterable and contains only integral types
5.252733
5.36026
0.97994
r if not is_iterable(l): return False return all(is_float(value) for value in l)
def is_iterable_of_float(l)
r""" Checks if l is iterable and contains only floating point types
5.195973
4.761707
1.0912
r if isinstance(l, np.ndarray): if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'): return True return False
def is_int_vector(l)
r"""Checks if l is a numpy array of integers
2.83163
2.724355
1.039376
r if isinstance(l, np.ndarray): if l.ndim == 2 and (l.dtype == bool): return True return False
def is_bool_matrix(l)
r"""Checks if l is a 2D numpy array of bools
3.947834
3.5034
1.126858
r if isinstance(l, np.ndarray): if l.dtype.kind == 'f': return True return False
def is_float_array(l)
r"""Checks if l is a numpy array of floats (any dimension
3.898977
5.215244
0.747612
r if isinstance(dtrajs, list): # elements are ints? then wrap into a list if is_list_of_int(dtrajs): return [np.array(dtrajs, dtype=int)] else: for i, dtraj in enumerate(dtrajs): dtrajs[i] = ensure_dtraj(dtraj) return dtrajs else: ...
def ensure_dtraj_list(dtrajs)
r"""Makes sure that dtrajs is a list of discrete trajectories (array of int)
2.986731
2.813048
1.061742
if is_int_vector(I): return I elif is_int(I): return np.array([I]) elif is_list_of_int(I): return np.array(I) elif is_tuple_of_int(I): return np.array(I) elif isinstance(I, set): if require_order: raise TypeError('Argument is an unordered set,...
def ensure_int_vector(I, require_order = False)
Checks if the argument can be converted to an array of ints and does that. Parameters ---------- I: int or iterable of int require_order : bool If False (default), an unordered set is accepted. If True, a set is not accepted. Returns ------- arr : ndarray(n) numpy array wit...
2.479995
2.410671
1.028757
if F is None: return F else: return ensure_int_vector(F, require_order = require_order)
def ensure_int_vector_or_None(F, require_order = False)
Ensures that F is either None, or a numpy array of floats If F is already either None or a numpy array of floats, F is returned (no copied!) Otherwise, checks if the argument can be converted to an array of floats and does that. Parameters ---------- F: None, float, or iterable of float Retur...
2.551673
3.336725
0.764724
if is_float_vector(F): return F elif is_float(F): return np.array([F]) elif is_iterable_of_float(F): return np.array(F) elif isinstance(F, set): if require_order: raise TypeError('Argument is an unordered set, but I require an ordered array of floats') ...
def ensure_float_vector(F, require_order = False)
Ensures that F is a numpy array of floats If F is already a numpy array of floats, F is returned (no copied!) Otherwise, checks if the argument can be converted to an array of floats and does that. Parameters ---------- F: float, or iterable of float require_order : bool If False (defa...
2.936409
2.728852
1.07606
if F is None: return F else: return ensure_float_vector(F, require_order = require_order)
def ensure_float_vector_or_None(F, require_order = False)
Ensures that F is either None, or a numpy array of floats If F is already either None or a numpy array of floats, F is returned (no copied!) Otherwise, checks if the argument can be converted to an array of floats and does that. Parameters ---------- F: float, list of float or 1D-ndarray of float ...
2.485166
3.185152
0.780235
r if isinstance(x, np.ndarray): if x.dtype.kind == 'f': return x elif x.dtype.kind == 'i': return x.astype(default) else: raise TypeError('x is of type '+str(x.dtype)+' that cannot be converted to float') else: raise TypeError('x is not an ...
def ensure_dtype_float(x, default=np.float64)
r"""Makes sure that x is type of float
2.667672
2.448416
1.08955
r try: if shape is not None: if not np.array_equal(np.shape(A), shape): raise AssertionError('Expected shape '+str(shape)+' but given array has shape '+str(np.shape(A))) if uniform is not None: shapearr = np.array(np.shape(A)) is_uniform = np.c...
def assert_array(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None)
r""" Asserts whether the given array or sparse matrix has the given properties Parameters ---------- A : ndarray, scipy.sparse matrix or array-like the array under investigation shape : shape, optional, default=None asserts if the array has the requested shape. Be careful with vectors ...
2.276297
2.214519
1.027897
r if not isinstance(A, np.ndarray): try: A = np.array(A) except: raise AssertionError('Given argument cannot be converted to an ndarray:\n'+str(A)) assert_array(A, shape=shape, uniform=uniform, ndim=ndim, size=size, dtype=dtype, kind=kind) return A
def ensure_ndarray(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None)
r""" Ensures A is an ndarray and does an assert_array with the given parameters Returns ------- A : ndarray If A is already an ndarray, it is just returned. Otherwise this is an independent copy as an ndarray
2.808672
2.581268
1.088098
r if not isinstance(A, np.ndarray) and not scisp.issparse(A): try: A = np.array(A) except: raise AssertionError('Given argument cannot be converted to an ndarray:\n'+str(A)) assert_array(A, shape=shape, uniform=uniform, ndim=ndim, size=size, dtype=dtype, kind=kind) ...
def ensure_ndarray_or_sparse(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None)
r""" Ensures A is an ndarray or a scipy sparse matrix and does an assert_array with the given parameters Returns ------- A : ndarray If A is already an ndarray, it is just returned. Otherwise this is an independent copy as an ndarray
3.17735
2.871676
1.106444
r if A is not None: return ensure_ndarray(A, shape=shape, uniform=uniform, ndim=ndim, size=size, dtype=dtype, kind=kind) else: return None
def ensure_ndarray_or_None(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None)
r""" Ensures A is None or an ndarray and does an assert_array with the given parameters
2.291649
2.505029
0.914819
r if is_float_matrix(traj) or is_bool_matrix(traj): return traj elif is_float_vector(traj): return traj[:,None] else: try: arr = np.array(traj) arr = ensure_dtype_float(arr) if is_float_matrix(arr): return arr if is_...
def ensure_traj(traj)
r"""Makes sure that traj is a trajectory (array of float)
4.416813
4.205876
1.050153
at = topology.atom(index) if topology.n_chains > 1: return "%s %i %s %i %i" % (at.residue.name, at.residue.resSeq, at.name, at.index, at.residue.chain.index ) else: return "%s %i %s %i" % (at.residue.name, at.residue.resSeq, at.name, at.index)
def _describe_atom(topology, index)
Returns a string describing the given atom :param topology: :param index: :return:
2.516281
2.605757
0.965662
if traj_a is None and traj_b is None: return True if traj_a is None and traj_b is not None: return False if traj_a is not None and traj_b is None: return False equal_top = traj_a.top == traj_b.top xyz_close = np.allclose(traj_a.xyz, traj_b.xyz) equal_time = np.all(tr...
def cmp_traj(traj_a, traj_b)
Parameters ---------- traj_a, traj_b: mdtraj.Trajectory
1.779126
1.744576
1.019805
r if is_iterable_of_int(indices1): MDlogger.warning('The 1D arrays input for %s have been sorted, and ' 'index duplicates have been eliminated.\n' 'Check the output of describe() to see the actual order of the features' % fname) # Eliminate dup...
def _parse_pairwise_input(indices1, indices2, MDlogger, fname='')
r"""For input of pairwise type (distances, inverse distances, contacts) checks the type of input the user gave and reformats it so that :py:func:`DistanceFeature`, :py:func:`InverseDistanceFeature`, and ContactFeature can work. In case the input isn't already a list of distances, this function ...
4.525552
4.352436
1.039775
r assert isinstance(group_definitions, list), "group_definitions has to be of type list, not %s"%type(group_definitions) # Handle the special case of just one group if len(group_definitions) == 1: group_pairs = np.array([0,0], ndmin=2) # Sort the elements within each group parsed_group...
def _parse_groupwise_input(group_definitions, group_pairs, MDlogger, mname='')
r"""For input of group type (add_group_mindist), prepare the array of pairs of indices and groups so that :py:func:`MinDistanceFeature` can work This function will: - check the input types - sort the 1D arrays of each entry of group_definitions - check for duplicates...
3.142042
2.982668
1.053433
r atoms_in_residues = [] if subset_of_atom_idxs is None: subset_of_atom_idxs = np.arange(top.n_atoms) special_residues = [] for rr in top.residues: if rr.index in residue_idxs: toappend = np.array([aa.index for aa in rr.atoms if aa.index in subset_of_atom_idxs]) ...
def _atoms_in_residues(top, residue_idxs, subset_of_atom_idxs=None, fallback_to_full_residue=True, MDlogger=None)
r"""Returns a list of ndarrays containing the atom indices in each residue of :obj:`residue_idxs` :param top: mdtraj.Topology :param residue_idxs: list or ndarray (ndim=1) of integers :param subset_of_atom_idxs : iterable of atom_idxs to which the selection has to be restricted. If None, all atoms consider...
2.791684
2.745406
1.016857
if isinstance(arr, np.ndarray) or hasattr(arr, 'data'): # numpy array or sparse matrix with .data attribute data = arr.data if sparse.issparse(arr) else arr return data.flat[0], data.flat[-1] else: # Sparse matrices without .data attribute. Only dok_matrix at # the t...
def _first_and_last_element(arr)
Returns first and last element of numpy array or sparse matrix.
5.223238
4.344646
1.202224
estimator_type = type(estimator) # XXX: not handling dictionaries if estimator_type in (list, tuple, set, frozenset): return estimator_type([clone(e, safe=safe) for e in estimator]) elif not hasattr(estimator, 'get_params'): if not safe: return copy.deepcopy(estimator) ...
def clone(estimator, safe=True)
Constructs a new estimator with the same parameters. Clone does a deep copy of the model in an estimator without actually copying attached data. It yields a new estimator with the same parameters that has not been fit on any data. Parameters ---------- estimator : estimator object, or list, tupl...
3.11491
3.189445
0.976631
# fetch the constructor or the original constructor before # deprecation wrapping if any init = getattr(cls.__init__, 'deprecated_original', cls.__init__) if init is object.__init__: # No explicit constructor to introspect return [] # introspect ...
def _get_param_names(cls)
Get parameter names for the estimator
1.851543
1.756995
1.053813
return RunningCovar(compute_XX=xx, compute_XY=xy, compute_YY=yy, sparse_mode=sparse_mode, modify_data=modify_data, remove_mean=remove_mean, symmetrize=symmetrize, column_selection=column_selection, diag_only=diag_only, nsave=nsave)
def running_covar(xx=True, xy=False, yy=False, remove_mean=False, symmetrize=False, sparse_mode='auto', modify_data=False, column_selection=None, diag_only=False, nsave=5)
Returns a running covariance estimator Returns an estimator object that can be fed chunks of X and Y data, and that can generate on-the-fly estimates of mean, covariance, running sum and second moment matrix. Parameters ---------- xx : bool Estimate the covariance of X xy : bool ...
1.769069
2.191986
0.807062
w1 = self.w w2 = other.w w = w1 + w2 # TODO: fix this div by zero error q = w2 / w1 dsx = q * self.sx - other.sx dsy = q * self.sy - other.sy # update self.w = w1 + w2 self.sx = self.sx + other.sx self.sy = self.sy + other....
def combine(self, other, mean_free=False)
References ---------- [1] http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf
3.397341
3.376307
1.00623
if bessel: return self.Mxy/ (self.w-1) else: return self.Mxy / self.w
def covar(self, bessel=True)
Return covariance matrix: Parameters: ----------- bessel : bool, optional, default=True Use Bessel's correction in order to obtain an unbiased estimator of sample covariances.
6.337626
7.601199
0.833767
if len(self.storage) < 2: return False return self.storage[-2].w <= self.storage[-1].w * self.rtol
def _can_merge_tail(self)
Checks if the two last list elements can be merged
6.272077
5.515038
1.137268
if len(self.storage) == self.nsave: # merge if we must # print 'must merge' self.storage[-1].combine(moments, mean_free=self.remove_mean) else: # append otherwise # print 'append' self.storage.append(moments) # merge if possible ...
def store(self, moments)
Store object X with weight w
5.215712
5.113053
1.020078
# check input T = X.shape[0] if Y is not None: assert Y.shape[0] == T, 'X and Y must have equal length' # Weights cannot be used for compute_YY: if weights is not None and self.compute_YY: raise ValueError('Use of weights is not implemented for c...
def add(self, X, Y=None, weights=None)
Add trajectory to estimate. Parameters ---------- X : ndarray(T, N) array of N time series. Y : ndarray(T, N) array of N time series, usually time shifted version of X. weights : None or float or ndarray(T, ): weights assigned to each trajecto...
2.143998
2.132326
1.005474
# get the reference HMM submodel ref = super(SampledHMSM, self).submodel(states=states, obs=obs) # get the sample submodels samples_sub = [sample.submodel(states=states, obs=obs) for sample in self.samples] # new model return SampledHMSM(samples_sub, ref=ref, con...
def submodel(self, states=None, obs=None)
Returns a HMM with restricted state space Parameters ---------- states : None or int-array Hidden states to restrict the model to (if not None). obs : None, str or int-array Observed states to restrict the model to (if not None). Returns ------- ...
4.553115
5.025855
0.905938
r # determine lag times lags = [1] # build default lag list lag = 1.0 import decimal while lag <= maxlag: lag = lag*multiplier # round up, like python 2 lag = int(decimal.Decimal(lag).quantize(decimal.Decimal('1'), round...
def _generate_lags(maxlag, multiplier)
r"""Generate a set of lag times starting from 1 to maxlag, using the given multiplier between successive lags
4.618973
4.725589
0.977438
from itertools import combinations as _combinations, chain from scipy.special import comb count = comb(len(seq), k, exact=True) res = np.fromiter(chain.from_iterable(_combinations(seq, k)), int, count=count*k) return res.reshape(-1, k)
def combinations(seq, k)
Return j length subsequences of elements from the input iterable. This version uses Numpy/Scipy and should be preferred over itertools. It avoids the creation of all intermediate Python objects. Examples -------- >>> import numpy as np >>> from itertools import combinations as iter_comb >...
3.353716
4.549182
0.737213
arrays = [np.asarray(x) for x in arrays] shape = (len(x) for x in arrays) dtype = arrays[0].dtype ix = np.indices(shape) ix = ix.reshape(len(arrays), -1).T out = np.empty_like(ix, dtype=dtype) for n, _ in enumerate(arrays): out[:, n] = arrays[n][ix[:, n]] return out
def product(*arrays)
Generate a cartesian product of input arrays. Parameters ---------- arrays : list of array-like 1-D arrays to form the cartesian product of. Returns ------- out : ndarray 2-D array of shape (M, len(arrays)) containing cartesian products formed of input arrays.
2.224886
2.977682
0.747187
r r = np.linalg.norm(rvec) - rcut rr = r ** 2 if r < 0.0: return -2.5 * rr return 0.5 * (r - 2.0) * rr
def folding_model_energy(rvec, rcut)
r"""computes the potential energy at point rvec
5.093396
4.507348
1.130021
r rnorm = np.linalg.norm(rvec) if rnorm == 0.0: return np.zeros(rvec.shape) r = rnorm - rcut if r < 0.0: return -5.0 * r * rvec / rnorm return (1.5 * r - 2.0) * rvec / rnorm
def folding_model_gradient(rvec, rcut)
r"""computes the potential's gradient at point rvec
3.229798
2.920881
1.105762
r adw = AsymmetricDoubleWell(dt, kT, mass=mass, damping=damping) return adw.sample(x0, nstep, nskip=nskip)
def get_asymmetric_double_well_data(nstep, x0=0., nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0)
r"""wrapper for the asymmetric double well generator
4.680533
4.554443
1.027685
r fm = FoldingModel(dt, kT, mass=mass, damping=damping, rcut=rcut) return fm.sample(rvec0, nstep, nskip=nskip)
def get_folding_model_data( nstep, rvec0=np.zeros((5)), nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0, rcut=3.0)
r"""wrapper for the folding model generator
4.091492
3.795293
1.078044
r pw = PrinzModel(dt, kT, mass=mass, damping=damping) return pw.sample(x0, nstep, nskip=nskip)
def get_prinz_pot(nstep, x0=0., nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0)
r"""wrapper for the Prinz model generator
5.692517
4.909613
1.159464
r return x - self.coeff_A * self.gradient(x) \ + self.coeff_B * np.random.normal(size=self.dim)
def step(self, x)
r"""perform a single Brownian dynamics step
7.50632
7.358619
1.020072
r x = np.zeros(shape=(nsteps + 1,)) x[0] = x0 for t in range(nsteps): q = x[t] for s in range(nskip): q = self.step(q) x[t + 1] = q return x
def sample(self, x0, nsteps, nskip=1)
r"""generate nsteps sample points
2.773977
2.803383
0.98951
r rvec = np.zeros(shape=(nsteps + 1, self.dim)) rvec[0, :] = rvec0[:] for t in range(nsteps): q = rvec[t, :] for s in range(nskip): q = self.step(q) rvec[t + 1, :] = q[:] return rvec
def sample(self, rvec0, nsteps, nskip=1)
r"""generate nsteps sample points
2.510869
2.676871
0.937987
# set arrow properties dist = _sqrt( ((x2 - x1) / float(Dx))**2 + ((y2 - y1) / float(Dy))**2) arrow_curvature *= 0.075 # standard scale rad = arrow_curvature / (dist) tail_width = width head_width = max(0.5, 2 * width) head_length = head_widt...
def _draw_arrow( self, x1, y1, x2, y2, Dx, Dy, label="", width=1.0, arrow_curvature=1.0, color="grey", patchA=None, patchB=None, shrinkA=0, shrinkB=0, arrow_label_size=None)
Draws a slightly curved arrow from (x1,y1) to (x2,y2). Will allow the given patches at start end end.
2.518489
2.533221
0.994184
initpos = None holddim = None if self.xpos is not None: y = _np.random.random(len(self.xpos)) initpos = _np.vstack((self.xpos, y)).T holddim = 0 elif self.ypos is not None: x = _np.zeros_like(self.xpos) initpos = _np.vs...
def _find_best_positions(self, G)
Finds best positions for the given graph (given as adjacency matrix) nodes by minimizing a network potential.
1.89808
1.883428
1.007779
assert hasattr(class_with_globalize_methods, 'active_set') assert hasattr(class_with_globalize_methods, 'nstates_full') for name, method in class_with_globalize_methods.__dict__.copy().items(): if isinstance(method, property) and hasattr(method.fget, '_map_to_full_state_def_arg'): ...
def add_full_state_methods(class_with_globalize_methods)
class decorator to create "_full_state" methods/properties on the class (so they are valid for all instances created from this class). Parameters ---------- class_with_globalize_methods
2.40007
2.486447
0.965261
if X is None: return None from pyemma._ext.variational.estimators.covar_c._covartools import (variable_cols_double, variable_cols_float, variable_cols_int,...
def variable_cols(X, tol=0.0, min_constant=0)
Evaluates which columns are constant (0) or variable (1) Parameters ---------- X : ndarray Matrix whose columns will be checked for constant or variable. tol : float Tolerance for float-matrices. When set to 0 only equal columns with values will be considered constant. When set ...
2.721506
2.799466
0.972152
r if connectivity=='post_hoc_RE' or connectivity=='BAR_variance': raise Exception('Connectivity type %s not supported for dTRAM data.'%connectivity) state_counts = _np.maximum(count_matrices.sum(axis=1), count_matrices.sum(axis=2)) return _compute_csets( connectivity, state_counts, coun...
def compute_csets_dTRAM(connectivity, count_matrices, nn=None, callback=None)
r""" Computes the largest connected sets for dTRAM data. Parameters ---------- connectivity : string one 'reversible_pathways', 'neighbors', 'summed_count_matrix' or None. Selects the algorithm for measuring overlap between thermodynamic and Markov states. * 'reversible...
7.420557
9.977421
0.743735