code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def _is_utf_8(txt): assert isinstance(txt, six.binary_type) try: _ = six.text_type(txt, 'utf-8') except (TypeError, UnicodeEncodeError): return False else: return True
Check a string is utf-8 encoded :param bytes txt: utf-8 string :return: Whether the string\ is utf-8 encoded or not :rtype: bool
def load_libs(self, scripts_paths): for path in scripts_paths: self.run_script(_read_file(path), identifier=path)
Load script files into the context.\ This can be thought as the HTML script tag.\ The files content must be utf-8 encoded. This is a shortcut for reading the files\ and pass the content to :py:func:`run_script` :param list scripts_paths: Script file paths. :raises OSErr...
def run_script(self, script, identifier=_DEFAULT_SCRIPT_NAME): assert isinstance(script, six.text_type) or _is_utf_8(script) assert isinstance(identifier, six.text_type) or _is_utf_8(identifier) if isinstance(script, six.text_type): script = script.encode('utf-8') ...
Run a JS script within the context.\ All code is ran synchronously,\ there is no event loop. It's thread-safe :param script: utf-8 encoded or unicode string :type script: bytes or str :param identifier: utf-8 encoded or unicode string.\ This is used as the name of the sc...
def eigenvalues(T, k=None, reversible=False, mu=None): r if reversible: try: evals = eigenvalues_rev(T, k=k, mu=mu) except: evals = eigvals(T).real # use fallback code but cast to real else: evals = eigvals(T) # nonreversible """Sort by decreasing absol...
r"""Compute eigenvalues of given transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) k : int or tuple of ints, optional Compute the first k eigenvalues of T reversible : bool, optional Indicate that transition matrix is reversibl...
def eigenvalues_rev(T, k=None, mu=None): r """compute stationary distribution if not given""" if mu is None: mu = stationary_distribution(T) if np.any(mu <= 0): raise ValueError('Cannot symmetrize transition matrix') """ symmetrize T """ smu = np.sqrt(mu) S = smu[:,None] * T...
r"""Compute eigenvalues of reversible transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) k : int or tuple of ints, optional Compute the first k eigenvalues of T mu : (d,) ndarray, optional Stationary distribution of T Retur...
def eigenvectors(T, k=None, right=True, reversible=False, mu=None): r if reversible: eigvec = eigenvectors_rev(T, right=right, mu=mu) else: eigvec = eigenvectors_nrev(T, right=right) """ Return eigenvectors """ if k is None: return eigvec elif isinstance(k, numbers.Integ...
r"""Compute eigenvectors of transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) k : int or tuple of ints, optional Compute the first k eigenvalues of T right : bool, optional If right=True compute right eigenvectors, left eigenve...
def eigenvectors_nrev(T, right=True): r if right: val, R = eig(T, left=False, right=True) """ Sorted eigenvalues and left and right eigenvectors. """ perm = np.argsort(np.abs(val))[::-1] # eigval=val[perm] eigvec = R[:, perm] else: val, L = eig(T, left=True, ...
r"""Compute eigenvectors of transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) k : int or tuple of ints, optional Compute the first k eigenvalues of T right : bool, optional If right=True compute right eigenvectors, left eigenve...
def eigenvectors_rev(T, right=True, mu=None): r if mu is None: mu = stationary_distribution(T) """ symmetrize T """ smu = np.sqrt(mu) S = smu[:,None] * T / smu val, eigvec = eigh(S) """Sort eigenvectors""" perm = np.argsort(np.abs(val))[::-1] eigvec = eigvec[:, perm] if r...
r"""Compute eigenvectors of reversible transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) right : bool, optional If right=True compute right eigenvectors, left eigenvectors otherwise mu : (d,) ndarray, optional Stationar...
def timescales(T, tau=1, k=None, reversible=False, mu=None): r values = eigenvalues(T, reversible=reversible, mu=mu) """Sort by absolute value""" ind = np.argsort(np.abs(values))[::-1] values = values[ind] if k is None: values = values else: values = values[0:k] """Com...
r"""Compute implied time scales of given transition matrix Parameters ---------- T : (M, M) ndarray Transition matrix tau : int, optional lag time k : int, optional Number of time scales reversible : bool, optional Indicate that transition matirx is reversible ...
def timescales_from_eigenvalues(evals, tau=1): r """Check for dominant eigenvalues with large imaginary part""" if not np.allclose(evals.imag, 0.0): warnings.warn('Using eigenvalues with non-zero imaginary part', ImaginaryEigenValueWarning) """Check for multiple eigenvalues of magnitude one""...
r"""Compute implied time scales from given eigenvalues Parameters ---------- evals : eigenvalues tau : lag time Returns ------- ts : ndarray The implied time scales to the given eigenvalues, in the same order.
def is_sparse_file(filename): dirname, basename = os.path.split(filename) name, ext = os.path.splitext(basename) matrix_name, matrix_ext = os.path.splitext(name) if matrix_ext == '.coo': return True else: return False
Determine if the given filename indicates a dense or a sparse matrix If pathname is xxx.coo.yyy return True otherwise False.
def read_matrix_sparse(filename, dtype=float, comments='#'): coo = np.loadtxt(filename, comments=comments, dtype=dtype) if len(coo.shape) == 2 and coo.shape[1] == 3: row = coo[:, 0] col = coo[:, 1] values = coo[:, 2] """Check if imaginary part of row and col is zero""" ...
Check if coo is (M, 3) ndarray
def load_matrix_sparse(filename): coo = np.load(filename) if len(coo.shape) == 2 and coo.shape[1] == 3: row = coo[:, 0] col = coo[:, 1] values = coo[:, 2] """Check if imaginary part of row and col is zero""" if np.all(np.isreal(row)) and np.all(np.isreal(col)): ...
Check if coo is (M, 3) ndarray
def backward_iteration(A, mu, x0, tol=1e-14, maxiter=100): r T = A - mu * eye(A.shape[0], A.shape[0]) T = T.tocsc() """Prefactor T and return a function for solution""" solve = factorized(T) """Starting iterate with ||y_0||=1""" r0 = 1.0 / np.linalg.norm(x0) y0 = x0 * r0 """Local var...
r"""Find eigenvector to approximate eigenvalue via backward iteration. Parameters ---------- A : (N, N) scipy.sparse matrix Matrix for which eigenvector is desired mu : float Approximate eigenvalue for desired eigenvector x0 : (N, ) ndarray Initial guess for eigenvector ...
def stationary_distribution_from_backward_iteration(P, eps=1e-15): r A = P.transpose() mu = 1.0 - eps x0 = np.ones(P.shape[0]) y = backward_iteration(A, mu, x0) pi = y / y.sum() return pi
r"""Fast computation of the stationary vector using backward iteration. Parameters ---------- P : (M, M) scipy.sparse matrix Transition matrix eps : float (optional) Perturbation parameter for the true eigenvalue. Returns ------- pi : (M,) ndarray Stationary vec...
def stationary_distribution_from_eigenvector(T, ncv=None): r vals, vecs = scipy.sparse.linalg.eigs(T.transpose(), k=1, which='LR', ncv=ncv) nu = vecs[:, 0].real mu = nu / np.sum(nu) return mu
r"""Compute stationary distribution of stochastic matrix T. The stationary distribution is the left eigenvector corresponding to the 1 non-degenerate eigenvalue :math: `\lambda=1`. Input: ------ T : numpy array, shape(d,d) Transition matrix (stochastic matrix). ncv : int (optional) ...
def stationary_distribution(T): r fallback = False try: mu = stationary_distribution_from_backward_iteration(T) if np.any(mu < 0): # numerical problem, fall back to more robust algorithm. fallback=True except RuntimeError: fallback = True if fallback: mu...
r"""Compute stationary distribution of stochastic matrix T. Chooses the fastest applicable algorithm automatically Input: ------ T : numpy array, shape(d,d) Transition matrix (stochastic matrix). Returns ------- mu : numpy array, shape(d,) Vector of stationary probabilitie...
def eigenvalues(T, k=None, ncv=None, reversible=False, mu=None): r if k is None: raise ValueError("Number of eigenvalues required for decomposition of sparse matrix") else: if reversible: try: v = eigenvalues_rev(T, k, ncv=ncv, mu=mu) except: # use fa...
r"""Compute the eigenvalues of a sparse transition matrix. Parameters ---------- T : (M, M) scipy.sparse matrix Transition matrix k : int, optional Number of eigenvalues to compute. ncv : int, optional The number of Lanczos vectors generated, `ncv` must be greater than k; ...
def eigenvalues_rev(T, k, ncv=None, mu=None): r """compute stationary distribution if not given""" if mu is None: mu = stationary_distribution(T) if np.any(mu <= 0): raise ValueError('Cannot symmetrize transition matrix') """ symmetrize T """ smu = np.sqrt(mu) D = diags(smu,...
r"""Compute the eigenvalues of a reversible, sparse transition matrix. Parameters ---------- T : (M, M) scipy.sparse matrix Transition matrix k : int Number of eigenvalues to compute. ncv : int, optional The number of Lanczos vectors generated, `ncv` must be greater than k; ...
def eigenvectors(T, k=None, right=True, ncv=None, reversible=False, mu=None): r if k is None: raise ValueError("Number of eigenvectors required for decomposition of sparse matrix") else: if reversible: eigvec = eigenvectors_rev(T, k, right=right, ncv=ncv, mu=mu) retur...
r"""Compute eigenvectors of given transition matrix. Parameters ---------- T : scipy.sparse matrix Transition matrix (stochastic matrix). k : int (optional) or array-like For integer k compute the first k eigenvalues of T else return those eigenvector sepcified by integer indice...
def eigenvectors_nrev(T, k, right=True, ncv=None): r if right: val, vecs = scipy.sparse.linalg.eigs(T, k=k, which='LM', ncv=ncv) ind = np.argsort(np.abs(val))[::-1] return vecs[:, ind] else: val, vecs = scipy.sparse.linalg.eigs(T.transpose(), k=k, which='LM', ncv=ncv) ...
r"""Compute eigenvectors of transition matrix. Parameters ---------- T : (M, M) scipy.sparse matrix Transition matrix (stochastic matrix) k : int Number of eigenvalues to compute right : bool, optional If True compute right eigenvectors, left eigenvectors otherwise ncv :...
def eigenvectors_rev(T, k, right=True, ncv=None, mu=None): r if mu is None: mu = stationary_distribution(T) """ symmetrize T """ smu = np.sqrt(mu) D = diags(smu, 0) Dinv = diags(1.0/smu, 0) S = (D.dot(T)).dot(Dinv) """Compute eigenvalues, eigenvecs using a solver for symmetri...
r"""Compute eigenvectors of reversible transition matrix. Parameters ---------- T : (M, M) scipy.sparse matrix Transition matrix (stochastic matrix) k : int Number of eigenvalues to compute right : bool, optional If True compute right eigenvectors, left eigenvectors otherwis...
def timescales(T, tau=1, k=None, ncv=None, reversible=False, mu=None): r if k is None: raise ValueError("Number of time scales required for decomposition of sparse matrix") values = eigenvalues(T, k=k, ncv=ncv, reversible=reversible) """Check for dominant eigenvalues with large imaginary part""...
r"""Compute implied time scales of given transition matrix Parameters ---------- T : transition matrix tau : lag time k : int (optional) Compute the first k implied time scales. ncv : int (optional) The number of Lanczos vectors generated, `ncv` must be greater than k; i...
def number_of_states(dtrajs): r # determine number of states n nmax = 0 for dtraj in dtrajs: nmax = max(nmax, np.max(dtraj)) # return number of states return nmax + 1
r""" Determine the number of states from a set of discrete trajectories Parameters ---------- dtrajs : list of int-arrays discrete trajectories
def determine_lengths(dtrajs): r if (isinstance(dtrajs[0], (int))): return len(dtrajs) * np.ones((1)) lengths = np.zeros((len(dtrajs))) for i in range(len(dtrajs)): lengths[i] = len(dtrajs[i]) return lengths
r""" Determines the lengths of all trajectories Parameters ---------- dtrajs : list of int-arrays discrete trajectories
def bootstrap_trajectories(trajs, correlation_length): from scipy.stats import rv_discrete # if we have just one trajectory, put it into a one-element list: if (isinstance(trajs[0], (int, int, float))): trajs = [trajs] ntraj = len(trajs) # determine correlation length to be used le...
Generates a randomly resampled count matrix given the input coordinates. See API function for full documentation.
def bootstrap_counts_singletraj(dtraj, lagtime, n): # check if length is sufficient L = len(dtraj) if (lagtime > L): raise ValueError( 'Cannot sample counts with lagtime ' + str(lagtime) + ' from a trajectory with length ' + str(L)) # sample I = np.random.randint(0, L - lagt...
Samples n counts at the given lagtime from the given trajectory
def connected_sets(C, directed=True): r M = C.shape[0] """ Compute connected components of C. nc is the number of components, indices contain the component labels of the states """ nc, indices = csgraph.connected_components(C, directed=directed, connection='strong') states = np.arange(M) #...
r"""Compute connected components for a directed graph with weights represented by the given count matrix. Parameters ---------- C : scipy.sparse matrix or numpy ndarray square matrix specifying edge weights. directed : bool, optional Whether to compute connected components for a dire...
def largest_connected_submatrix(C, directed=True, lcc=None): r if lcc is None: lcc = largest_connected_set(C, directed=directed) """Row slicing""" if scipy.sparse.issparse(C): C_cc = C.tocsr() else: C_cc = C C_cc = C_cc[lcc, :] """Column slicing""" if scipy.spar...
r"""Compute the count matrix of the largest connected set. The input count matrix is used as a weight matrix for the construction of a directed graph. The largest connected set of the constructed graph is computed. Vertices belonging to the largest connected component are used to generate a completely ...
def is_connected(C, directed=True): r nc = csgraph.connected_components(C, directed=directed, connection='strong', \ return_labels=False) return nc == 1
r"""Return true, if the input count matrix is completely connected. Effectively checking if the number of connected components equals one. Parameters ---------- C : scipy.sparse matrix or numpy ndarray Count matrix specifying edge weights. directed : bool, optional Whether to compute...
def to_netflux(flux): r if issparse(flux): return sparse.tpt.to_netflux(flux) elif isdense(flux): return dense.tpt.to_netflux(flux) else: raise _type_not_supported
r"""Compute the netflux from the gross flux. Parameters ---------- flux : (M, M) ndarray Matrix of flux values between pairs of states. Returns ------- netflux : (M, M) ndarray Matrix of netflux values between pairs of states. Notes ----- The netflux or effective c...
def coarsegrain(F, sets): r if issparse(F): return sparse.tpt.coarsegrain(F, sets) elif isdense(F): return dense.tpt.coarsegrain(F, sets) else: raise _type_not_supported
r"""Coarse-grains the flux to the given sets. Parameters ---------- F : (n, n) ndarray or scipy.sparse matrix Matrix of flux values between pairs of states. sets : list of array-like of ints The sets of states onto which the flux is coarse-grained. Notes ----- The coarse gr...
def total_flux(F, A=None): r if issparse(F): return sparse.tpt.total_flux(F, A=A) elif isdense(F): return dense.tpt.total_flux(F, A=A) else: raise _type_not_supported
r"""Compute the total flux, or turnover flux, that is produced by the flux sources and consumed by the flux sinks. Parameters ---------- F : (M, M) ndarray Matrix of flux values between pairs of states. A : array_like (optional) List of integer state labels for set A (reactant) ...
def rate(totflux, pi, qminus): r return dense.tpt.rate(totflux, pi, qminus)
r"""Transition rate for reaction A to B. Parameters ---------- totflux : float The total flux between reactant and product pi : (M,) ndarray Stationary distribution qminus : (M,) ndarray Backward comittor Returns ------- kAB : float The reaction rate (pe...
def mfpt(totflux, pi, qminus): r return dense.tpt.mfpt(totflux, pi, qminus)
r"""Mean first passage time for reaction A to B. Parameters ---------- totflux : float The total flux between reactant and product pi : (M,) ndarray Stationary distribution qminus : (M,) ndarray Backward comittor Returns ------- tAB : float The mean firs...
def pathways(F, A, B, fraction=1.0, maxiter=1000): r if issparse(F): return sparse.pathways.pathways(F, A, B, fraction=fraction, maxiter=maxiter) elif isdense(F): return sparse.pathways.pathways(csr_matrix(F), A, B, fraction=fraction, maxiter=maxiter) else: raise _type_not_suppor...
r"""Decompose flux network into dominant reaction paths. Parameters ---------- F : (M, M) scipy.sparse matrix The flux network (matrix of netflux values) A : array_like The set of starting states B : array_like The set of end states fraction : float, optional Fra...
def _fill_matrix(rot_crop_matrix, eigvectors): (x, y) = rot_crop_matrix.shape row_sums = np.sum(rot_crop_matrix, axis=1) row_sums = np.reshape(row_sums, (x, 1)) # add -row_sums as leftmost column to rot_crop_matrix rot_crop_matrix = np.concatenate((-row_sums, rot_crop_matrix), axis=1) t...
Helper function for opt_soft
def coarsegrain(P, n): M = pcca(P, n) # coarse-grained transition matrix W = np.linalg.inv(np.dot(M.T, M)) A = np.dot(np.dot(M.T, P), M) P_coarse = np.dot(W, A) # symmetrize and renormalize to eliminate numerical errors from msmtools.analysis import stationary_distribution pi_coars...
Coarse-grains transition matrix P to n sets using PCCA Coarse-grains transition matrix P such that the dominant eigenvalues are preserved, using: ..math: \tilde{P} = M^T P M (M^T M)^{-1} See [2]_ for the derivation of this form from the coarse-graining method first derived in [1]_. Reference...
def is_transition_matrix(T, tol=1e-12): r T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): return sparse.assessment.is_transition_matrix(T, tol) else: return dense.assessment.is_transition_matrix(T, tol)
r"""Check if the given matrix is a transition matrix. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Matrix to check tol : float (optional) Floating point tolerance to check with Returns ------- is_transition_matrix : bool True, if T is a valid tran...
def is_rate_matrix(K, tol=1e-12): r K = _types.ensure_ndarray_or_sparse(K, ndim=2, uniform=True, kind='numeric') if _issparse(K): return sparse.assessment.is_rate_matrix(K, tol) else: return dense.assessment.is_rate_matrix(K, tol)
r"""Check if the given matrix is a rate matrix. Parameters ---------- K : (M, M) ndarray or scipy.sparse matrix Matrix to check tol : float (optional) Floating point tolerance to check with Returns ------- is_rate_matrix : bool True, if K is a valid rate matrix, Fal...
def stationary_distribution(T): r # is this a transition matrix? if not is_transition_matrix(T): raise ValueError("Input matrix is not a transition matrix." "Cannot compute stationary distribution") # is the stationary distribution unique? if not is_connected(T, dire...
r"""Compute stationary distribution of stochastic matrix T. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix Returns ------- mu : (M,) ndarray Vector of stationary probabilities. Notes ----- The stationary distribution :math:`\mu` i...
def hitting_probability(T, target): T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') target = _types.ensure_int_vector(target) if _issparse(T): _showSparseConversionWarning() # currently no sparse implementation! return dense.hitting_probability.hitting_prob...
Computes the hitting probabilities for all states to the target states. The hitting probability of state i to the target set A is defined as the minimal, non-negative solution of: .. math:: h_i^A &= 1 \:\:\:\: i\in A \\ h_i^A &= \sum_j p_{ij} h_i^A \:\:\:\: i \notin A...
def expected_counts(T, p0, N): r # check input T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') p0 = _types.ensure_float_vector(p0, require_order=True) # go if _issparse(T): return sparse.expectations.expected_counts(p0, T, N) else: return dense.ex...
r"""Compute expected transition counts for Markov chain with n steps. Parameters ---------- T : (M, M) ndarray or sparse matrix Transition matrix p0 : (M,) ndarray Initial (probability) vector N : int Number of steps to take Returns -------- EC : (M, M) ndarray ...
def expected_counts_stationary(T, N, mu=None): r # check input T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') mu = _types.ensure_float_vector_or_None(mu, require_order=True) # go if _issparse(T): return sparse.expectations.expected_counts_stationary(T, N, mu...
r"""Expected transition counts for Markov chain in equilibrium. Parameters ---------- T : (M, M) ndarray or sparse matrix Transition matrix. N : int Number of steps for chain. mu : (M,) ndarray (optional) Stationary distribution for T. If mu is not specified it will be ...
def expectation(T, a, mu=None): r # check if square matrix and remember size T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') n = T.shape[0] a = _types.ensure_ndarray(a, ndim=1, size=n, kind='numeric') mu = _types.ensure_ndarray_or_None(mu, ndim=1, size=n, kind='numer...
r"""Equilibrium expectation value of a given observable. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix a : (M,) ndarray Observable vector mu : (M,) ndarray (optional) The stationary distribution of T. If given, the stationary dist...
def _pcca_object(T, m): if _issparse(T): _showSparseConversionWarning() T = T.toarray() T = _types.ensure_ndarray(T, ndim=2, uniform=True, kind='numeric') return dense.pcca.PCCA(T, m)
Constructs the pcca object from dense or sparse Parameters ---------- T : (n, n) ndarray or scipy.sparse matrix Transition matrix m : int Number of metastable sets Returns ------- pcca : PCCA PCCA object
def eigenvalue_sensitivity(T, k): r T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): _showSparseConversionWarning() eigenvalue_sensitivity(T.todense(), k) else: return dense.sensitivity.eigenvalue_sensitivity(T, k)
r"""Sensitivity matrix of a specified eigenvalue. Parameters ---------- T : (M, M) ndarray Transition matrix k : int Compute sensitivity matrix for k-th eigenvalue Returns ------- S : (M, M) ndarray Sensitivity matrix for k-th eigenvalue.
def eigenvector_sensitivity(T, k, j, right=True): r T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): _showSparseConversionWarning() eigenvector_sensitivity(T.todense(), k, j, right=right) else: return dense.sensitivity.eigenvector_sens...
r"""Sensitivity matrix of a selected eigenvector element. Parameters ---------- T : (M, M) ndarray Transition matrix (stochastic matrix). k : int Eigenvector index j : int Element index right : bool If True compute for right eigenvector, otherwise compute for lef...
def stationary_distribution_sensitivity(T, j): r T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): _showSparseConversionWarning() stationary_distribution_sensitivity(T.todense(), j) else: return dense.sensitivity.stationary_distribution...
r"""Sensitivity matrix of a stationary distribution element. Parameters ---------- T : (M, M) ndarray Transition matrix (stochastic matrix). j : int Index of stationary distribution element for which sensitivity matrix is computed. Returns ------- S : (M, M) ndarray...
def mfpt_sensitivity(T, target, i): r # check input T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') target = _types.ensure_int_vector(target) # go if _issparse(T): _showSparseConversionWarning() mfpt_sensitivity(T.todense(), target, i) else: ...
r"""Sensitivity matrix of the mean first-passage time from specified state. Parameters ---------- T : (M, M) ndarray Transition matrix target : int or list Target state or set for mfpt computation i : int Compute the sensitivity for state `i` Returns ------- S :...
def committor_sensitivity(T, A, B, i, forward=True): r # check inputs T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') A = _types.ensure_int_vector(A) B = _types.ensure_int_vector(B) if _issparse(T): _showSparseConversionWarning() committor_sensitivity...
r"""Sensitivity matrix of a specified committor entry. Parameters ---------- T : (M, M) ndarray Transition matrix A : array_like List of integer state labels for set A B : array_like List of integer state labels for set B i : int Compute the sensitivity for comm...
def expectation_sensitivity(T, a): r # check input T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') a = _types.ensure_float_vector(a, require_order=True) # go if _issparse(T): _showSparseConversionWarning() return dense.sensitivity.expectation_sensitiv...
r"""Sensitivity of expectation value of observable A=(a_i). Parameters ---------- T : (M, M) ndarray Transition matrix a : (M,) ndarray Observable, a[i] is the value of the observable at state i. Returns ------- S : (M, M) ndarray Sensitivity matrix of the expectati...
def allclose_sparse(A, B, rtol=1e-5, atol=1e-8): A = A.tocsr() B = B.tocsr() """Shape""" same_shape = (A.shape == B.shape) """Data""" if same_shape: diff = (A - B).data same_data = np.allclose(diff, 0.0, rtol=rtol, atol=atol) return same_data else: ret...
Compares two sparse matrices in the same matter like numpy.allclose() Parameters ---------- A : scipy.sparse matrix first matrix to compare B : scipy.sparse matrix second matrix to compare rtol : float relative tolerance atol : float absolute tolerance Return...
def tmatrix_cov(C, row=None): r if row is None: alpha = C + 1.0 # Dirichlet parameters alpha0 = alpha.sum(axis=1) # Sum of paramters (per row) norm = alpha0 ** 2 * (alpha0 + 1.0) """Non-normalized covariance tensor""" Z = -alpha[:, :, np.newaxis] * alpha[:, np.newaxi...
r"""Covariance tensor for the non-reversible transition matrix ensemble Normally the covariance tensor cov(p_ij, p_kl) would carry four indices (i,j,k,l). In the non-reversible case rows are independent so that cov(p_ij, p_kl)=0 for i not equal to k. Therefore the function will only return cov(p_ij, p_...
def dirichlet_covariance(alpha): r alpha0 = alpha.sum() norm = alpha0 ** 2 * (alpha0 + 1.0) """Non normalized covariance""" Z = -alpha[:, np.newaxis] * alpha[np.newaxis, :] """Correct diagonal""" ind = np.diag_indices(Z.shape[0]) Z[ind] += alpha0 * alpha """Covariance matrix""" ...
r"""Covariance matrix for Dirichlet distribution. Parameters ---------- alpha : (M, ) ndarray Parameters of Dirichlet distribution Returns ------- cov : (M, M) ndarray Covariance matrix
def error_perturbation_single(C, S, R=None): r cov = tmatrix_cov(C) # (M, M, M) if R is None: R = S X = S[:, :, np.newaxis] * cov * R[:, np.newaxis, :] return X.sum()
r"""Error-perturbation arising from a given sensitivity Parameters ---------- C : (M, M) ndarray Count matrix S : (M, M) ndarray Sensitivity matrix R : (M, M) ndarray (optional) Sensitivity matrix Returns ------- var : float Variance (covariance) of obs...
def error_perturbation_var(C, S): r K = S.shape[0] cov = tmatrix_cov(C) for i in range(K): R = S[i, :, :] X[i] = (R[:, :, np.newaxis] * cov * R[:, np.newaxis, :]).sum()
r"""Error-perturbation arising from a given sensitivity Parameters ---------- C : (M, M) ndarray Count matrix S : (K, M, M) ndarray Sensitivity tensor
def error_perturbation_cov(C, S): r K = S.shape[0] X = np.zeros((K, K)) cov = tmatrix_cov(C) for i in range(K): for j in range(K): Q = S[i, :, :] R = S[j, :, :] X[i, j] = (Q[:, :, np.newaxis] * cov * R[:, np.newaxis, :]).sum() return X
r"""Error-perturbation arising from a given sensitivity Parameters ---------- C : (M, M) ndarray Count matrix S : (K, M, M) ndarray Sensitivity tensor Returns ------- X : (K, K) ndarray Covariance matrix for given sensitivity
def error_perturbation(C, S): r if len(S.shape) == 2: # Scalar observable return error_perturbation_single(C, S) elif len(S.shape) == 3: # Vector observable return error_perturbation_cov(C, S) else: raise ValueError("Sensitivity matrix S has to be a 2d or 3d array")
r"""Error perturbation for given sensitivity matrix. Parameters ---------- C : (M, M) ndarray Count matrix S : (M, M) ndarray or (K, M, M) ndarray Sensitivity matrix (for scalar observable) or sensitivity tensor for vector observable Returns ------- X : float or (K,...
def mfpt_between_sets(T, target, origin, mu=None): if mu is None: mu = stationary_distribution(T) """Stationary distribution restriced on starting set X""" nuX = mu[origin] muX = nuX / np.sum(nuX) """Mean first-passage time to Y (for all possible starting states)""" tY = mfpt(T, t...
Compute mean-first-passage time between subsets of state space. Parameters ---------- T : scipy.sparse matrix Transition matrix. target : int or list of int Set of target states. origin : int or list of int Set of starting states. mu : (M,) ndarray (optional) The...
def mydot(A, B): r if issparse(A) : return A.dot(B) elif issparse(B): return (B.T.dot(A.T)).T else: return np.dot(A, B)
r"""Dot-product that can handle dense and sparse arrays Parameters ---------- A : numpy ndarray or scipy sparse matrix The first factor B : numpy ndarray or scipy sparse matrix The second factor Returns C : numpy ndarray or scipy sparse matrix The dot-product of A and B
def factor_aug(z, DPhival, G, A): M, N = G.shape P, N = A.shape l = z[N+P:N+P+M] """Slacks""" s = z[N+P+M:] """Sigma matrix""" SIG = diags(l/s, 0) """Condensed system""" if issparse(DPhival): if not issparse(A): A = csr_matrix(A) H = DP...
Multiplier for inequality constraints
def solve_factorized_aug(z, Fval, LU, G, A): M, N=G.shape P, N=A.shape m = M """Primal variable""" x = z[0:N] """Multiplier for equality constraints""" nu = z[N:N+P] """Multiplier for inequality constraints""" l = z[N+P:N+P+M] """Slacks""" s = z[N+P+M:] """...
Total number of inequality constraints
def factor_schur(z, DPhival, G, A): M, N = G.shape P, N = A.shape l = z[N+P:N+P+M] """Slacks""" s = z[N+P+M:] """Sigma matrix""" SIG = diags(l/s, 0) """Augmented Jacobian""" H = DPhival + mydot(G.T, mydot(SIG, G)) """Factor H""" LU_H = myfactor(H) """Compute H^{...
Multiplier for inequality constraints
def solve_factorized_schur(z, Fval, LU, G, A): M, N=G.shape P, N=A.shape m = M """Primal variable""" x = z[0:N] """Multiplier for equality constraints""" nu = z[N:N+P] """Multiplier for inequality constraints""" l = z[N+P:N+P+M] """Slacks""" s = z[N+P+M:] "...
Total number of inequality constraints
def expected_counts(p0, T, N): r if (N <= 0): EC = coo_matrix(T.shape, dtype=float) return EC else: """Probability vector after (k=0) propagations""" p_k = 1.0 * p0 """Sum of vectors after (k=0) propagations""" p_sum = 1.0 * p_k """Transpose T to use s...
r"""Compute expected transition counts for Markov chain after N steps. Expected counts are computed according to ..math:: E[C_{ij}^{(n)}]=\sum_{k=0}^{N-1} (p_0^T T^{k})_{i} p_{ij} Parameters ---------- p0 : (M,) ndarray Starting (probability) vector of the chain. T : (M, M) sparse mat...
def expected_counts_stationary(T, n, mu=None): r if (n <= 0): EC = coo_matrix(T.shape, dtype=float) return EC else: if mu is None: mu = stationary_distribution(T) D_mu = diags(mu, 0) EC = n * D_mu.dot(T) return EC
r"""Expected transition counts for Markov chain in equilibrium. Since mu is stationary for T we have .. math:: E(C^{(n)})=n diag(mu)*T. Parameters ---------- T : (M, M) sparse matrix Transition matrix. n : int Number of steps for chain. mu : (M,) ndarray (optional...
def fingerprint_correlation(P, obs1, obs2=None, tau=1, k=None, ncv=None): r return fingerprint(P, obs1, obs2=obs2, tau=tau, k=k, ncv=ncv)
r"""Compute dynamical fingerprint crosscorrelation. The dynamical fingerprint autocorrelation is the timescale amplitude spectrum of the autocorrelation of the given observables under the action of the dynamics P Parameters ---------- P : ndarray, shape=(n, n) or scipy.sparse matrix Tr...
def fingerprint_relaxation(P, p0, obs, tau=1, k=None, ncv=None): r one_vec = np.ones(P.shape[0]) return fingerprint(P, one_vec, obs2=obs, p0=p0, tau=tau, k=k, ncv=ncv)
r"""Compute dynamical fingerprint crosscorrelation. The dynamical fingerprint autocorrelation is the timescale amplitude spectrum of the autocorrelation of the given observables under the action of the dynamics P Parameters ---------- P : ndarray, shape=(n, n) or scipy.sparse matrix Tr...
def fingerprint(P, obs1, obs2=None, p0=None, tau=1, k=None, ncv=None): r if obs2 is None: obs2 = obs1 R, D, L = rdl_decomposition(P, k=k, ncv=ncv) """Stationary vector""" mu = L[0, :] """Extract diagonal""" w = np.diagonal(D) """Compute time-scales""" timescales = timescales_...
r"""Dynamical fingerprint for equilibrium or relaxation experiment The dynamical fingerprint is given by the implied time-scale spectrum together with the corresponding amplitudes. Parameters ---------- P : (M, M) scipy.sparse matrix Transition matrix obs1 : (M,) ndarray Observ...
def correlation_matvec(P, obs1, obs2=None, times=[1]): r if obs2 is None: obs2 = obs1 """Compute stationary vector""" mu = statdist(P) obs1mu = mu * obs1 times = np.asarray(times) """Sort in increasing order""" ind = np.argsort(times) times = times[ind] if times[0] < 0...
r"""Time-correlation for equilibrium experiment - via matrix vector products. Parameters ---------- P : (M, M) ndarray Transition matrix obs1 : (M,) ndarray Observable, represented as vector on state space obs2 : (M,) ndarray (optional) Second observable, for cross-correlati...
def relaxation(P, p0, obs, times=[1], k=None, ncv=None): r M = P.shape[0] T = np.asarray(times).max() if T < M: return relaxation_matvec(P, p0, obs, times=times) else: return relaxation_decomp(P, p0, obs, times=times, k=k, ncv=ncv)
r"""Relaxation experiment. The relaxation experiment describes the time-evolution of an expectation value starting in a non-equilibrium situation. Parameters ---------- P : (M, M) ndarray Transition matrix p0 : (M,) ndarray (optional) Initial distribution for a relaxation e...
def relaxation_decomp(P, p0, obs, times=[1], k=None, ncv=None): r R, D, L = rdl_decomposition(P, k=k, ncv=ncv) """Extract eigenvalues""" ev = np.diagonal(D) """Amplitudes""" amplitudes = np.dot(p0, R) * np.dot(L, obs) """Propgate eigenvalues""" times = np.asarray(times) ev_t = ev[np....
r"""Relaxation experiment. The relaxation experiment describes the time-evolution of an expectation value starting in a non-equilibrium situation. Parameters ---------- P : (M, M) ndarray Transition matrix p0 : (M,) ndarray (optional) Initial distribution for a relaxation e...
def relaxation_matvec(P, p0, obs, times=[1]): r times = np.asarray(times) """Sort in increasing order""" ind = np.argsort(times) times = times[ind] if times[0] < 0: raise ValueError("Times can not be negative") dt = times[1:] - times[0:-1] nt = len(times) relaxations = np....
r"""Relaxation experiment. The relaxation experiment describes the time-evolution of an expectation value starting in a non-equilibrium situation. Parameters ---------- P : (M, M) ndarray Transition matrix p0 : (M,) ndarray (optional) Initial distribution for a relaxation e...
def propagate(A, x, N): r y = 1.0 * x for i in range(N): y = A.dot(y) return y
r"""Use matrix A to propagate vector x. Parameters ---------- A : (M, M) scipy.sparse matrix Matrix of propagator x : (M, ) ndarray or scipy.sparse matrix Vector to propagate N : int Number of steps to propagate Returns ------- y : (M, ) ndarray or scipy.sparse ...
def _maxlength(X): return np.fromiter((map(lambda x: len(x), X)), dtype=int).max()
Returns the maximum length of signal trajectories X
def aliased(aliased_class): original_methods = aliased_class.__dict__.copy() for name, method in original_methods.items(): if hasattr(method, '_aliases'): # Add the aliases for 'method', but don't override any # previously-defined attribute of 'aliased_class' for...
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...
def deprecated(*optional_message): def _deprecated(func, *args, **kw): caller_stack = stack()[1:] 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 ...
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.
def estimation_required(func, *args, **kw): self = args[0] if len(args) > 0 else None if self and hasattr(self, '_estimated') and not self._estimated: raise ValueError("Tried calling %s on %s which requires the estimator to be estimated." % (func.__name__, self.__class__.__...
Decorator checking the self._estimated flag in an Estimator instance, raising a value error if the decorated function is called before estimator.estimate() has been called. If mixed with a property-annotation, this annotation needs to come first in the chain of function calls, i.e., @property @estimat...
def generate_traj(P, N, start=None, stop=None, dt=1): sampler = MarkovChainSampler(P, dt=dt) return sampler.trajectory(N, start=start, stop=stop)
Generates a realization of the Markov chain with transition matrix P. Parameters ---------- P : (n, n) ndarray transition matrix N : int trajectory length start : int, optional, default = None starting state. If not given, will sample from the stationary distribution of P ...
def generate_trajs(P, M, N, start=None, stop=None, dt=1): sampler = MarkovChainSampler(P, dt=dt) return sampler.trajectories(M, N, start=start, stop=stop)
Generates multiple realizations of the Markov chain with transition matrix P. Parameters ---------- P : (n, n) ndarray transition matrix M : int number of trajectories N : int trajectory length start : int, optional, default = None starting state. If not given, w...
def trajectory(self, N, start=None, stop=None): # check input stop = types.ensure_int_vector_or_None(stop, require_order=False) if start is None: if self.mudist is None: # compute mu, the stationary distribution of P import msmtools.analysis ...
Generates a trajectory realization of length N, starting from state s Parameters ---------- N : int trajectory length start : int, optional, default = None starting state. If not given, will sample from the stationary distribution of P stop : int or int-a...
def trajectories(self, M, N, start=None, stop=None): trajs = [self.trajectory(N, start=start, stop=stop) for _ in range(M)] return trajs
Generates M trajectories, each of length N, starting from state s Parameters ---------- M : int number of trajectories N : int trajectory length start : int, optional, default = None starting state. If not given, will sample from the stationar...
def _split_sequences_singletraj(dtraj, nstates, lag): sall = [[] for _ in range(nstates)] res_states = [] res_seqs = [] for t in range(len(dtraj)-lag): sall[dtraj[t]].append(dtraj[t+lag]) for i in range(nstates): if len(sall[i]) > 0: res_states.append(i) ...
splits the discrete trajectory into conditional sequences by starting state Parameters ---------- dtraj : int-iterable discrete trajectory nstates : int total number of discrete states lag : int lag time
def _split_sequences_multitraj(dtrajs, lag): n = number_of_states(dtrajs) res = [] for i in range(n): res.append([]) for dtraj in dtrajs: states, seqs = _split_sequences_singletraj(dtraj, n, lag) for i in range(len(states)): res[states[i]].append(seqs[i]) ret...
splits the discrete trajectories into conditional sequences by starting state Parameters ---------- dtrajs : list of int-iterables discrete trajectories nstates : int total number of discrete states lag : int lag time
def _indicator_multitraj(ss, i, j): iseqs = ss[i] res = [] for iseq in iseqs: x = np.zeros(len(iseq)) I = np.where(iseq == j) x[I] = 1.0 res.append(x) return res
Returns conditional sequence for transition i -> j given all conditional sequences
def transition_matrix_non_reversible(C): r # multiply by 1.0 to make sure we're not doing integer division rowsums = 1.0 * np.sum(C, axis=1) if np.min(rowsums) <= 0: raise ValueError( "Transition matrix has row sum of " + str(np.min(rowsums)) + ". Must have strictly positive row sums...
r""" Estimates a non-reversible transition matrix from count matrix C T_ij = c_ij / c_i where c_i = sum_j c_ij Parameters ---------- C: ndarray, shape (n,n) count matrix Returns ------- T: Estimated transition matrix
def transition_matrix_reversible_pisym(C, return_statdist=False, **kwargs): r # nonreversible estimate T_nonrev = transition_matrix_non_reversible(C) from msmtools.analysis import stationary_distribution pi = stationary_distribution(T_nonrev) # correlation matrix X = pi[:, None] * T_nonrev ...
r""" Estimates reversible transition matrix as follows: ..:math: p_{ij} = c_{ij} / c_i where c_i = sum_j c_{ij} \pi_j = \sum_j \pi_i p_{ij} x_{ij} = \pi_i p_{ij} + \pi_j p_{ji} p^{rev}_{ij} = x_{ij} / x_i where x_i = sum_j x_{ij} In words: takes the nonreversible transition...
def backward_iteration(A, mu, x0, tol=1e-14, maxiter=100): r T = A - mu * np.eye(A.shape[0]) """LU-factor of T""" lupiv = lu_factor(T) """Starting iterate with ||y_0||=1""" r0 = 1.0 / np.linalg.norm(x0) y0 = x0 * r0 """Local variables for inverse iteration""" y = 1.0 * y0 r = 1.0...
r"""Find eigenvector to approximate eigenvalue via backward iteration. Parameters ---------- A : (N, N) ndarray Matrix for which eigenvector is desired mu : float Approximate eigenvalue for desired eigenvector x0 : (N, ) ndarray Initial guess for eigenvector tol : float ...
def stationary_distribution_from_eigenvector(T): r val, L = eig(T, left=True, right=False) """ Sorted eigenvalues and left and right eigenvectors. """ perm = np.argsort(val)[::-1] val = val[perm] L = L[:, perm] """ Make sure that stationary distribution is non-negative and l1-normalized ""...
r"""Compute stationary distribution of stochastic matrix T. The stationary distribution is the left eigenvector corresponding to the non-degenerate eigenvalue :math: `\lambda=1`. Input: ------ T : numpy array, shape(d,d) Transition matrix (stochastic matrix). Returns ------- m...
def time_correlation_by_diagonalization(P, pi, obs1, obs2=None, time=1, rdl=None): if rdl is None: raise ValueError("no rdl decomposition") R, D, L = rdl d_times = np.diag(D) ** time diag_inds = np.diag_indices_from(D) D_time = np.zeros(D.shape, dtype=d_times.dtype) D_time[diag_ind...
calculates time correlation. Raises P to power 'times' by diagonalization. If rdl tuple (R, D, L) is given, it will be used for further calculation.
def time_correlations_direct(P, pi, obs1, obs2=None, times=[1]): r n_t = len(times) times = np.sort(times) # sort it to use caching of previously computed correlations f = np.zeros(n_t) # maximum time > number of rows? if times[-1] > P.shape[0]: use_diagonalization = True R, D,...
r"""Compute time-correlations of obs1, or time-cross-correlation with obs2. The time-correlation at time=k is computed by the matrix-vector expression: cor(k) = obs1' diag(pi) P^k obs2 Parameters ---------- P : ndarray, shape=(n, n) or scipy.sparse matrix Transition matrix obs1 : ndar...
def time_relaxations_direct(P, p0, obs, times=[1]): r n_t = len(times) times = np.sort(times) # maximum time > number of rows? if times[-1] > P.shape[0]: use_diagonalization = True R, D, L = rdl_decomposition(P) # discard imaginary part, if all elements i=0 if not np...
r"""Compute time-relaxations of obs with respect of given initial distribution. relaxation(k) = p0 P^k obs Parameters ---------- P : ndarray, shape=(n, n) or scipy.sparse matrix Transition matrix p0 : ndarray, shape=(n) initial distribution obs : ndarray, shape=(n) Vect...
def factor_aug(z, DPhival, G, A): r M, N = G.shape P, N = A.shape """Multiplier for inequality constraints""" l = z[N+P:N+P+M] """Slacks""" s = z[N+P+M:] """Sigma matrix""" SIG = diags(l/s, 0) # SIG = diags(l*s, 0) """Convert A""" if not issparse(A): A = csr_ma...
r"""Set up augmented system and return. Parameters ---------- z : (N+P+M+M,) ndarray Current iterate, z = (x, nu, l, s) DPhival : LinearOperator Jacobian of the variational inequality mapping G : (M, N) ndarray or sparse matrix Inequality constraints A : (P, N) ndarray o...
def I(self): r return list(set(range(self.nstates)) - set(self._A) - set(self._B))
r"""Returns the set of intermediate states
def pathways(self, fraction=1.0, maxiter=1000): r return tptapi.pathways(self.net_flux, self.A, self.B, fraction=fraction, maxiter=maxiter)
r"""Decompose flux network into dominant reaction paths. Parameters ---------- fraction : float, optional Fraction of total flux to assemble in pathway decomposition maxiter : int, optional Maximum number of pathways for decomposition Returns ---...
def _pathways_to_flux(self, paths, pathfluxes, n=None): r if (n is None): n = 0 for p in paths: n = max(n, np.max(p)) n += 1 # initialize flux F = np.zeros((n, n)) for i in range(len(paths)): p = paths[i] ...
r"""Sums up the flux from the pathways given Parameters ----------- paths : list of int-arrays list of pathways pathfluxes : double-array array with path fluxes n : int number of states. If not set, will be automatically determined. Ret...
def major_flux(self, fraction=0.9): r (paths, pathfluxes) = self.pathways(fraction=fraction) return self._pathways_to_flux(paths, pathfluxes, n=self.nstates)
r"""Returns the main pathway part of the net flux comprising at most the requested fraction of the full flux.
def transition_matrix(self): P0 = np.diag(self.r, k=0) P1 = np.diag(self.p[0:-1], k=1) P_1 = np.diag(self.q[1:], k=-1) return P0 + P1 + P_1
Tridiagonal transition matrix for birth and death chain Returns ------- P : (N,N) ndarray Transition matrix for birth and death chain with given creation and anhilation probabilities.
def transition_matrix_sparse(self): P = diags([self.q[1:], self.r, self.p[0:-1]], [-1, 0, 1]) return P
Tridiagonal transition matrix for birth and death chain Returns ------- P : (N,N) scipy.sparse matrix Transition matrix for birth and death chain with given birth and death probabilities.