code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# only consider first n_clusters eigenvectors eigvectors = eigvectors[:, :n_clusters] # crop first row and first column from rot_matrix # rot_crop_matrix = rot_matrix[1:,1:] rot_crop_matrix = rot_matrix[1:][:, 1:] (x, y) = rot_crop_matrix.shape # reshape rot_crop_matrix into linear v...
def _opt_soft(eigvectors, rot_matrix, n_clusters)
Optimizes the PCCA+ rotation matrix such that the memberships are exclusively nonnegative. Parameters ---------- eigenvectors : ndarray A matrix with the sorted eigenvectors in the columns. The stationary eigenvector should be first, then the one to the slowest relaxation process, etc. ...
2.913987
3.0093
0.968327
(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) tmp = -np.dot(eigvectors[:, 1:], rot_crop_matrix...
def _fill_matrix(rot_crop_matrix, eigvectors)
Helper function for opt_soft
2.399872
2.366107
1.01427
# test connectivity from msmtools.estimation import connected_sets labels = connected_sets(P) n_components = len(labels) # (n_components, labels) = connected_components(P, connection='strong') if (n_components > 1): raise ValueError("Transition matrix is disconnected. Cannot use pcca...
def _pcca_connected(P, n, return_rot=False)
PCCA+ spectral clustering method with optimized memberships [1]_ Clusters the first n_cluster eigenvectors of a transition matrix in order to cluster the states. This function assumes that the transition matrix is fully connected. Parameters ---------- P : ndarray (n,n) Transition matrix. ...
6.162675
5.916187
1.041663
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_coarse = np.dot(M.T, station...
def coarsegrain(P, n)
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...
3.79053
3.99249
0.949415
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)
def is_transition_matrix(T, tol=1e-12)
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...
5.193741
8.760164
0.592882
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)
def is_rate_matrix(K, tol=1e-12)
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...
5.309823
8.746539
0.607077
r T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): return sparse.assessment.is_connected(T, directed=directed) else: T = _csr_matrix(T) return sparse.assessment.is_connected(T, directed=directed)
def is_connected(T, directed=True)
r"""Check connectivity of the given matrix. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Matrix to check directed : bool (optional) If True respect direction of transitions, if False do not distinguish between forward and backward transitions Returns --...
4.98748
7.716536
0.646337
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.assessment.is_reversible(T, mu, tol) else: return dense.assessment.is_reversible(T,...
def is_reversible(T, mu=None, tol=1e-12)
r"""Check reversibility of the given transition matrix. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix mu : (M,) ndarray (optional) Test reversibility with respect to this vector tol : float (optional) Floating point tolerance to check wit...
5.426889
7.317065
0.741676
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, directed=False): raise Value...
def stationary_distribution(T)
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...
5.407028
6.486997
0.833518
r T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): return sparse.decomposition.timescales(T, tau=tau, k=k, ncv=ncv, reversible=reversible, mu=mu) else: return dense.decomposition.timescales(T, tau...
def timescales(T, tau=1, k=None, ncv=None, reversible=False, mu=None)
r"""Compute implied time scales of given transition matrix. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix tau : int (optional) The time-lag (in elementary time steps of the microstate trajectory) at which the given transition matrix was ...
3.421708
4.965337
0.689119
r T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): if right: return sparse.decomposition.eigenvectors(T, k=k, right=right, ncv=ncv) else: return sparse.decomposition.eigenvectors(T, k=k, right=right, ncv=ncv).T else: ...
def eigenvectors(T, k=None, right=True, ncv=None, reversible=False, mu=None)
r"""Compute eigenvectors of given transition matrix. Parameters ---------- T : numpy.ndarray, shape(d,d) or scipy.sparse matrix Transition matrix (stochastic matrix) k : int (optional) Compute the first k eigenvectors ncv : int (optional) The number of Lanczos vectors genera...
2.537637
3.465299
0.7323
r # check inputs T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') target = _types.ensure_int_vector(target) origin = _types.ensure_int_vector_or_None(origin) # go if _issparse(T): if origin is None: t_tau = sparse.mean_first_passage_time.mfpt(T...
def mfpt(T, target, origin=None, tau=1, mu=None)
r"""Mean first passage times (from a set of starting states - optional) to a set of target states. Parameters ---------- T : ndarray or scipy.sparse matrix, shape=(n,n) Transition matrix. target : int or list of int Target states for mfpt calculation. origin : int or list of int...
3.728615
3.787686
0.984405
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_probability(T.toarray(), target) els...
def hitting_probability(T, target)
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...
6.11782
7.31585
0.836242
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.expectations.expected_counts(p0, ...
def expected_counts(T, p0, N)
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 ...
5.735813
8.267198
0.693804
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=mu) else: return dense.expectation...
def expected_counts_stationary(T, N, mu=None)
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 ...
4.984588
6.666422
0.747716
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] # will not do fingerprint analysis for nonreversible matrices if not is_reversible(T): raise ValueError('Fingerprint calculation is not supported for n...
def fingerprint_relaxation(T, p0, obs, tau=1, k=None, ncv=None)
r"""Dynamical fingerprint for relaxation experiment. The dynamical fingerprint is given by the implied time-scale spectrum together with the corresponding amplitudes. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix obs1 : (M,) ndarray Observabl...
3.819255
4.983599
0.766365
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='numeric') # go if not mu: ...
def expectation(T, a, mu=None)
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...
4.485921
5.377739
0.834165
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] p0 = _types.ensure_ndarray(p0, ndim=1, size=n, kind='numeric') obs = _types.ensure_ndarray(obs, ndim=1, size=n, kind='numeric') times = _types.ensure_int_v...
def relaxation(T, p0, obs, times=(1), k=None, ncv=None)
r"""Relaxation experiment. The relaxation experiment describes the time-evolution of an expectation value starting in a non-equilibrium situation. Parameters ---------- T : (M, M) ndarray or scipy.sparse matrix Transition matrix p0 : (M,) ndarray (optional) Initial distribu...
3.615076
4.53034
0.79797
if _issparse(T): _showSparseConversionWarning() T = T.toarray() T = _types.ensure_ndarray(T, ndim=2, uniform=True, kind='numeric') return dense.pcca.PCCA(T, m)
def _pcca_object(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
8.873096
9.438076
0.940138
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)
def 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.
8.129065
11.456095
0.709584
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_sensitivity(T, k, j, right=right)
def eigenvector_sensitivity(T, k, j, right=True)
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...
6.060354
8.30965
0.729315
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_sensitivity(T, j)
def stationary_distribution_sensitivity(T, j)
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...
7.69609
11.071156
0.695148
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: return dense.sensitivity.mfpt_sen...
def mfpt_sensitivity(T, target, i)
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 :...
7.001595
7.803712
0.897213
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(T.todense(), A, B, i, forward) else: if ...
def committor_sensitivity(T, A, B, i, forward=True)
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...
3.898312
3.909556
0.997124
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_sensitivity(T.toarray(), a) else: ...
def expectation_sensitivity(T, a)
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...
6.496305
7.418376
0.875704
A = A.tocsr() B = B.tocsr() same_shape = (A.shape == B.shape) if same_shape: diff = (A - B).data same_data = np.allclose(diff, 0.0, rtol=rtol, atol=atol) return same_data else: return False
def allclose_sparse(A, B, rtol=1e-5, atol=1e-8)
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...
2.522225
2.980253
0.846312
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) Z = -alpha[:, :, np.newaxis] * alpha[:, np.newaxis, :] ind = np.diag_indices(C.shape[0]) Z[...
def tmatrix_cov(C, row=None)
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_...
4.817919
4.9256
0.978139
r alpha0 = alpha.sum() norm = alpha0 ** 2 * (alpha0 + 1.0) Z = -alpha[:, np.newaxis] * alpha[np.newaxis, :] ind = np.diag_indices(Z.shape[0]) Z[ind] += alpha0 * alpha cov = Z / norm return cov
def dirichlet_covariance(alpha)
r"""Covariance matrix for Dirichlet distribution. Parameters ---------- alpha : (M, ) ndarray Parameters of Dirichlet distribution Returns ------- cov : (M, M) ndarray Covariance matrix
6.382432
6.371005
1.001794
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()
def error_perturbation_single(C, S, R=None)
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...
7.23963
8.782099
0.824362
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()
def error_perturbation_var(C, S)
r"""Error-perturbation arising from a given sensitivity Parameters ---------- C : (M, M) ndarray Count matrix S : (K, M, M) ndarray Sensitivity tensor
6.266271
6.708465
0.934084
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
def error_perturbation_cov(C, S)
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
3.37724
3.356699
1.00612
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")
def error_perturbation(C, S)
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,...
3.509578
3.118868
1.125273
r dim = T.shape[0] A = eye(dim, dim) - T A = A.todok() D = A.diagonal() A[target, :] = 0.0 D[target] = 1.0 A.setdiag(D) A = A.tocsr() b = np.ones(dim) b[target] = 0.0 m_t = spsolve(A, b) return m_t
def mfpt(T, target)
r"""Mean first passage times to a set of target states. Parameters ---------- T : scipy.sparse matrix Transition matrix. target : int or list of int Target states for mfpt calculation. Returns ------- m_t : ndarray, shape=(n,) Vector of mean first passage times to ...
4.591568
4.679596
0.981189
if mu is None: mu = stationary_distribution(T) nuX = mu[origin] muX = nuX / np.sum(nuX) tY = mfpt(T, target) tXY = np.dot(muX, tY[origin]) return tXY
def mfpt_between_sets(T, target, origin, mu=None)
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...
6.026936
7.630431
0.789855
r if issparse(A) : return A.dot(B) elif issparse(B): return (B.T.dot(A.T)).T else: return np.dot(A, B)
def mydot(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
3.576998
3.927752
0.910699
if not issparse(A): A = csr_matrix(A) H = DPhival + mydot(G.T, mydot(SIG, G)) J = bmat([[H, A.T], [A, None]]) else: if issparse(A): A = A.toarray() J = np.zeros((N+P, N+P)) J[0:N, 0:N] = DPhival + mydot(G.T, mydot(SIG, G)) ...
def solve_full(z, Fval, DPhival, G, A): M, N=G.shape P, N=A.shape m=M x=z[0:N] nu=z[N:N+P] l=z[N+P:N+P+M] s=z[N+P+M:] rd = Fval[0:N] rp1 = Fval[N:N+P] rp2 = Fval[N+P:N+P+M] rc = Fval[N+P+M:] SIG = np.diag(l...
Total number of inequality constraints
3.267362
3.250723
1.005119
if not issparse(A): A = csr_matrix(A) H = DPhival + mydot(G.T, mydot(SIG, G)) J = bmat([[H, A.T], [A, None]]) else: if issparse(A): A = A.toarray() J = np.zeros((N+P, N+P)) J[0:N, 0:N] = DPhival + mydot(G.T, mydot(SIG, G)) ...
def factor_aug(z, DPhival, G, A): M, N = G.shape P, N = A.shape l = z[N+P:N+P+M] s = z[N+P+M:] SIG = diags(l/s, 0) if issparse(DPhival)
Multiplier for inequality constraints
3.24451
3.195395
1.015371
M, N=G.shape P, N=A.shape m = M x = z[0:N] nu = z[N:N+P] l = z[N+P:N+P+M] s = z[N+P+M:] rd = Fval[0:N] rp1 = Fval[N:N+P] rp2 = Fval[N+P:N+P+M] rc = Fval[N+P+M:] SIG = diags(l/s, 0) b1 = -rd - mydot(G....
def solve_factorized_aug(z, Fval, LU, G, A)
Total number of inequality constraints
4.731546
4.644999
1.018632
M, N = G.shape P, N = A.shape l = z[N+P:N+P+M] s = z[N+P+M:] SIG = diags(l/s, 0) H = DPhival + mydot(G.T, mydot(SIG, G)) LU_H = myfactor(H) HinvAt = mysolve(LU_H, A.T) S = mydot(A, HinvAt) LU_S = myfactor(S) LU = (LU_S, LU_H) ...
def factor_schur(z, DPhival, G, A)
Multiplier for inequality constraints
6.805704
6.855244
0.992773
M, N=G.shape P, N=A.shape m = M x = z[0:N] nu = z[N:N+P] l = z[N+P:N+P+M] s = z[N+P+M:] rd = Fval[0:N] rp1 = Fval[N:N+P] rp2 = Fval[N+P:N+P+M] rc = Fval[N+P+M:] SIG = diags(l/s, 0) r1 = rd + mydot(G.T...
def solve_factorized_schur(z, Fval, LU, G, A)
Total number of inequality constraints
5.215648
5.129455
1.016804
r if (N <= 0): EC = coo_matrix(T.shape, dtype=float) return EC else: p_k = 1.0 * p0 p_sum = 1.0 * p_k Tt = T.transpose() for k in np.arange(N - 1): p_k = Tt.dot(p_k) p_sum += p_k ...
def expected_counts(p0, T, N)
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...
4.464447
4.428122
1.008203
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
def expected_counts_stationary(T, n, mu=None)
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...
4.954811
4.034285
1.228176
r return fingerprint(P, obs1, obs2=obs2, tau=tau, k=k, ncv=ncv)
def fingerprint_correlation(P, obs1, obs2=None, tau=1, k=None, ncv=None)
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...
3.592807
7.047681
0.509786
r one_vec = np.ones(P.shape[0]) return fingerprint(P, one_vec, obs2=obs, p0=p0, tau=tau, k=k, ncv=ncv)
def fingerprint_relaxation(P, p0, obs, tau=1, k=None, ncv=None)
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...
4.991208
6.126942
0.814633
r if obs2 is None: obs2 = obs1 R, D, L = rdl_decomposition(P, k=k, ncv=ncv) mu = L[0, :] w = np.diagonal(D) timescales = timescales_from_eigenvalues(w, tau) if p0 is None: amplitudes = np.dot(mu * obs1, R) * np.dot(L, obs2) else: a...
def fingerprint(P, obs1, obs2=None, p0=None, tau=1, k=None, ncv=None)
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...
4.708606
4.748168
0.991668
r if obs2 is None: obs2 = obs1 mu = statdist(P) obs1mu = mu * obs1 times = np.asarray(times) 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) c...
def correlation_matvec(P, obs1, obs2=None, times=[1])
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...
3.133116
3.134704
0.999493
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)
def relaxation(P, p0, obs, times=[1], k=None, ncv=None)
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...
3.622374
4.097029
0.884147
r R, D, L = rdl_decomposition(P, k=k, ncv=ncv) ev = np.diagonal(D) amplitudes = np.dot(p0, R) * np.dot(L, obs) times = np.asarray(times) ev_t = ev[np.newaxis, :] ** times[:, np.newaxis] res = np.dot(ev_t, amplitudes) res = res.real return res
def relaxation_decomp(P, p0, obs, times=[1], k=None, ncv=None)
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...
5.25142
6.490842
0.809051
r times = np.asarray(times) 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.zeros(nt) obs_t = 1.0 * obs obs_t = propagate(P, obs_t, times[...
def relaxation_matvec(P, p0, obs, times=[1])
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...
2.925675
3.149775
0.928852
r y = 1.0 * x for i in range(N): y = A.dot(y) return y
def propagate(A, x, N)
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 ...
5.30171
6.776749
0.782338
return np.fromiter((map(lambda x: len(x), X)), dtype=int).max()
def _maxlength(X)
Returns the maximum length of signal trajectories X
4.798473
4.135561
1.160296
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 alias in method._aliases - ...
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...
3.470682
3.606305
0.962393
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 'decorator' in filename or __file__...
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.166193
4.091311
1.018303
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__.__name__)) return func(*args, **kw)
def estimation_required(func, *args, **kw)
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...
3.324072
3.271367
1.016111
sampler = MarkovChainSampler(P, dt=dt) return sampler.trajectory(N, start=start, stop=stop)
def generate_traj(P, N, start=None, stop=None, dt=1)
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 ...
4.237319
6.12781
0.69149
sampler = MarkovChainSampler(P, dt=dt) return sampler.trajectories(M, N, start=start, stop=stop)
def generate_trajs(P, M, N, start=None, stop=None, dt=1)
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...
3.895491
5.480782
0.710755
r # check input if (d <= 0 or d > 1): raise ValueError('Diffusivity must be in (0,1]. Trying to set the invalid value', str(d)) # init n = len(E) P = np.zeros((n, n)) # set offdiagonals P[0, 1] = 0.5 * d * min(1.0, math.exp(-(E[1] - E[0]))) for i in range(1, n - 1): P...
def transition_matrix_metropolis_1d(E, d=1.0)
r"""Transition matrix describing the Metropolis chain jumping between neighbors in a discrete 1D energy landscape. Parameters ---------- E : (M,) ndarray Energies in units of kT d : float (optional) Diffusivity of the chain, d in (0, 1] Returns ------- P : (M, M) ndarra...
2.343598
2.069542
1.132424
# 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 as msmana from scipy.stats impor...
def trajectory(self, N, start=None, stop=None)
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...
4.803268
4.25649
1.128458
trajs = [self.trajectory(N, start=start, stop=stop) for _ in range(M)] return trajs
def trajectories(self, M, N, start=None, stop=None)
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...
3.532361
5.018711
0.703838
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) res_seqs.append(np.array(sall[i])) return res_st...
def _split_sequences_singletraj(dtraj, nstates, lag)
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
2.142581
2.315532
0.925308
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]) return res
def _split_sequences_multitraj(dtrajs, lag)
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
2.557919
2.792362
0.916041
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
def _indicator_multitraj(ss, i, j)
Returns conditional sequence for transition i -> j given all conditional sequences
3.454105
3.237542
1.066891
r # count matrix if C is None: C = count_matrix_coo2_mult(dtrajs, lag, sliding=True, sparse=True) if callback is not None: if not callable(callback): raise ValueError('Provided callback is not callable') # split sequences splitseq = _split_sequences_multitraj(dtrajs, ...
def statistical_inefficiencies(dtrajs, lag, C=None, truncate_acf=True, mact=2.0, n_jobs=1, callback=None)
r""" Computes statistical inefficiencies of sliding-window transition counts at given lag Consider a discrete trajectory :math`{ x_t }` with :math:`x_t \in {1, ..., n}`. For each starting state :math:`i`, we collect the target sequence .. mathh: Y^(i) = {x_{t+\tau} | x_{t}=i} which contains t...
4.148458
4.267267
0.972158
r # observed C C = count_matrix_coo2_mult(dtrajs, lag, sliding=True, sparse=True) # statistical inefficiencies si = statistical_inefficiencies(dtrajs, lag, C=C, truncate_acf=truncate_acf, mact=mact, n_jobs=n_jobs, callback=callback) # effective element-wise co...
def effective_count_matrix(dtrajs, lag, average='row', truncate_acf=True, mact=1.0, n_jobs=1, callback=None)
r""" Computes the statistically effective transition count matrix Given a list of discrete trajectories, compute the effective number of statistically uncorrelated transition counts at the given lag time. First computes the full sliding-window counts :math:`c_{ij}(tau)`. Then uses :func:`statistical_ineffi...
4.289425
4.117918
1.041649
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.") return np.divide(C, rowsums[:, np...
def transition_matrix_non_reversible(C)
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
4.653471
5.043878
0.922598
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 X = X.T + X # result T_rev = X / X.sum(axis=1)[:, None] if re...
def transition_matrix_reversible_pisym(C, return_statdist=False, **kwargs)
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...
3.995696
3.411335
1.1713
r T = A - mu * np.eye(A.shape[0]) lupiv = lu_factor(T) r0 = 1.0 / np.linalg.norm(x0) y0 = x0 * r0 y = 1.0 * y0 r = 1.0 * r0 for i in range(maxiter): x = lu_solve(lupiv, y) r = 1.0 / np.linalg.norm(x) y = x * r if r <= tol: return...
def backward_iteration(A, mu, x0, tol=1e-14, maxiter=100)
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 ...
3.351771
3.657177
0.916491
r val, L = eig(T, left=True, right=False) perm = np.argsort(val)[::-1] val = val[perm] L = L[:, perm] nu = np.abs(L[:, 0]) mu = nu / np.sum(nu) return mu
def stationary_distribution_from_eigenvector(T)
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...
4.974628
6.275636
0.792689
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_inds] = d_times P_time = np.dot(np.dot(R, D_time), L) # multiply element-wise...
def time_correlation_by_diagonalization(P, pi, obs1, obs2=None, time=1, rdl=None)
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.
4.164502
3.92273
1.061633
r # input checks if not (type(time) == int): if not (type(time) == np.int64): raise TypeError("given time (%s) is not an integer, but has type: %s" % (str(time), type(time))) if obs1.shape[0] != P.shape[0]: raise ValueError("observable shape not co...
def time_correlation_direct_by_mtx_vec_prod(P, mu, obs1, obs2=None, time=1, start_values=None, return_P_k_obs=False)
r"""Compute time-correlation 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 : ndarr...
4.943742
4.383541
1.127796
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, L = rdl_decomposition(P) # discard imaginary part, if al...
def time_correlations_direct(P, pi, obs1, obs2=None, times=[1])
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...
3.892434
3.79626
1.025334
r # input checks if not type(time) == int: if not type(time) == np.int64: raise TypeError("given time (%s) is not an integer, but has type: %s" % (str(time), type(time))) if obs.shape[0] != P.shape[0]: raise ValueError("observable shape not compati...
def time_relaxation_direct_by_mtx_vec_prod(P, p0, obs, time=1, start_values=None, return_pP_k=False)
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...
3.970564
3.805611
1.043345
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.any(np.iscomplex(R)): R = np.real(R) ...
def time_relaxations_direct(P, p0, obs, times=[1])
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...
3.451066
3.634138
0.949624
r M, N = G.shape P, N = A.shape l = z[N+P:N+P+M] s = z[N+P+M:] SIG = diags(l/s, 0) # SIG = diags(l*s, 0) if not issparse(A): A = csr_matrix(A) if not issparse(G): G = csr_matrix(G) sign = np.zeros(N) sign[0:N//2] = 1.0 si...
def factor_aug(z, DPhival, G, A)
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...
4.46133
4.145351
1.076225
M, N=G.shape P, N=A.shape m=M x=z[0:N] nu=z[N:N+P] l=z[N+P:N+P+M] s=z[N+P+M:] rd = Fval[0:N] rp1 = Fval[N:N+P] rp2 = Fval[N+P:N+P+M] rc = Fval[N+P+M:] SIG = diags(l/s, 0) W = LU b1 = -rd - mydot(...
def solve_factorized_aug(z, Fval, LU, G, A)
Total number of inequality constraints
4.52806
4.438535
1.02017
r return list(set(range(self.nstates)) - set(self._A) - set(self._B))
def I(self)
r"""Returns the set of intermediate states
11.943036
9.005345
1.326216
r return tptapi.pathways(self.net_flux, self.A, self.B, fraction=fraction, maxiter=maxiter)
def pathways(self, fraction=1.0, maxiter=1000)
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 ---...
12.455184
13.498417
0.922714
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] for t in range(len(p) - 1): F[p[t], p[...
def _pathways_to_flux(self, paths, pathfluxes, n=None)
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...
2.588893
2.886364
0.896939
r (paths, pathfluxes) = self.pathways(fraction=fraction) return self._pathways_to_flux(paths, pathfluxes, n=self.nstates)
def major_flux(self, fraction=0.9)
r"""Returns the main pathway part of the net flux comprising at most the requested fraction of the full flux.
12.048782
12.323156
0.977735
r # set-ify everything setA = set(self.A) setB = set(self.B) setI = set(self.I) raw_sets = [set(user_set) for user_set in user_sets] # anything missing? Compute all listed states set_all = set(range(self.nstates)) set_all_user = [] for use...
def _compute_coarse_sets(self, user_sets)
r"""Computes the sets to coarse-grain the tpt flux to. Parameters ---------- (tpt_sets, A, B) with tpt_sets : list of int-iterables sets of states that shall be distinguished in the coarse-grained flux. A : int-iterable set indexes...
2.624464
2.485075
1.05609
r # coarse-grain sets (tpt_sets, Aindexes, Bindexes) = self._compute_coarse_sets(user_sets) nnew = len(tpt_sets) # coarse-grain fluxHere we should branch between sparse and dense implementations, but currently there is only a F_coarse = tptapi.coarsegrain(self._gross_flu...
def coarse_grain(self, user_sets)
r"""Coarse-grains the flux onto user-defined sets. Parameters ---------- user_sets : list of int-iterables sets of states that shall be distinguished in the coarse-grained flux. Returns ------- (sets, tpt) : (list of int-iterables, tpt-object) se...
4.683279
4.079592
1.147977
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
def transition_matrix(self)
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.
3.515464
3.404481
1.032599
P = diags([self.q[1:], self.r, self.p[0:-1]], [-1, 0, 1]) return P
def transition_matrix_sparse(self)
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.
7.006545
8.457153
0.828476
r u = np.zeros(self.dim) g = np.zeros(self.dim - 1) g[0] = 1.0 g[1:] = np.cumprod(self.q[1:-1] / self.p[1:-1]) if a == b: return u elif a < b: u[0:a + 1] = 0.0 u[b:] = 1.0 ...
def committor_forward(self, a, b)
r"""Forward committor for birth-and-death-chain. The forward committor is the probability to hit state b before hitting state a starting in state x, u_x=P_x(T_b<T_a) T_i is the first arrival time of the chain to state i, T_i = inf( t>0 | X_t=i ) Parameters ...
2.583999
2.752965
0.938624
r # if b<=a: # raise ValueError("State index b has to be strictly larger than state index a") qminus = self.committor_backward(a, b) qplus = self.committor_forward(a, b) P = self.transition_matrix() pi = self.stationary_distribution() flux = pi[:, np.newa...
def flux(self, a, b)
r"""The flux network for the reaction from A=[0,...,a] => B=[b,...,M]. Parameters ---------- a : int State index b : int State index Returns ------- flux : (M, M) ndarray Matrix of flux values between pairs of states.
4.68935
4.497097
1.04275
r flux = self.flux(a, b) netflux = flux - np.transpose(flux) ind = (netflux < 0.0) netflux[ind] = 0.0 return netflux
def netflux(self, a, b)
r"""The netflux network for the reaction from A=[0,...,a] => B=[b,...,M]. Parameters ---------- a : int State index b : int State index Returns ------- netflux : (M, M) ndarray Matrix of flux values between pairs of st...
4.023638
5.273676
0.762966
r flux = self.flux(a, b) A = list(range(a + 1)) notA = list(range(a + 1, flux.shape[0])) F = flux[A, :][:, notA].sum() return F
def totalflux(self, a, b)
r"""The tiotal flux for the reaction A=[0,...,a] => B=[b,...,M]. Parameters ---------- a : int State index b : int State index Returns ------- F : float The total flux between reactant and product
5.668203
5.909083
0.959236
if not scipy.sparse.issparse(C): C = scipy.sparse.csr_matrix(C) rowsum = C.tocsr().sum(axis=1) # catch div by zero if np.min(rowsum) == 0.0: raise ValueError("matrix C contains rows with sum zero.") rowsum = np.array(1. / rowsum).flatten() norm = scipy.sparse.diags(rowsum, 0...
def transition_matrix_non_reversible(C)
implementation of transition_matrix
3.565128
3.558797
1.001779
r row_sums = T.sum(axis=1).A1 max_sum = np.max(row_sums) if max_sum == 0.0: max_sum = 1.0 return (T + scipy.sparse.diags(-row_sums+max_sum, 0)) / max_sum
def correct_transition_matrix(T, reversible=None)
r"""Normalize transition matrix Fixes a the row normalization of a transition matrix. To be used with the reversible estimators to fix an almost coverged transition matrix. Parameters ---------- T : (M, M) ndarray matrix to correct reversible : boolean for future use R...
3.802726
4.261889
0.892263
r # nonreversible estimate T_nonrev = transition_matrix_non_reversible(C) from msmtools.analysis import stationary_distribution pi = stationary_distribution(T_nonrev) # correlation matrix X = scipy.sparse.diags(pi).dot(T_nonrev) X = X.T + X # result pi_rev = np.array(X.sum(axis=1...
def transition_matrix_reversible_pisym(C, return_statdist=False, **kwargs)
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...
3.686382
3.233155
1.140181
r pi = statdist(P) return np.dot(pi, obs)
def expectation(P, obs)
r"""Equilibrium expectation of given observable. Parameters ---------- P : (M, M) ndarray Transition matrix obs : (M,) ndarray Observable, represented as vector on state space Returns ------- x : float Expectation value
20.897324
43.655468
0.478687
r M = P.shape[0] T = np.asarray(times).max() if T < M: return correlation_matvec(P, obs1, obs2=obs2, times=times) else: return correlation_decomp(P, obs1, obs2=obs2, times=times, k=k)
def correlation(P, obs1, obs2=None, times=[1], k=None)
r"""Time-correlation for equilibrium experiment. 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-correlations times : list of int (...
3.664452
3.931873
0.931986
r if obs2 is None: obs2 = obs1 R, D, L = rdl_decomposition(P, k=k) mu = L[0, :] ev = np.diagonal(D) amplitudes = np.dot(mu * obs1, R) * np.dot(L, obs2) times = np.asarray(times) ev_t = ev[np.newaxis, :] ** times[:, np.newaxis] res = np.dot(ev_t, ampli...
def correlation_decomp(P, obs1, obs2=None, times=[1], k=None)
r"""Time-correlation for equilibrium experiment - via decomposition. 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-correlations t...
5.744756
6.01705
0.954746
C = C.tocsr() T = T.tocsr() ind = scipy.nonzero(C) relT = np.array(T[ind])[0, :] relT = np.log(relT) relC = np.array(C[ind])[0, :] return relT.dot(relC)
def log_likelihood(C, T)
implementation of likelihood of C given T
4.062374
4.053676
1.002146
r dim = T.shape[0] A = np.eye(dim) - T A[target, :] = 0.0 A[target, target] = 1.0 b = np.ones(dim) b[target] = 0.0 m_t = solve(A, b) return m_t
def mfpt(T, target)
r"""Mean first passage times to a set of target states. Parameters ---------- T : ndarray, shape=(n,n) Transition matrix. target : int or list of int Target states for mfpt calculation. Returns ------- m_t : ndarray, shape=(n,) Vector of mean first passage times to...
3.578835
3.792056
0.943772
r X = set(range(T.shape[0])) A = set(A) B = set(B) AB = A.intersection(B) notAB = X.difference(A).difference(B) if len(AB) > 0: raise ValueError("Sets A and B have to be disjoint") L = T - eye(T.shape[0], T.shape[0]) W = 1.0 * L W = W.todok() W[list(A...
def forward_committor(T, A, B)
r"""Forward committor between given sets. The forward committor u(x) between sets A and B is the probability for the chain starting in x to reach B before reaching A. Parameters ---------- T : (M, M) scipy.sparse matrix Transition matrix A : array_like List of integer state lab...
2.989358
2.980074
1.003115
r X = set(range(T.shape[0])) A = set(A) B = set(B) AB = A.intersection(B) notAB = X.difference(A).difference(B) if len(AB) > 0: raise ValueError("Sets A and B have to be disjoint") pi = stationary_distribution(T) L = T - eye(T.shape[0], T.shape[0]) D = diags([pi, ], [0, ]...
def backward_committor(T, A, B)
r"""Backward committor between given sets. The backward committor u(x) between sets A and B is the probability for the chain starting in x to have come from A last rather than from B. Parameters ---------- T : (M, M) ndarray Transition matrix A : array_like List of integer ...
3.214788
3.173473
1.013019
slack = Slacker(token) slack.files.upload(file_name, channels=channel_name)
def upload_file(token, channel_name, file_name)
upload file to a channel
3.957959
3.997883
0.990014
''' priority of token 1) as argumment: -t 2) as environ variable priority of as_user 1) as argument: -a 2) as environ variable ''' arg_token = args.token arg_as_user = args.as_user slack_token_var_name = 'SLACK_TOKEN' if slack_token_var_name in ...
def args_priority(args, environ)
priority of token 1) as argumment: -t 2) as environ variable priority of as_user 1) as argument: -a 2) as environ variable
3.459132
2.138249
1.617741
global _context if _context is not None: raise AssertionError( 'This function must only be called ' 'once in an application lifetime') platform.set_up() vm = platform.create_vm() vm.set_up() _context = vm.create_context() _context.set_up() atexit.re...
def set_up()
Set ups the V8 machinery:\ platform, VM and context. This function is not thread-safe,\ it must be called from a place\ where is guaranteed it will be\ called once and only once.\ Probably within the main-thread\ at import time.
4.477072
3.500212
1.279086