repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
markovmodel/PyEMMA
pyemma/util/debug.py
unregister_signal_handlers
def unregister_signal_handlers(): """ set signal handlers to default """ signal.signal(SIGNAL_STACKTRACE, signal.SIG_IGN) signal.signal(SIGNAL_PDB, signal.SIG_IGN)
python
def unregister_signal_handlers(): """ set signal handlers to default """ signal.signal(SIGNAL_STACKTRACE, signal.SIG_IGN) signal.signal(SIGNAL_PDB, signal.SIG_IGN)
[ "def", "unregister_signal_handlers", "(", ")", ":", "signal", ".", "signal", "(", "SIGNAL_STACKTRACE", ",", "signal", ".", "SIG_IGN", ")", "signal", ".", "signal", "(", "SIGNAL_PDB", ",", "signal", ".", "SIG_IGN", ")" ]
set signal handlers to default
[ "set", "signal", "handlers", "to", "default" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/debug.py#L93-L96
train
204,100
markovmodel/PyEMMA
pyemma/coordinates/transform/nystroem_tica.py
selection_strategy
def selection_strategy(oasis_obj, strategy='spectral-oasis', nsel=1, neig=None): """ Factory for selection strategy object Returns ------- selstr : SelectionStrategy Selection strategy object """ strategy = strategy.lower() if strategy == 'random': return SelectionStrategyRandom(oasis_obj, strategy, nsel=nsel, neig=neig) elif strategy == 'oasis': return SelectionStrategyOasis(oasis_obj, strategy, nsel=nsel, neig=neig) elif strategy == 'spectral-oasis': return SelectionStrategySpectralOasis(oasis_obj, strategy, nsel=nsel, neig=neig) else: raise ValueError('Selected strategy is unknown: '+str(strategy))
python
def selection_strategy(oasis_obj, strategy='spectral-oasis', nsel=1, neig=None): """ Factory for selection strategy object Returns ------- selstr : SelectionStrategy Selection strategy object """ strategy = strategy.lower() if strategy == 'random': return SelectionStrategyRandom(oasis_obj, strategy, nsel=nsel, neig=neig) elif strategy == 'oasis': return SelectionStrategyOasis(oasis_obj, strategy, nsel=nsel, neig=neig) elif strategy == 'spectral-oasis': return SelectionStrategySpectralOasis(oasis_obj, strategy, nsel=nsel, neig=neig) else: raise ValueError('Selected strategy is unknown: '+str(strategy))
[ "def", "selection_strategy", "(", "oasis_obj", ",", "strategy", "=", "'spectral-oasis'", ",", "nsel", "=", "1", ",", "neig", "=", "None", ")", ":", "strategy", "=", "strategy", ".", "lower", "(", ")", "if", "strategy", "==", "'random'", ":", "return", "S...
Factory for selection strategy object Returns ------- selstr : SelectionStrategy Selection strategy object
[ "Factory", "for", "selection", "strategy", "object" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/nystroem_tica.py#L769-L786
train
204,101
markovmodel/PyEMMA
pyemma/coordinates/transform/nystroem_tica.py
oASIS_Nystroem._compute_error
def _compute_error(self): """ Evaluate the absolute error of the Nystroem approximation for each column """ # err_i = sum_j R_{k,ij} A_{k,ji} - d_i self._err = np.sum(np.multiply(self._R_k, self._C_k.T), axis=0) - self._d
python
def _compute_error(self): """ Evaluate the absolute error of the Nystroem approximation for each column """ # err_i = sum_j R_{k,ij} A_{k,ji} - d_i self._err = np.sum(np.multiply(self._R_k, self._C_k.T), axis=0) - self._d
[ "def", "_compute_error", "(", "self", ")", ":", "# err_i = sum_j R_{k,ij} A_{k,ji} - d_i", "self", ".", "_err", "=", "np", ".", "sum", "(", "np", ".", "multiply", "(", "self", ".", "_R_k", ",", "self", ".", "_C_k", ".", "T", ")", ",", "axis", "=", "0",...
Evaluate the absolute error of the Nystroem approximation for each column
[ "Evaluate", "the", "absolute", "error", "of", "the", "Nystroem", "approximation", "for", "each", "column" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/nystroem_tica.py#L411-L414
train
204,102
markovmodel/PyEMMA
pyemma/coordinates/transform/nystroem_tica.py
oASIS_Nystroem.set_selection_strategy
def set_selection_strategy(self, strategy='spectral-oasis', nsel=1, neig=None): """ Defines the column selection strategy Parameters ---------- strategy : str One of the following strategies to select new columns: random : randomly choose from non-selected columns oasis : maximal approximation error in the diagonal of :math:`A` spectral-oasis : selects the nsel columns that are most distanced in the oASIS-error-scaled dominant eigenspace nsel : int number of columns to be selected in each round neig : int or None, optional, default None Number of eigenvalues to be optimized by the selection process. If None, use the whole available eigenspace """ self._selection_strategy = selection_strategy(self, strategy, nsel, neig)
python
def set_selection_strategy(self, strategy='spectral-oasis', nsel=1, neig=None): """ Defines the column selection strategy Parameters ---------- strategy : str One of the following strategies to select new columns: random : randomly choose from non-selected columns oasis : maximal approximation error in the diagonal of :math:`A` spectral-oasis : selects the nsel columns that are most distanced in the oASIS-error-scaled dominant eigenspace nsel : int number of columns to be selected in each round neig : int or None, optional, default None Number of eigenvalues to be optimized by the selection process. If None, use the whole available eigenspace """ self._selection_strategy = selection_strategy(self, strategy, nsel, neig)
[ "def", "set_selection_strategy", "(", "self", ",", "strategy", "=", "'spectral-oasis'", ",", "nsel", "=", "1", ",", "neig", "=", "None", ")", ":", "self", ".", "_selection_strategy", "=", "selection_strategy", "(", "self", ",", "strategy", ",", "nsel", ",", ...
Defines the column selection strategy Parameters ---------- strategy : str One of the following strategies to select new columns: random : randomly choose from non-selected columns oasis : maximal approximation error in the diagonal of :math:`A` spectral-oasis : selects the nsel columns that are most distanced in the oASIS-error-scaled dominant eigenspace nsel : int number of columns to be selected in each round neig : int or None, optional, default None Number of eigenvalues to be optimized by the selection process. If None, use the whole available eigenspace
[ "Defines", "the", "column", "selection", "strategy" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/nystroem_tica.py#L421-L438
train
204,103
markovmodel/PyEMMA
pyemma/coordinates/transform/nystroem_tica.py
oASIS_Nystroem.update_inverse
def update_inverse(self): """ Recomputes W_k_inv and R_k given the current column selection When computed, the block matrix inverse W_k_inv will be updated. This is useful when you want to compute eigenvalues or get an approximation for the full matrix or individual columns. Calling this function is not strictly necessary, but then you rely on the fact that the updates did not accumulate large errors. That depends very much on how columns were added. Adding columns with very small Schur complement causes accumulation of errors and is more likely to make it necessary to update the inverse. """ # compute R_k and W_k_inv Wk = self._C_k[self._columns, :] self._W_k_inv = np.linalg.pinv(Wk) self._R_k = np.dot(self._W_k_inv, self._C_k.T)
python
def update_inverse(self): """ Recomputes W_k_inv and R_k given the current column selection When computed, the block matrix inverse W_k_inv will be updated. This is useful when you want to compute eigenvalues or get an approximation for the full matrix or individual columns. Calling this function is not strictly necessary, but then you rely on the fact that the updates did not accumulate large errors. That depends very much on how columns were added. Adding columns with very small Schur complement causes accumulation of errors and is more likely to make it necessary to update the inverse. """ # compute R_k and W_k_inv Wk = self._C_k[self._columns, :] self._W_k_inv = np.linalg.pinv(Wk) self._R_k = np.dot(self._W_k_inv, self._C_k.T)
[ "def", "update_inverse", "(", "self", ")", ":", "# compute R_k and W_k_inv", "Wk", "=", "self", ".", "_C_k", "[", "self", ".", "_columns", ",", ":", "]", "self", ".", "_W_k_inv", "=", "np", ".", "linalg", ".", "pinv", "(", "Wk", ")", "self", ".", "_R...
Recomputes W_k_inv and R_k given the current column selection When computed, the block matrix inverse W_k_inv will be updated. This is useful when you want to compute eigenvalues or get an approximation for the full matrix or individual columns. Calling this function is not strictly necessary, but then you rely on the fact that the updates did not accumulate large errors. That depends very much on how columns were added. Adding columns with very small Schur complement causes accumulation of errors and is more likely to make it necessary to update the inverse.
[ "Recomputes", "W_k_inv", "and", "R_k", "given", "the", "current", "column", "selection" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/nystroem_tica.py#L451-L464
train
204,104
markovmodel/PyEMMA
pyemma/coordinates/transform/nystroem_tica.py
oASIS_Nystroem.approximate_cholesky
def approximate_cholesky(self, epsilon=1e-6): r""" Compute low-rank approximation to the Cholesky decomposition of target matrix. The decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float, optional, default 1e-6 Cutoff for eigenvalue norms. If negative eigenvalues occur, with norms larger than epsilon, the largest negative eigenvalue norm will be used instead of epsilon, i.e. a band including all negative eigenvalues will be cut off. Returns ------- L : ndarray((n,m), dtype=float) Cholesky matrix such that `A \approx L L^{\top}`. Number of columns :math:`m` is most at the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon. """ # compute the Eigenvalues of C0 using Schur factorization Wk = self._C_k[self._columns, :] L0 = spd_inv_split(Wk, epsilon=epsilon) L = np.dot(self._C_k, L0) return L
python
def approximate_cholesky(self, epsilon=1e-6): r""" Compute low-rank approximation to the Cholesky decomposition of target matrix. The decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float, optional, default 1e-6 Cutoff for eigenvalue norms. If negative eigenvalues occur, with norms larger than epsilon, the largest negative eigenvalue norm will be used instead of epsilon, i.e. a band including all negative eigenvalues will be cut off. Returns ------- L : ndarray((n,m), dtype=float) Cholesky matrix such that `A \approx L L^{\top}`. Number of columns :math:`m` is most at the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon. """ # compute the Eigenvalues of C0 using Schur factorization Wk = self._C_k[self._columns, :] L0 = spd_inv_split(Wk, epsilon=epsilon) L = np.dot(self._C_k, L0) return L
[ "def", "approximate_cholesky", "(", "self", ",", "epsilon", "=", "1e-6", ")", ":", "# compute the Eigenvalues of C0 using Schur factorization", "Wk", "=", "self", ".", "_C_k", "[", "self", ".", "_columns", ",", ":", "]", "L0", "=", "spd_inv_split", "(", "Wk", ...
r""" Compute low-rank approximation to the Cholesky decomposition of target matrix. The decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float, optional, default 1e-6 Cutoff for eigenvalue norms. If negative eigenvalues occur, with norms larger than epsilon, the largest negative eigenvalue norm will be used instead of epsilon, i.e. a band including all negative eigenvalues will be cut off. Returns ------- L : ndarray((n,m), dtype=float) Cholesky matrix such that `A \approx L L^{\top}`. Number of columns :math:`m` is most at the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon.
[ "r", "Compute", "low", "-", "rank", "approximation", "to", "the", "Cholesky", "decomposition", "of", "target", "matrix", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/nystroem_tica.py#L578-L602
train
204,105
markovmodel/PyEMMA
pyemma/coordinates/transform/nystroem_tica.py
oASIS_Nystroem.approximate_eig
def approximate_eig(self, epsilon=1e-6): """ Compute low-rank approximation of the eigenvalue decomposition of target matrix. If spd is True, the decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float, optional, default 1e-6 Cutoff for eigenvalue norms. If negative eigenvalues occur, with norms larger than epsilon, the largest negative eigenvalue norm will be used instead of epsilon, i.e. a band including all negative eigenvalues will be cut off. Returns ------- s : ndarray((m,), dtype=float) approximated eigenvalues. Number of eigenvalues returned is at most the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon. W : ndarray((n,m), dtype=float) approximated eigenvectors in columns. Number of eigenvectors returned is at most the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon. """ L = self.approximate_cholesky(epsilon=epsilon) LL = np.dot(L.T, L) s, V = np.linalg.eigh(LL) # sort s, V = sort_by_norm(s, V) # back-transform eigenvectors Linv = np.linalg.pinv(L.T) V = np.dot(Linv, V) # normalize eigenvectors ncol = V.shape[1] for i in range(ncol): if not np.allclose(V[:, i], 0): V[:, i] /= np.sqrt(np.dot(V[:, i], V[:, i])) return s, V
python
def approximate_eig(self, epsilon=1e-6): """ Compute low-rank approximation of the eigenvalue decomposition of target matrix. If spd is True, the decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float, optional, default 1e-6 Cutoff for eigenvalue norms. If negative eigenvalues occur, with norms larger than epsilon, the largest negative eigenvalue norm will be used instead of epsilon, i.e. a band including all negative eigenvalues will be cut off. Returns ------- s : ndarray((m,), dtype=float) approximated eigenvalues. Number of eigenvalues returned is at most the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon. W : ndarray((n,m), dtype=float) approximated eigenvectors in columns. Number of eigenvectors returned is at most the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon. """ L = self.approximate_cholesky(epsilon=epsilon) LL = np.dot(L.T, L) s, V = np.linalg.eigh(LL) # sort s, V = sort_by_norm(s, V) # back-transform eigenvectors Linv = np.linalg.pinv(L.T) V = np.dot(Linv, V) # normalize eigenvectors ncol = V.shape[1] for i in range(ncol): if not np.allclose(V[:, i], 0): V[:, i] /= np.sqrt(np.dot(V[:, i], V[:, i])) return s, V
[ "def", "approximate_eig", "(", "self", ",", "epsilon", "=", "1e-6", ")", ":", "L", "=", "self", ".", "approximate_cholesky", "(", "epsilon", "=", "epsilon", ")", "LL", "=", "np", ".", "dot", "(", "L", ".", "T", ",", "L", ")", "s", ",", "V", "=", ...
Compute low-rank approximation of the eigenvalue decomposition of target matrix. If spd is True, the decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive. Parameters ---------- epsilon : float, optional, default 1e-6 Cutoff for eigenvalue norms. If negative eigenvalues occur, with norms larger than epsilon, the largest negative eigenvalue norm will be used instead of epsilon, i.e. a band including all negative eigenvalues will be cut off. Returns ------- s : ndarray((m,), dtype=float) approximated eigenvalues. Number of eigenvalues returned is at most the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon. W : ndarray((n,m), dtype=float) approximated eigenvectors in columns. Number of eigenvectors returned is at most the number of columns used in the Nystroem approximation, but may be smaller depending on epsilon.
[ "Compute", "low", "-", "rank", "approximation", "of", "the", "eigenvalue", "decomposition", "of", "target", "matrix", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/nystroem_tica.py#L604-L643
train
204,106
markovmodel/PyEMMA
pyemma/coordinates/transform/nystroem_tica.py
SelectionStrategy.select
def select(self): """ Selects next column indexes according to defined strategy Returns ------- cols : ndarray((nsel,), dtype=int) selected columns """ err = self._oasis_obj.error if np.allclose(err, 0): return None nsel = self._check_nsel() if nsel is None: return None return self._select(nsel, err)
python
def select(self): """ Selects next column indexes according to defined strategy Returns ------- cols : ndarray((nsel,), dtype=int) selected columns """ err = self._oasis_obj.error if np.allclose(err, 0): return None nsel = self._check_nsel() if nsel is None: return None return self._select(nsel, err)
[ "def", "select", "(", "self", ")", ":", "err", "=", "self", ".", "_oasis_obj", ".", "error", "if", "np", ".", "allclose", "(", "err", ",", "0", ")", ":", "return", "None", "nsel", "=", "self", ".", "_check_nsel", "(", ")", "if", "nsel", "is", "No...
Selects next column indexes according to defined strategy Returns ------- cols : ndarray((nsel,), dtype=int) selected columns
[ "Selects", "next", "column", "indexes", "according", "to", "defined", "strategy" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/nystroem_tica.py#L689-L704
train
204,107
markovmodel/PyEMMA
pyemma/_base/serialization/h5file.py
H5File.delete
def delete(self, name): """ deletes model with given name """ if name not in self._parent: raise KeyError('model "{}" not present'.format(name)) del self._parent[name] if self._current_model_group == name: self._current_model_group = None
python
def delete(self, name): """ deletes model with given name """ if name not in self._parent: raise KeyError('model "{}" not present'.format(name)) del self._parent[name] if self._current_model_group == name: self._current_model_group = None
[ "def", "delete", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "_parent", ":", "raise", "KeyError", "(", "'model \"{}\" not present'", ".", "format", "(", "name", ")", ")", "del", "self", ".", "_parent", "[", "name", "]", ...
deletes model with given name
[ "deletes", "model", "with", "given", "name" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/serialization/h5file.py#L57-L63
train
204,108
markovmodel/PyEMMA
pyemma/_base/serialization/h5file.py
H5File.select_model
def select_model(self, name): """ choose an existing model """ if name not in self._parent: raise KeyError('model "{}" not present'.format(name)) self._current_model_group = name
python
def select_model(self, name): """ choose an existing model """ if name not in self._parent: raise KeyError('model "{}" not present'.format(name)) self._current_model_group = name
[ "def", "select_model", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "_parent", ":", "raise", "KeyError", "(", "'model \"{}\" not present'", ".", "format", "(", "name", ")", ")", "self", ".", "_current_model_group", "=", "name...
choose an existing model
[ "choose", "an", "existing", "model" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/serialization/h5file.py#L65-L69
train
204,109
markovmodel/PyEMMA
pyemma/_base/serialization/h5file.py
H5File.models_descriptive
def models_descriptive(self): """ list all stored models in given file. Returns ------- dict: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...} """ f = self._parent return {name: {a: f[name].attrs[a] for a in H5File.stored_attributes} for name in f.keys()}
python
def models_descriptive(self): """ list all stored models in given file. Returns ------- dict: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...} """ f = self._parent return {name: {a: f[name].attrs[a] for a in H5File.stored_attributes} for name in f.keys()}
[ "def", "models_descriptive", "(", "self", ")", ":", "f", "=", "self", ".", "_parent", "return", "{", "name", ":", "{", "a", ":", "f", "[", "name", "]", ".", "attrs", "[", "a", "]", "for", "a", "in", "H5File", ".", "stored_attributes", "}", "for", ...
list all stored models in given file. Returns ------- dict: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...}
[ "list", "all", "stored", "models", "in", "given", "file", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/serialization/h5file.py#L181-L192
train
204,110
markovmodel/PyEMMA
pyemma/_base/progress/reporter/__init__.py
ProgressReporterMixin.show_progress
def show_progress(self): """ whether to show the progress of heavy calculations on this object. """ from pyemma import config # no value yet, obtain from config if not hasattr(self, "_show_progress"): val = config.show_progress_bars self._show_progress = val # config disabled progress? elif not config.show_progress_bars: return False return self._show_progress
python
def show_progress(self): """ whether to show the progress of heavy calculations on this object. """ from pyemma import config # no value yet, obtain from config if not hasattr(self, "_show_progress"): val = config.show_progress_bars self._show_progress = val # config disabled progress? elif not config.show_progress_bars: return False return self._show_progress
[ "def", "show_progress", "(", "self", ")", ":", "from", "pyemma", "import", "config", "# no value yet, obtain from config", "if", "not", "hasattr", "(", "self", ",", "\"_show_progress\"", ")", ":", "val", "=", "config", ".", "show_progress_bars", "self", ".", "_s...
whether to show the progress of heavy calculations on this object.
[ "whether", "to", "show", "the", "progress", "of", "heavy", "calculations", "on", "this", "object", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/progress/reporter/__init__.py#L45-L56
train
204,111
markovmodel/PyEMMA
pyemma/_base/progress/reporter/__init__.py
ProgressReporterMixin._progress_set_description
def _progress_set_description(self, stage, description): """ set description of an already existing progress """ self.__check_stage_registered(stage) self._prog_rep_descriptions[stage] = description if self._prog_rep_progressbars[stage]: self._prog_rep_progressbars[stage].set_description(description, refresh=False)
python
def _progress_set_description(self, stage, description): """ set description of an already existing progress """ self.__check_stage_registered(stage) self._prog_rep_descriptions[stage] = description if self._prog_rep_progressbars[stage]: self._prog_rep_progressbars[stage].set_description(description, refresh=False)
[ "def", "_progress_set_description", "(", "self", ",", "stage", ",", "description", ")", ":", "self", ".", "__check_stage_registered", "(", "stage", ")", "self", ".", "_prog_rep_descriptions", "[", "stage", "]", "=", "description", "if", "self", ".", "_prog_rep_p...
set description of an already existing progress
[ "set", "description", "of", "an", "already", "existing", "progress" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/progress/reporter/__init__.py#L155-L160
train
204,112
markovmodel/PyEMMA
pyemma/_base/progress/reporter/__init__.py
ProgressReporterMixin._progress_update
def _progress_update(self, numerator_increment, stage=0, show_eta=True, **kw): """ Updates the progress. Will update progress bars or other progress output. Parameters ---------- numerator : int numerator of partial work done already in current stage stage : int, nonnegative, default=0 Current stage of the algorithm, 0 or greater """ if not self.show_progress: return self.__check_stage_registered(stage) if not self._prog_rep_progressbars[stage]: return pg = self._prog_rep_progressbars[stage] pg.update(int(numerator_increment))
python
def _progress_update(self, numerator_increment, stage=0, show_eta=True, **kw): """ Updates the progress. Will update progress bars or other progress output. Parameters ---------- numerator : int numerator of partial work done already in current stage stage : int, nonnegative, default=0 Current stage of the algorithm, 0 or greater """ if not self.show_progress: return self.__check_stage_registered(stage) if not self._prog_rep_progressbars[stage]: return pg = self._prog_rep_progressbars[stage] pg.update(int(numerator_increment))
[ "def", "_progress_update", "(", "self", ",", "numerator_increment", ",", "stage", "=", "0", ",", "show_eta", "=", "True", ",", "*", "*", "kw", ")", ":", "if", "not", "self", ".", "show_progress", ":", "return", "self", ".", "__check_stage_registered", "(",...
Updates the progress. Will update progress bars or other progress output. Parameters ---------- numerator : int numerator of partial work done already in current stage stage : int, nonnegative, default=0 Current stage of the algorithm, 0 or greater
[ "Updates", "the", "progress", ".", "Will", "update", "progress", "bars", "or", "other", "progress", "output", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/progress/reporter/__init__.py#L162-L182
train
204,113
markovmodel/PyEMMA
pyemma/_base/progress/reporter/__init__.py
ProgressReporterMixin._progress_force_finish
def _progress_force_finish(self, stage=0, description=None): """ forcefully finish the progress for given stage """ if not self.show_progress: return self.__check_stage_registered(stage) if not self._prog_rep_progressbars[stage]: return pg = self._prog_rep_progressbars[stage] pg.desc = description increment = int(pg.total - pg.n) if increment > 0: pg.update(increment) pg.refresh(nolock=True) pg.close() self._prog_rep_progressbars.pop(stage, None) self._prog_rep_descriptions.pop(stage, None) self._prog_rep_callbacks.pop(stage, None)
python
def _progress_force_finish(self, stage=0, description=None): """ forcefully finish the progress for given stage """ if not self.show_progress: return self.__check_stage_registered(stage) if not self._prog_rep_progressbars[stage]: return pg = self._prog_rep_progressbars[stage] pg.desc = description increment = int(pg.total - pg.n) if increment > 0: pg.update(increment) pg.refresh(nolock=True) pg.close() self._prog_rep_progressbars.pop(stage, None) self._prog_rep_descriptions.pop(stage, None) self._prog_rep_callbacks.pop(stage, None)
[ "def", "_progress_force_finish", "(", "self", ",", "stage", "=", "0", ",", "description", "=", "None", ")", ":", "if", "not", "self", ".", "show_progress", ":", "return", "self", ".", "__check_stage_registered", "(", "stage", ")", "if", "not", "self", ".",...
forcefully finish the progress for given stage
[ "forcefully", "finish", "the", "progress", "for", "given", "stage" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/progress/reporter/__init__.py#L184-L203
train
204,114
markovmodel/PyEMMA
pyemma/plots/plots1d.py
plot_feature_histograms
def plot_feature_histograms(xyzall, feature_labels=None, ax=None, ylog=False, outfile=None, n_bins=50, ignore_dim_warning=False, **kwargs): r"""Feature histogram plot Parameters ---------- xyzall : np.ndarray(T, d) (Concatenated list of) input features; containing time series data to be plotted. Array of T data points in d dimensions (features). feature_labels : iterable of str or pyemma.Featurizer, optional, default=None Labels of histogramed features, defaults to feature index. ax : matplotlib.Axes object, optional, default=None. The ax to plot to; if ax=None, a new ax (and fig) is created. ylog : boolean, default=False If True, plot logarithm of histogram values. n_bins : int, default=50 Number of bins the histogram uses. outfile : str, default=None If not None, saves plot to this file. ignore_dim_warning : boolean, default=False Enable plotting for more than 50 dimensions (on your own risk). **kwargs: kwargs passed to pyplot.fill_between. See the doc of pyplot for options. Returns ------- fig : matplotlib.Figure object The figure in which the used ax resides. ax : matplotlib.Axes object The ax in which the historams were plotted. """ if not isinstance(xyzall, _np.ndarray): raise ValueError('Input data hast to be a numpy array. Did you concatenate your data?') if xyzall.shape[1] > 50 and not ignore_dim_warning: raise RuntimeError('This function is only useful for less than 50 dimensions. Turn-off this warning ' 'at your own risk with ignore_dim_warning=True.') if feature_labels is not None: if not isinstance(feature_labels, list): from pyemma.coordinates.data.featurization.featurizer import MDFeaturizer as _MDFeaturizer if isinstance(feature_labels, _MDFeaturizer): feature_labels = feature_labels.describe() else: raise ValueError('feature_labels must be a list of feature labels, ' 'a pyemma featurizer object or None.') if not xyzall.shape[1] == len(feature_labels): raise ValueError('feature_labels must have the same dimension as the input data xyzall.') # make nice plots if user does not decide on color and transparency if 'color' not in kwargs.keys(): kwargs['color'] = 'b' if 'alpha' not in kwargs.keys(): kwargs['alpha'] = .25 import matplotlib.pyplot as _plt # check input if ax is None: fig, ax = _plt.subplots() else: fig = ax.get_figure() hist_offset = -.2 for h, coordinate in enumerate(reversed(xyzall.T)): hist, edges = _np.histogram(coordinate, bins=n_bins) if not ylog: y = hist / hist.max() else: y = _np.zeros_like(hist) + _np.NaN pos_idx = hist > 0 y[pos_idx] = _np.log(hist[pos_idx]) / _np.log(hist[pos_idx]).max() ax.fill_between(edges[:-1], y + h + hist_offset, y2=h + hist_offset, **kwargs) ax.axhline(y=h + hist_offset, xmin=0, xmax=1, color='k', linewidth=.2) ax.set_ylim(hist_offset, h + hist_offset + 1) # formatting if feature_labels is None: feature_labels = [str(n) for n in range(xyzall.shape[1])] ax.set_ylabel('Feature histograms') ax.set_yticks(_np.array(range(len(feature_labels))) + .3) ax.set_yticklabels(feature_labels[::-1]) ax.set_xlabel('Feature values') # save if outfile is not None: fig.savefig(outfile) return fig, ax
python
def plot_feature_histograms(xyzall, feature_labels=None, ax=None, ylog=False, outfile=None, n_bins=50, ignore_dim_warning=False, **kwargs): r"""Feature histogram plot Parameters ---------- xyzall : np.ndarray(T, d) (Concatenated list of) input features; containing time series data to be plotted. Array of T data points in d dimensions (features). feature_labels : iterable of str or pyemma.Featurizer, optional, default=None Labels of histogramed features, defaults to feature index. ax : matplotlib.Axes object, optional, default=None. The ax to plot to; if ax=None, a new ax (and fig) is created. ylog : boolean, default=False If True, plot logarithm of histogram values. n_bins : int, default=50 Number of bins the histogram uses. outfile : str, default=None If not None, saves plot to this file. ignore_dim_warning : boolean, default=False Enable plotting for more than 50 dimensions (on your own risk). **kwargs: kwargs passed to pyplot.fill_between. See the doc of pyplot for options. Returns ------- fig : matplotlib.Figure object The figure in which the used ax resides. ax : matplotlib.Axes object The ax in which the historams were plotted. """ if not isinstance(xyzall, _np.ndarray): raise ValueError('Input data hast to be a numpy array. Did you concatenate your data?') if xyzall.shape[1] > 50 and not ignore_dim_warning: raise RuntimeError('This function is only useful for less than 50 dimensions. Turn-off this warning ' 'at your own risk with ignore_dim_warning=True.') if feature_labels is not None: if not isinstance(feature_labels, list): from pyemma.coordinates.data.featurization.featurizer import MDFeaturizer as _MDFeaturizer if isinstance(feature_labels, _MDFeaturizer): feature_labels = feature_labels.describe() else: raise ValueError('feature_labels must be a list of feature labels, ' 'a pyemma featurizer object or None.') if not xyzall.shape[1] == len(feature_labels): raise ValueError('feature_labels must have the same dimension as the input data xyzall.') # make nice plots if user does not decide on color and transparency if 'color' not in kwargs.keys(): kwargs['color'] = 'b' if 'alpha' not in kwargs.keys(): kwargs['alpha'] = .25 import matplotlib.pyplot as _plt # check input if ax is None: fig, ax = _plt.subplots() else: fig = ax.get_figure() hist_offset = -.2 for h, coordinate in enumerate(reversed(xyzall.T)): hist, edges = _np.histogram(coordinate, bins=n_bins) if not ylog: y = hist / hist.max() else: y = _np.zeros_like(hist) + _np.NaN pos_idx = hist > 0 y[pos_idx] = _np.log(hist[pos_idx]) / _np.log(hist[pos_idx]).max() ax.fill_between(edges[:-1], y + h + hist_offset, y2=h + hist_offset, **kwargs) ax.axhline(y=h + hist_offset, xmin=0, xmax=1, color='k', linewidth=.2) ax.set_ylim(hist_offset, h + hist_offset + 1) # formatting if feature_labels is None: feature_labels = [str(n) for n in range(xyzall.shape[1])] ax.set_ylabel('Feature histograms') ax.set_yticks(_np.array(range(len(feature_labels))) + .3) ax.set_yticklabels(feature_labels[::-1]) ax.set_xlabel('Feature values') # save if outfile is not None: fig.savefig(outfile) return fig, ax
[ "def", "plot_feature_histograms", "(", "xyzall", ",", "feature_labels", "=", "None", ",", "ax", "=", "None", ",", "ylog", "=", "False", ",", "outfile", "=", "None", ",", "n_bins", "=", "50", ",", "ignore_dim_warning", "=", "False", ",", "*", "*", "kwargs...
r"""Feature histogram plot Parameters ---------- xyzall : np.ndarray(T, d) (Concatenated list of) input features; containing time series data to be plotted. Array of T data points in d dimensions (features). feature_labels : iterable of str or pyemma.Featurizer, optional, default=None Labels of histogramed features, defaults to feature index. ax : matplotlib.Axes object, optional, default=None. The ax to plot to; if ax=None, a new ax (and fig) is created. ylog : boolean, default=False If True, plot logarithm of histogram values. n_bins : int, default=50 Number of bins the histogram uses. outfile : str, default=None If not None, saves plot to this file. ignore_dim_warning : boolean, default=False Enable plotting for more than 50 dimensions (on your own risk). **kwargs: kwargs passed to pyplot.fill_between. See the doc of pyplot for options. Returns ------- fig : matplotlib.Figure object The figure in which the used ax resides. ax : matplotlib.Axes object The ax in which the historams were plotted.
[ "r", "Feature", "histogram", "plot" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/plots/plots1d.py#L24-L118
train
204,115
markovmodel/PyEMMA
pyemma/coordinates/data/_base/_in_memory_mixin.py
InMemoryMixin.in_memory
def in_memory(self, op_in_mem): r""" If set to True, the output will be stored in memory. """ old_state = self.in_memory if not old_state and op_in_mem: self._map_to_memory() elif not op_in_mem and old_state: self._clear_in_memory()
python
def in_memory(self, op_in_mem): r""" If set to True, the output will be stored in memory. """ old_state = self.in_memory if not old_state and op_in_mem: self._map_to_memory() elif not op_in_mem and old_state: self._clear_in_memory()
[ "def", "in_memory", "(", "self", ",", "op_in_mem", ")", ":", "old_state", "=", "self", ".", "in_memory", "if", "not", "old_state", "and", "op_in_mem", ":", "self", ".", "_map_to_memory", "(", ")", "elif", "not", "op_in_mem", "and", "old_state", ":", "self"...
r""" If set to True, the output will be stored in memory.
[ "r", "If", "set", "to", "True", "the", "output", "will", "be", "stored", "in", "memory", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/_base/_in_memory_mixin.py#L22-L30
train
204,116
markovmodel/PyEMMA
pyemma/coordinates/transform/vamp.py
VAMPModel.expectation
def expectation(self, observables, statistics, lag_multiple=1, observables_mean_free=False, statistics_mean_free=False): r"""Compute future expectation of observable or covariance using the approximated Koopman operator. Parameters ---------- observables : np.ndarray((input_dimension, n_observables)) Coefficients that express one or multiple observables in the basis of the input features. statistics : np.ndarray((input_dimension, n_statistics)), optional Coefficients that express one or multiple statistics in the basis of the input features. This parameter can be None. In that case, this method returns the future expectation value of the observable(s). lag_multiple : int If > 1, extrapolate to a multiple of the estimator's lag time by assuming Markovianity of the approximated Koopman operator. observables_mean_free : bool, default=False If true, coefficients in `observables` refer to the input features with feature means removed. If false, coefficients in `observables` refer to the unmodified input features. statistics_mean_free : bool, default=False If true, coefficients in `statistics` refer to the input features with feature means removed. If false, coefficients in `statistics` refer to the unmodified input features. Notes ----- A "future expectation" of a observable g is the average of g computed over a time window that has the same total length as the input data from which the Koopman operator was estimated but is shifted by lag_multiple*tau time steps into the future (where tau is the lag time). It is computed with the equation: .. math:: \mathbb{E}[g]_{\rho_{n}}=\mathbf{q}^{T}\mathbf{P}^{n-1}\mathbf{e}_{1} where .. math:: P_{ij}=\sigma_{i}\langle\psi_{i},\phi_{j}\rangle_{\rho_{1}} and .. math:: q_{i}=\langle g,\phi_{i}\rangle_{\rho_{1}} and :math:`\mathbf{e}_{1}` is the first canonical unit vector. A model prediction of time-lagged covariances between the observable f and the statistic g at a lag-time of lag_multiple*tau is computed with the equation: .. math:: \mathrm{cov}[g,\,f;n\tau]=\mathbf{q}^{T}\mathbf{P}^{n-1}\boldsymbol{\Sigma}\mathbf{r} where :math:`r_{i}=\langle\psi_{i},f\rangle_{\rho_{0}}` and :math:`\boldsymbol{\Sigma}=\mathrm{diag(\boldsymbol{\sigma})}` . """ # TODO: implement the case lag_multiple=0 dim = self.dimension() S = np.diag(np.concatenate(([1.0], self.singular_values[0:dim]))) V = self.V[:, 0:dim] U = self.U[:, 0:dim] m_0 = self.mean_0 m_t = self.mean_t assert lag_multiple >= 1, 'lag_multiple = 0 not implemented' if lag_multiple == 1: P = S else: p = np.zeros((dim + 1, dim + 1)) p[0, 0] = 1.0 p[1:, 0] = U.T.dot(m_t - m_0) p[1:, 1:] = U.T.dot(self.Ctt).dot(V) P = np.linalg.matrix_power(S.dot(p), lag_multiple - 1).dot(S) Q = np.zeros((observables.shape[1], dim + 1)) if not observables_mean_free: Q[:, 0] = observables.T.dot(m_t) Q[:, 1:] = observables.T.dot(self.Ctt).dot(V) if statistics is not None: # compute covariance R = np.zeros((statistics.shape[1], dim + 1)) if not statistics_mean_free: R[:, 0] = statistics.T.dot(m_0) R[:, 1:] = statistics.T.dot(self.C00).dot(U) if statistics is not None: # compute lagged covariance return Q.dot(P).dot(R.T) # TODO: discuss whether we want to return this or the transpose # TODO: from MSMs one might expect to first index to refer to the statistics, here it is the other way round else: # compute future expectation return Q.dot(P)[:, 0]
python
def expectation(self, observables, statistics, lag_multiple=1, observables_mean_free=False, statistics_mean_free=False): r"""Compute future expectation of observable or covariance using the approximated Koopman operator. Parameters ---------- observables : np.ndarray((input_dimension, n_observables)) Coefficients that express one or multiple observables in the basis of the input features. statistics : np.ndarray((input_dimension, n_statistics)), optional Coefficients that express one or multiple statistics in the basis of the input features. This parameter can be None. In that case, this method returns the future expectation value of the observable(s). lag_multiple : int If > 1, extrapolate to a multiple of the estimator's lag time by assuming Markovianity of the approximated Koopman operator. observables_mean_free : bool, default=False If true, coefficients in `observables` refer to the input features with feature means removed. If false, coefficients in `observables` refer to the unmodified input features. statistics_mean_free : bool, default=False If true, coefficients in `statistics` refer to the input features with feature means removed. If false, coefficients in `statistics` refer to the unmodified input features. Notes ----- A "future expectation" of a observable g is the average of g computed over a time window that has the same total length as the input data from which the Koopman operator was estimated but is shifted by lag_multiple*tau time steps into the future (where tau is the lag time). It is computed with the equation: .. math:: \mathbb{E}[g]_{\rho_{n}}=\mathbf{q}^{T}\mathbf{P}^{n-1}\mathbf{e}_{1} where .. math:: P_{ij}=\sigma_{i}\langle\psi_{i},\phi_{j}\rangle_{\rho_{1}} and .. math:: q_{i}=\langle g,\phi_{i}\rangle_{\rho_{1}} and :math:`\mathbf{e}_{1}` is the first canonical unit vector. A model prediction of time-lagged covariances between the observable f and the statistic g at a lag-time of lag_multiple*tau is computed with the equation: .. math:: \mathrm{cov}[g,\,f;n\tau]=\mathbf{q}^{T}\mathbf{P}^{n-1}\boldsymbol{\Sigma}\mathbf{r} where :math:`r_{i}=\langle\psi_{i},f\rangle_{\rho_{0}}` and :math:`\boldsymbol{\Sigma}=\mathrm{diag(\boldsymbol{\sigma})}` . """ # TODO: implement the case lag_multiple=0 dim = self.dimension() S = np.diag(np.concatenate(([1.0], self.singular_values[0:dim]))) V = self.V[:, 0:dim] U = self.U[:, 0:dim] m_0 = self.mean_0 m_t = self.mean_t assert lag_multiple >= 1, 'lag_multiple = 0 not implemented' if lag_multiple == 1: P = S else: p = np.zeros((dim + 1, dim + 1)) p[0, 0] = 1.0 p[1:, 0] = U.T.dot(m_t - m_0) p[1:, 1:] = U.T.dot(self.Ctt).dot(V) P = np.linalg.matrix_power(S.dot(p), lag_multiple - 1).dot(S) Q = np.zeros((observables.shape[1], dim + 1)) if not observables_mean_free: Q[:, 0] = observables.T.dot(m_t) Q[:, 1:] = observables.T.dot(self.Ctt).dot(V) if statistics is not None: # compute covariance R = np.zeros((statistics.shape[1], dim + 1)) if not statistics_mean_free: R[:, 0] = statistics.T.dot(m_0) R[:, 1:] = statistics.T.dot(self.C00).dot(U) if statistics is not None: # compute lagged covariance return Q.dot(P).dot(R.T) # TODO: discuss whether we want to return this or the transpose # TODO: from MSMs one might expect to first index to refer to the statistics, here it is the other way round else: # compute future expectation return Q.dot(P)[:, 0]
[ "def", "expectation", "(", "self", ",", "observables", ",", "statistics", ",", "lag_multiple", "=", "1", ",", "observables_mean_free", "=", "False", ",", "statistics_mean_free", "=", "False", ")", ":", "# TODO: implement the case lag_multiple=0", "dim", "=", "self",...
r"""Compute future expectation of observable or covariance using the approximated Koopman operator. Parameters ---------- observables : np.ndarray((input_dimension, n_observables)) Coefficients that express one or multiple observables in the basis of the input features. statistics : np.ndarray((input_dimension, n_statistics)), optional Coefficients that express one or multiple statistics in the basis of the input features. This parameter can be None. In that case, this method returns the future expectation value of the observable(s). lag_multiple : int If > 1, extrapolate to a multiple of the estimator's lag time by assuming Markovianity of the approximated Koopman operator. observables_mean_free : bool, default=False If true, coefficients in `observables` refer to the input features with feature means removed. If false, coefficients in `observables` refer to the unmodified input features. statistics_mean_free : bool, default=False If true, coefficients in `statistics` refer to the input features with feature means removed. If false, coefficients in `statistics` refer to the unmodified input features. Notes ----- A "future expectation" of a observable g is the average of g computed over a time window that has the same total length as the input data from which the Koopman operator was estimated but is shifted by lag_multiple*tau time steps into the future (where tau is the lag time). It is computed with the equation: .. math:: \mathbb{E}[g]_{\rho_{n}}=\mathbf{q}^{T}\mathbf{P}^{n-1}\mathbf{e}_{1} where .. math:: P_{ij}=\sigma_{i}\langle\psi_{i},\phi_{j}\rangle_{\rho_{1}} and .. math:: q_{i}=\langle g,\phi_{i}\rangle_{\rho_{1}} and :math:`\mathbf{e}_{1}` is the first canonical unit vector. A model prediction of time-lagged covariances between the observable f and the statistic g at a lag-time of lag_multiple*tau is computed with the equation: .. math:: \mathrm{cov}[g,\,f;n\tau]=\mathbf{q}^{T}\mathbf{P}^{n-1}\boldsymbol{\Sigma}\mathbf{r} where :math:`r_{i}=\langle\psi_{i},f\rangle_{\rho_{0}}` and :math:`\boldsymbol{\Sigma}=\mathrm{diag(\boldsymbol{\sigma})}` .
[ "r", "Compute", "future", "expectation", "of", "observable", "or", "covariance", "using", "the", "approximated", "Koopman", "operator", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/vamp.py#L150-L262
train
204,117
markovmodel/PyEMMA
pyemma/coordinates/transform/vamp.py
VAMPModel._diagonalize
def _diagonalize(self): """Performs SVD on covariance matrices and save left, right singular vectors and values in the model. Parameters ---------- scaling : None or string, default=None Scaling to be applied to the VAMP modes upon transformation * None: no scaling will be applied, variance of the singular functions is 1 * 'kinetic map' or 'km': singular functions are scaled by singular value. Note that only the left singular functions induce a kinetic map. """ L0 = spd_inv_split(self.C00, epsilon=self.epsilon) self._rank0 = L0.shape[1] if L0.ndim == 2 else 1 Lt = spd_inv_split(self.Ctt, epsilon=self.epsilon) self._rankt = Lt.shape[1] if Lt.ndim == 2 else 1 W = np.dot(L0.T, self.C0t).dot(Lt) from scipy.linalg import svd A, s, BT = svd(W, compute_uv=True, lapack_driver='gesvd') self._singular_values = s # don't pass any values in the argument list that call _diagonalize again!!! m = VAMPModel._dimension(self._rank0, self._rankt, self.dim, self._singular_values) U = np.dot(L0, A[:, :m]) V = np.dot(Lt, BT[:m, :].T) # scale vectors if self.scaling is not None: U *= s[np.newaxis, 0:m] # scaled left singular functions induce a kinetic map V *= s[np.newaxis, 0:m] # scaled right singular functions induce a kinetic map wrt. backward propagator self._U = U self._V = V self._svd_performed = True
python
def _diagonalize(self): """Performs SVD on covariance matrices and save left, right singular vectors and values in the model. Parameters ---------- scaling : None or string, default=None Scaling to be applied to the VAMP modes upon transformation * None: no scaling will be applied, variance of the singular functions is 1 * 'kinetic map' or 'km': singular functions are scaled by singular value. Note that only the left singular functions induce a kinetic map. """ L0 = spd_inv_split(self.C00, epsilon=self.epsilon) self._rank0 = L0.shape[1] if L0.ndim == 2 else 1 Lt = spd_inv_split(self.Ctt, epsilon=self.epsilon) self._rankt = Lt.shape[1] if Lt.ndim == 2 else 1 W = np.dot(L0.T, self.C0t).dot(Lt) from scipy.linalg import svd A, s, BT = svd(W, compute_uv=True, lapack_driver='gesvd') self._singular_values = s # don't pass any values in the argument list that call _diagonalize again!!! m = VAMPModel._dimension(self._rank0, self._rankt, self.dim, self._singular_values) U = np.dot(L0, A[:, :m]) V = np.dot(Lt, BT[:m, :].T) # scale vectors if self.scaling is not None: U *= s[np.newaxis, 0:m] # scaled left singular functions induce a kinetic map V *= s[np.newaxis, 0:m] # scaled right singular functions induce a kinetic map wrt. backward propagator self._U = U self._V = V self._svd_performed = True
[ "def", "_diagonalize", "(", "self", ")", ":", "L0", "=", "spd_inv_split", "(", "self", ".", "C00", ",", "epsilon", "=", "self", ".", "epsilon", ")", "self", ".", "_rank0", "=", "L0", ".", "shape", "[", "1", "]", "if", "L0", ".", "ndim", "==", "2"...
Performs SVD on covariance matrices and save left, right singular vectors and values in the model. Parameters ---------- scaling : None or string, default=None Scaling to be applied to the VAMP modes upon transformation * None: no scaling will be applied, variance of the singular functions is 1 * 'kinetic map' or 'km': singular functions are scaled by singular value. Note that only the left singular functions induce a kinetic map.
[ "Performs", "SVD", "on", "covariance", "matrices", "and", "save", "left", "right", "singular", "vectors", "and", "values", "in", "the", "model", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/vamp.py#L264-L301
train
204,118
markovmodel/PyEMMA
pyemma/coordinates/transform/vamp.py
VAMPModel.score
def score(self, test_model=None, score_method='VAMP2'): """Compute the VAMP score for this model or the cross-validation score between self and a second model. Parameters ---------- test_model : VAMPModel, optional, default=None If `test_model` is not None, this method computes the cross-validation score between self and `test_model`. It is assumed that self was estimated from the "training" data and `test_model` was estimated from the "test" data. The score is computed for one realization of self and `test_model`. Estimation of the average cross-validation score and partitioning of data into test and training part is not performed by this method. If `test_model` is None, this method computes the VAMP score for the model contained in self. score_method : str, optional, default='VAMP2' Available scores are based on the variational approach for Markov processes [1]_: * 'VAMP1' Sum of singular values of the half-weighted Koopman matrix [1]_ . If the model is reversible, this is equal to the sum of Koopman matrix eigenvalues, also called Rayleigh quotient [1]_. * 'VAMP2' Sum of squared singular values of the half-weighted Koopman matrix [1]_ . If the model is reversible, this is equal to the kinetic variance [2]_ . * 'VAMPE' Approximation error of the estimated Koopman operator with respect to the true Koopman operator up to an additive constant [1]_ . Returns ------- score : float If `test_model` is not None, returns the cross-validation VAMP score between self and `test_model`. Otherwise return the selected VAMP-score of self. References ---------- .. [1] Wu, H. and Noe, F. 2017. Variational approach for learning Markov processes from time series data. arXiv:1707.04659v1 .. [2] Noe, F. and Clementi, C. 2015. Kinetic distance and kinetic maps from molecular dynamics simulation. J. Chem. Theory. Comput. doi:10.1021/acs.jctc.5b00553 """ # TODO: implement for TICA too if test_model is None: test_model = self Uk = self.U[:, 0:self.dimension()] Vk = self.V[:, 0:self.dimension()] res = None if score_method == 'VAMP1' or score_method == 'VAMP2': A = spd_inv_sqrt(Uk.T.dot(test_model.C00).dot(Uk)) B = Uk.T.dot(test_model.C0t).dot(Vk) C = spd_inv_sqrt(Vk.T.dot(test_model.Ctt).dot(Vk)) ABC = mdot(A, B, C) if score_method == 'VAMP1': res = np.linalg.norm(ABC, ord='nuc') elif score_method == 'VAMP2': res = np.linalg.norm(ABC, ord='fro')**2 elif score_method == 'VAMPE': Sk = np.diag(self.singular_values[0:self.dimension()]) res = np.trace(2.0 * mdot(Vk, Sk, Uk.T, test_model.C0t) - mdot(Vk, Sk, Uk.T, test_model.C00, Uk, Sk, Vk.T, test_model.Ctt)) else: raise ValueError('"score" should be one of VAMP1, VAMP2 or VAMPE') # add the contribution (+1) of the constant singular functions to the result assert res return res + 1
python
def score(self, test_model=None, score_method='VAMP2'): """Compute the VAMP score for this model or the cross-validation score between self and a second model. Parameters ---------- test_model : VAMPModel, optional, default=None If `test_model` is not None, this method computes the cross-validation score between self and `test_model`. It is assumed that self was estimated from the "training" data and `test_model` was estimated from the "test" data. The score is computed for one realization of self and `test_model`. Estimation of the average cross-validation score and partitioning of data into test and training part is not performed by this method. If `test_model` is None, this method computes the VAMP score for the model contained in self. score_method : str, optional, default='VAMP2' Available scores are based on the variational approach for Markov processes [1]_: * 'VAMP1' Sum of singular values of the half-weighted Koopman matrix [1]_ . If the model is reversible, this is equal to the sum of Koopman matrix eigenvalues, also called Rayleigh quotient [1]_. * 'VAMP2' Sum of squared singular values of the half-weighted Koopman matrix [1]_ . If the model is reversible, this is equal to the kinetic variance [2]_ . * 'VAMPE' Approximation error of the estimated Koopman operator with respect to the true Koopman operator up to an additive constant [1]_ . Returns ------- score : float If `test_model` is not None, returns the cross-validation VAMP score between self and `test_model`. Otherwise return the selected VAMP-score of self. References ---------- .. [1] Wu, H. and Noe, F. 2017. Variational approach for learning Markov processes from time series data. arXiv:1707.04659v1 .. [2] Noe, F. and Clementi, C. 2015. Kinetic distance and kinetic maps from molecular dynamics simulation. J. Chem. Theory. Comput. doi:10.1021/acs.jctc.5b00553 """ # TODO: implement for TICA too if test_model is None: test_model = self Uk = self.U[:, 0:self.dimension()] Vk = self.V[:, 0:self.dimension()] res = None if score_method == 'VAMP1' or score_method == 'VAMP2': A = spd_inv_sqrt(Uk.T.dot(test_model.C00).dot(Uk)) B = Uk.T.dot(test_model.C0t).dot(Vk) C = spd_inv_sqrt(Vk.T.dot(test_model.Ctt).dot(Vk)) ABC = mdot(A, B, C) if score_method == 'VAMP1': res = np.linalg.norm(ABC, ord='nuc') elif score_method == 'VAMP2': res = np.linalg.norm(ABC, ord='fro')**2 elif score_method == 'VAMPE': Sk = np.diag(self.singular_values[0:self.dimension()]) res = np.trace(2.0 * mdot(Vk, Sk, Uk.T, test_model.C0t) - mdot(Vk, Sk, Uk.T, test_model.C00, Uk, Sk, Vk.T, test_model.Ctt)) else: raise ValueError('"score" should be one of VAMP1, VAMP2 or VAMPE') # add the contribution (+1) of the constant singular functions to the result assert res return res + 1
[ "def", "score", "(", "self", ",", "test_model", "=", "None", ",", "score_method", "=", "'VAMP2'", ")", ":", "# TODO: implement for TICA too", "if", "test_model", "is", "None", ":", "test_model", "=", "self", "Uk", "=", "self", ".", "U", "[", ":", ",", "0...
Compute the VAMP score for this model or the cross-validation score between self and a second model. Parameters ---------- test_model : VAMPModel, optional, default=None If `test_model` is not None, this method computes the cross-validation score between self and `test_model`. It is assumed that self was estimated from the "training" data and `test_model` was estimated from the "test" data. The score is computed for one realization of self and `test_model`. Estimation of the average cross-validation score and partitioning of data into test and training part is not performed by this method. If `test_model` is None, this method computes the VAMP score for the model contained in self. score_method : str, optional, default='VAMP2' Available scores are based on the variational approach for Markov processes [1]_: * 'VAMP1' Sum of singular values of the half-weighted Koopman matrix [1]_ . If the model is reversible, this is equal to the sum of Koopman matrix eigenvalues, also called Rayleigh quotient [1]_. * 'VAMP2' Sum of squared singular values of the half-weighted Koopman matrix [1]_ . If the model is reversible, this is equal to the kinetic variance [2]_ . * 'VAMPE' Approximation error of the estimated Koopman operator with respect to the true Koopman operator up to an additive constant [1]_ . Returns ------- score : float If `test_model` is not None, returns the cross-validation VAMP score between self and `test_model`. Otherwise return the selected VAMP-score of self. References ---------- .. [1] Wu, H. and Noe, F. 2017. Variational approach for learning Markov processes from time series data. arXiv:1707.04659v1 .. [2] Noe, F. and Clementi, C. 2015. Kinetic distance and kinetic maps from molecular dynamics simulation. J. Chem. Theory. Comput. doi:10.1021/acs.jctc.5b00553
[ "Compute", "the", "VAMP", "score", "for", "this", "model", "or", "the", "cross", "-", "validation", "score", "between", "self", "and", "a", "second", "model", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/vamp.py#L303-L366
train
204,119
markovmodel/PyEMMA
pyemma/datasets/api.py
get_umbrella_sampling_data
def get_umbrella_sampling_data(ntherm=11, us_fc=20.0, us_length=500, md_length=1000, nmd=20): """ Continuous MCMC process in an asymmetric double well potential using umbrella sampling. Parameters ---------- ntherm: int, optional, default=11 Number of umbrella states. us_fc: double, optional, default=20.0 Force constant in kT/length^2 for each umbrella. us_length: int, optional, default=500 Length in steps of each umbrella trajectory. md_length: int, optional, default=1000 Length in steps of each unbiased trajectory. nmd: int, optional, default=20 Number of unbiased trajectories. Returns ------- dict - keys shown below in brackets Trajectory data from umbrella sampling (us_trajs) and unbiased (md_trajs) MCMC runs and their discretised counterparts (us_dtrajs + md_dtrajs + centers). The umbrella sampling parameters (us_centers + us_force_constants) are in the same order as the umbrella sampling trajectories. Energies are given in kT, lengths in arbitrary units. """ dws = _DWS() us_data = dws.us_sample( ntherm=ntherm, us_fc=us_fc, us_length=us_length, md_length=md_length, nmd=nmd) us_data.update(centers=dws.centers) return us_data
python
def get_umbrella_sampling_data(ntherm=11, us_fc=20.0, us_length=500, md_length=1000, nmd=20): """ Continuous MCMC process in an asymmetric double well potential using umbrella sampling. Parameters ---------- ntherm: int, optional, default=11 Number of umbrella states. us_fc: double, optional, default=20.0 Force constant in kT/length^2 for each umbrella. us_length: int, optional, default=500 Length in steps of each umbrella trajectory. md_length: int, optional, default=1000 Length in steps of each unbiased trajectory. nmd: int, optional, default=20 Number of unbiased trajectories. Returns ------- dict - keys shown below in brackets Trajectory data from umbrella sampling (us_trajs) and unbiased (md_trajs) MCMC runs and their discretised counterparts (us_dtrajs + md_dtrajs + centers). The umbrella sampling parameters (us_centers + us_force_constants) are in the same order as the umbrella sampling trajectories. Energies are given in kT, lengths in arbitrary units. """ dws = _DWS() us_data = dws.us_sample( ntherm=ntherm, us_fc=us_fc, us_length=us_length, md_length=md_length, nmd=nmd) us_data.update(centers=dws.centers) return us_data
[ "def", "get_umbrella_sampling_data", "(", "ntherm", "=", "11", ",", "us_fc", "=", "20.0", ",", "us_length", "=", "500", ",", "md_length", "=", "1000", ",", "nmd", "=", "20", ")", ":", "dws", "=", "_DWS", "(", ")", "us_data", "=", "dws", ".", "us_samp...
Continuous MCMC process in an asymmetric double well potential using umbrella sampling. Parameters ---------- ntherm: int, optional, default=11 Number of umbrella states. us_fc: double, optional, default=20.0 Force constant in kT/length^2 for each umbrella. us_length: int, optional, default=500 Length in steps of each umbrella trajectory. md_length: int, optional, default=1000 Length in steps of each unbiased trajectory. nmd: int, optional, default=20 Number of unbiased trajectories. Returns ------- dict - keys shown below in brackets Trajectory data from umbrella sampling (us_trajs) and unbiased (md_trajs) MCMC runs and their discretised counterparts (us_dtrajs + md_dtrajs + centers). The umbrella sampling parameters (us_centers + us_force_constants) are in the same order as the umbrella sampling trajectories. Energies are given in kT, lengths in arbitrary units.
[ "Continuous", "MCMC", "process", "in", "an", "asymmetric", "double", "well", "potential", "using", "umbrella", "sampling", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/api.py#L57-L86
train
204,120
markovmodel/PyEMMA
pyemma/datasets/api.py
get_multi_temperature_data
def get_multi_temperature_data(kt0=1.0, kt1=5.0, length0=10000, length1=10000, n0=10, n1=10): """ Continuous MCMC process in an asymmetric double well potential at multiple temperatures. Parameters ---------- kt0: double, optional, default=1.0 Temperature in kT for the first thermodynamic state. kt1: double, optional, default=5.0 Temperature in kT for the second thermodynamic state. length0: int, optional, default=10000 Trajectory length in steps for the first thermodynamic state. length1: int, optional, default=10000 Trajectory length in steps for the second thermodynamic state. n0: int, optional, default=10 Number of trajectories in the first thermodynamic state. n1: int, optional, default=10 Number of trajectories in the second thermodynamic state. Returns ------- dict - keys shown below in brackets Trajectory (trajs), energy (energy_trajs), and temperature (temp_trajs) data from the MCMC runs as well as the discretised version (dtrajs + centers). Energies and temperatures are given in kT, lengths in arbitrary units. """ dws = _DWS() mt_data = dws.mt_sample( kt0=kt0, kt1=kt1, length0=length0, length1=length1, n0=n0, n1=n1) mt_data.update(centers=dws.centers) return mt_data
python
def get_multi_temperature_data(kt0=1.0, kt1=5.0, length0=10000, length1=10000, n0=10, n1=10): """ Continuous MCMC process in an asymmetric double well potential at multiple temperatures. Parameters ---------- kt0: double, optional, default=1.0 Temperature in kT for the first thermodynamic state. kt1: double, optional, default=5.0 Temperature in kT for the second thermodynamic state. length0: int, optional, default=10000 Trajectory length in steps for the first thermodynamic state. length1: int, optional, default=10000 Trajectory length in steps for the second thermodynamic state. n0: int, optional, default=10 Number of trajectories in the first thermodynamic state. n1: int, optional, default=10 Number of trajectories in the second thermodynamic state. Returns ------- dict - keys shown below in brackets Trajectory (trajs), energy (energy_trajs), and temperature (temp_trajs) data from the MCMC runs as well as the discretised version (dtrajs + centers). Energies and temperatures are given in kT, lengths in arbitrary units. """ dws = _DWS() mt_data = dws.mt_sample( kt0=kt0, kt1=kt1, length0=length0, length1=length1, n0=n0, n1=n1) mt_data.update(centers=dws.centers) return mt_data
[ "def", "get_multi_temperature_data", "(", "kt0", "=", "1.0", ",", "kt1", "=", "5.0", ",", "length0", "=", "10000", ",", "length1", "=", "10000", ",", "n0", "=", "10", ",", "n1", "=", "10", ")", ":", "dws", "=", "_DWS", "(", ")", "mt_data", "=", "...
Continuous MCMC process in an asymmetric double well potential at multiple temperatures. Parameters ---------- kt0: double, optional, default=1.0 Temperature in kT for the first thermodynamic state. kt1: double, optional, default=5.0 Temperature in kT for the second thermodynamic state. length0: int, optional, default=10000 Trajectory length in steps for the first thermodynamic state. length1: int, optional, default=10000 Trajectory length in steps for the second thermodynamic state. n0: int, optional, default=10 Number of trajectories in the first thermodynamic state. n1: int, optional, default=10 Number of trajectories in the second thermodynamic state. Returns ------- dict - keys shown below in brackets Trajectory (trajs), energy (energy_trajs), and temperature (temp_trajs) data from the MCMC runs as well as the discretised version (dtrajs + centers). Energies and temperatures are given in kT, lengths in arbitrary units.
[ "Continuous", "MCMC", "process", "in", "an", "asymmetric", "double", "well", "potential", "at", "multiple", "temperatures", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/api.py#L89-L119
train
204,121
markovmodel/PyEMMA
pyemma/util/units.py
TimeUnit.get_scaled
def get_scaled(self, factor): """ Get a new time unit, scaled by the given factor """ res = TimeUnit(self) res._factor = self._factor * factor res._unit = self._unit return res
python
def get_scaled(self, factor): """ Get a new time unit, scaled by the given factor """ res = TimeUnit(self) res._factor = self._factor * factor res._unit = self._unit return res
[ "def", "get_scaled", "(", "self", ",", "factor", ")", ":", "res", "=", "TimeUnit", "(", "self", ")", "res", ".", "_factor", "=", "self", ".", "_factor", "*", "factor", "res", ".", "_unit", "=", "self", ".", "_unit", "return", "res" ]
Get a new time unit, scaled by the given factor
[ "Get", "a", "new", "time", "unit", "scaled", "by", "the", "given", "factor" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/units.py#L116-L121
train
204,122
markovmodel/PyEMMA
pyemma/util/units.py
TimeUnit.rescale_around1
def rescale_around1(self, times): """ Suggests a rescaling factor and new physical time unit to balance the given time multiples around 1. Parameters ---------- times : float array array of times in multiple of the present elementary unit """ if self._unit == self._UNIT_STEP: return times, 'step' # nothing to do m = np.mean(times) mult = 1.0 cur_unit = self._unit # numbers are too small. Making them larger and reducing the unit: if (m < 0.001): while mult*m < 0.001 and cur_unit >= 0: mult *= 1000 cur_unit -= 1 return mult*times, self._unit_names[cur_unit] # numbers are too large. Making them smaller and increasing the unit: if (m > 1000): while mult*m > 1000 and cur_unit <= 5: mult /= 1000 cur_unit += 1 return mult*times, self._unit_names[cur_unit] # nothing to do return times, self._unit
python
def rescale_around1(self, times): """ Suggests a rescaling factor and new physical time unit to balance the given time multiples around 1. Parameters ---------- times : float array array of times in multiple of the present elementary unit """ if self._unit == self._UNIT_STEP: return times, 'step' # nothing to do m = np.mean(times) mult = 1.0 cur_unit = self._unit # numbers are too small. Making them larger and reducing the unit: if (m < 0.001): while mult*m < 0.001 and cur_unit >= 0: mult *= 1000 cur_unit -= 1 return mult*times, self._unit_names[cur_unit] # numbers are too large. Making them smaller and increasing the unit: if (m > 1000): while mult*m > 1000 and cur_unit <= 5: mult /= 1000 cur_unit += 1 return mult*times, self._unit_names[cur_unit] # nothing to do return times, self._unit
[ "def", "rescale_around1", "(", "self", ",", "times", ")", ":", "if", "self", ".", "_unit", "==", "self", ".", "_UNIT_STEP", ":", "return", "times", ",", "'step'", "# nothing to do", "m", "=", "np", ".", "mean", "(", "times", ")", "mult", "=", "1.0", ...
Suggests a rescaling factor and new physical time unit to balance the given time multiples around 1. Parameters ---------- times : float array array of times in multiple of the present elementary unit
[ "Suggests", "a", "rescaling", "factor", "and", "new", "physical", "time", "unit", "to", "balance", "the", "given", "time", "multiples", "around", "1", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/units.py#L123-L155
train
204,123
markovmodel/PyEMMA
pyemma/_base/serialization/__init__.py
list_models
def list_models(filename): """ Lists all models in given filename. Parameters ---------- filename: str path to filename, where the model has been stored. Returns ------- obj: dict A mapping by name and a comprehensive description like this: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...} """ from .h5file import H5File with H5File(filename, mode='r') as f: return f.models_descriptive
python
def list_models(filename): """ Lists all models in given filename. Parameters ---------- filename: str path to filename, where the model has been stored. Returns ------- obj: dict A mapping by name and a comprehensive description like this: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...} """ from .h5file import H5File with H5File(filename, mode='r') as f: return f.models_descriptive
[ "def", "list_models", "(", "filename", ")", ":", "from", ".", "h5file", "import", "H5File", "with", "H5File", "(", "filename", ",", "mode", "=", "'r'", ")", "as", "f", ":", "return", "f", ".", "models_descriptive" ]
Lists all models in given filename. Parameters ---------- filename: str path to filename, where the model has been stored. Returns ------- obj: dict A mapping by name and a comprehensive description like this: {model_name: {'repr' : 'string representation, 'created': 'human readable date', ...}
[ "Lists", "all", "models", "in", "given", "filename", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/serialization/__init__.py#L22-L38
train
204,124
markovmodel/PyEMMA
pyemma/util/types.py
is_iterable_of_int
def is_iterable_of_int(l): r""" Checks if l is iterable and contains only integral types """ if not is_iterable(l): return False return all(is_int(value) for value in l)
python
def is_iterable_of_int(l): r""" Checks if l is iterable and contains only integral types """ if not is_iterable(l): return False return all(is_int(value) for value in l)
[ "def", "is_iterable_of_int", "(", "l", ")", ":", "if", "not", "is_iterable", "(", "l", ")", ":", "return", "False", "return", "all", "(", "is_int", "(", "value", ")", "for", "value", "in", "l", ")" ]
r""" Checks if l is iterable and contains only integral types
[ "r", "Checks", "if", "l", "is", "iterable", "and", "contains", "only", "integral", "types" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L46-L51
train
204,125
markovmodel/PyEMMA
pyemma/util/types.py
is_iterable_of_float
def is_iterable_of_float(l): r""" Checks if l is iterable and contains only floating point types """ if not is_iterable(l): return False return all(is_float(value) for value in l)
python
def is_iterable_of_float(l): r""" Checks if l is iterable and contains only floating point types """ if not is_iterable(l): return False return all(is_float(value) for value in l)
[ "def", "is_iterable_of_float", "(", "l", ")", ":", "if", "not", "is_iterable", "(", "l", ")", ":", "return", "False", "return", "all", "(", "is_float", "(", "value", ")", "for", "value", "in", "l", ")" ]
r""" Checks if l is iterable and contains only floating point types
[ "r", "Checks", "if", "l", "is", "iterable", "and", "contains", "only", "floating", "point", "types" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L66-L71
train
204,126
markovmodel/PyEMMA
pyemma/util/types.py
is_int_vector
def is_int_vector(l): r"""Checks if l is a numpy array of integers """ if isinstance(l, np.ndarray): if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'): return True return False
python
def is_int_vector(l): r"""Checks if l is a numpy array of integers """ if isinstance(l, np.ndarray): if l.ndim == 1 and (l.dtype.kind == 'i' or l.dtype.kind == 'u'): return True return False
[ "def", "is_int_vector", "(", "l", ")", ":", "if", "isinstance", "(", "l", ",", "np", ".", "ndarray", ")", ":", "if", "l", ".", "ndim", "==", "1", "and", "(", "l", ".", "dtype", ".", "kind", "==", "'i'", "or", "l", ".", "dtype", ".", "kind", "...
r"""Checks if l is a numpy array of integers
[ "r", "Checks", "if", "l", "is", "a", "numpy", "array", "of", "integers" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L85-L92
train
204,127
markovmodel/PyEMMA
pyemma/util/types.py
is_bool_matrix
def is_bool_matrix(l): r"""Checks if l is a 2D numpy array of bools """ if isinstance(l, np.ndarray): if l.ndim == 2 and (l.dtype == bool): return True return False
python
def is_bool_matrix(l): r"""Checks if l is a 2D numpy array of bools """ if isinstance(l, np.ndarray): if l.ndim == 2 and (l.dtype == bool): return True return False
[ "def", "is_bool_matrix", "(", "l", ")", ":", "if", "isinstance", "(", "l", ",", "np", ".", "ndarray", ")", ":", "if", "l", ".", "ndim", "==", "2", "and", "(", "l", ".", "dtype", "==", "bool", ")", ":", "return", "True", "return", "False" ]
r"""Checks if l is a 2D numpy array of bools
[ "r", "Checks", "if", "l", "is", "a", "2D", "numpy", "array", "of", "bools" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L121-L128
train
204,128
markovmodel/PyEMMA
pyemma/util/types.py
is_float_array
def is_float_array(l): r"""Checks if l is a numpy array of floats (any dimension """ if isinstance(l, np.ndarray): if l.dtype.kind == 'f': return True return False
python
def is_float_array(l): r"""Checks if l is a numpy array of floats (any dimension """ if isinstance(l, np.ndarray): if l.dtype.kind == 'f': return True return False
[ "def", "is_float_array", "(", "l", ")", ":", "if", "isinstance", "(", "l", ",", "np", ".", "ndarray", ")", ":", "if", "l", ".", "dtype", ".", "kind", "==", "'f'", ":", "return", "True", "return", "False" ]
r"""Checks if l is a numpy array of floats (any dimension
[ "r", "Checks", "if", "l", "is", "a", "numpy", "array", "of", "floats", "(", "any", "dimension" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L130-L137
train
204,129
markovmodel/PyEMMA
pyemma/util/types.py
ensure_int_vector
def ensure_int_vector(I, require_order = False): """Checks if the argument can be converted to an array of ints and does that. Parameters ---------- I: int or iterable of int require_order : bool If False (default), an unordered set is accepted. If True, a set is not accepted. Returns ------- arr : ndarray(n) numpy array with the integers contained in the argument """ if is_int_vector(I): return I elif is_int(I): return np.array([I]) elif is_list_of_int(I): return np.array(I) elif is_tuple_of_int(I): return np.array(I) elif isinstance(I, set): if require_order: raise TypeError('Argument is an unordered set, but I require an ordered array of integers') else: lI = list(I) if is_list_of_int(lI): return np.array(lI) else: raise TypeError('Argument is not of a type that is convertible to an array of integers.')
python
def ensure_int_vector(I, require_order = False): """Checks if the argument can be converted to an array of ints and does that. Parameters ---------- I: int or iterable of int require_order : bool If False (default), an unordered set is accepted. If True, a set is not accepted. Returns ------- arr : ndarray(n) numpy array with the integers contained in the argument """ if is_int_vector(I): return I elif is_int(I): return np.array([I]) elif is_list_of_int(I): return np.array(I) elif is_tuple_of_int(I): return np.array(I) elif isinstance(I, set): if require_order: raise TypeError('Argument is an unordered set, but I require an ordered array of integers') else: lI = list(I) if is_list_of_int(lI): return np.array(lI) else: raise TypeError('Argument is not of a type that is convertible to an array of integers.')
[ "def", "ensure_int_vector", "(", "I", ",", "require_order", "=", "False", ")", ":", "if", "is_int_vector", "(", "I", ")", ":", "return", "I", "elif", "is_int", "(", "I", ")", ":", "return", "np", ".", "array", "(", "[", "I", "]", ")", "elif", "is_l...
Checks if the argument can be converted to an array of ints and does that. Parameters ---------- I: int or iterable of int require_order : bool If False (default), an unordered set is accepted. If True, a set is not accepted. Returns ------- arr : ndarray(n) numpy array with the integers contained in the argument
[ "Checks", "if", "the", "argument", "can", "be", "converted", "to", "an", "array", "of", "ints", "and", "does", "that", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L180-L211
train
204,130
markovmodel/PyEMMA
pyemma/util/types.py
ensure_float_vector
def ensure_float_vector(F, require_order = False): """Ensures that F is a numpy array of floats If F is already a numpy array of floats, F is returned (no copied!) Otherwise, checks if the argument can be converted to an array of floats and does that. Parameters ---------- F: float, or iterable of float require_order : bool If False (default), an unordered set is accepted. If True, a set is not accepted. Returns ------- arr : ndarray(n) numpy array with the floats contained in the argument """ if is_float_vector(F): return F elif is_float(F): return np.array([F]) elif is_iterable_of_float(F): return np.array(F) elif isinstance(F, set): if require_order: raise TypeError('Argument is an unordered set, but I require an ordered array of floats') else: lF = list(F) if is_list_of_float(lF): return np.array(lF) else: raise TypeError('Argument is not of a type that is convertible to an array of floats.')
python
def ensure_float_vector(F, require_order = False): """Ensures that F is a numpy array of floats If F is already a numpy array of floats, F is returned (no copied!) Otherwise, checks if the argument can be converted to an array of floats and does that. Parameters ---------- F: float, or iterable of float require_order : bool If False (default), an unordered set is accepted. If True, a set is not accepted. Returns ------- arr : ndarray(n) numpy array with the floats contained in the argument """ if is_float_vector(F): return F elif is_float(F): return np.array([F]) elif is_iterable_of_float(F): return np.array(F) elif isinstance(F, set): if require_order: raise TypeError('Argument is an unordered set, but I require an ordered array of floats') else: lF = list(F) if is_list_of_float(lF): return np.array(lF) else: raise TypeError('Argument is not of a type that is convertible to an array of floats.')
[ "def", "ensure_float_vector", "(", "F", ",", "require_order", "=", "False", ")", ":", "if", "is_float_vector", "(", "F", ")", ":", "return", "F", "elif", "is_float", "(", "F", ")", ":", "return", "np", ".", "array", "(", "[", "F", "]", ")", "elif", ...
Ensures that F is a numpy array of floats If F is already a numpy array of floats, F is returned (no copied!) Otherwise, checks if the argument can be converted to an array of floats and does that. Parameters ---------- F: float, or iterable of float require_order : bool If False (default), an unordered set is accepted. If True, a set is not accepted. Returns ------- arr : ndarray(n) numpy array with the floats contained in the argument
[ "Ensures", "that", "F", "is", "a", "numpy", "array", "of", "floats" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L234-L266
train
204,131
markovmodel/PyEMMA
pyemma/util/types.py
ensure_dtype_float
def ensure_dtype_float(x, default=np.float64): r"""Makes sure that x is type of float """ if isinstance(x, np.ndarray): if x.dtype.kind == 'f': return x elif x.dtype.kind == 'i': return x.astype(default) else: raise TypeError('x is of type '+str(x.dtype)+' that cannot be converted to float') else: raise TypeError('x is not an array')
python
def ensure_dtype_float(x, default=np.float64): r"""Makes sure that x is type of float """ if isinstance(x, np.ndarray): if x.dtype.kind == 'f': return x elif x.dtype.kind == 'i': return x.astype(default) else: raise TypeError('x is of type '+str(x.dtype)+' that cannot be converted to float') else: raise TypeError('x is not an array')
[ "def", "ensure_dtype_float", "(", "x", ",", "default", "=", "np", ".", "float64", ")", ":", "if", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")", ":", "if", "x", ".", "dtype", ".", "kind", "==", "'f'", ":", "return", "x", "elif", "x", "."...
r"""Makes sure that x is type of float
[ "r", "Makes", "sure", "that", "x", "is", "type", "of", "float" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L289-L301
train
204,132
markovmodel/PyEMMA
pyemma/util/types.py
ensure_ndarray
def ensure_ndarray(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): r""" Ensures A is an ndarray and does an assert_array with the given parameters Returns ------- A : ndarray If A is already an ndarray, it is just returned. Otherwise this is an independent copy as an ndarray """ if not isinstance(A, np.ndarray): try: A = np.array(A) except: raise AssertionError('Given argument cannot be converted to an ndarray:\n'+str(A)) assert_array(A, shape=shape, uniform=uniform, ndim=ndim, size=size, dtype=dtype, kind=kind) return A
python
def ensure_ndarray(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): r""" Ensures A is an ndarray and does an assert_array with the given parameters Returns ------- A : ndarray If A is already an ndarray, it is just returned. Otherwise this is an independent copy as an ndarray """ if not isinstance(A, np.ndarray): try: A = np.array(A) except: raise AssertionError('Given argument cannot be converted to an ndarray:\n'+str(A)) assert_array(A, shape=shape, uniform=uniform, ndim=ndim, size=size, dtype=dtype, kind=kind) return A
[ "def", "ensure_ndarray", "(", "A", ",", "shape", "=", "None", ",", "uniform", "=", "None", ",", "ndim", "=", "None", ",", "size", "=", "None", ",", "dtype", "=", "None", ",", "kind", "=", "None", ")", ":", "if", "not", "isinstance", "(", "A", ","...
r""" Ensures A is an ndarray and does an assert_array with the given parameters Returns ------- A : ndarray If A is already an ndarray, it is just returned. Otherwise this is an independent copy as an ndarray
[ "r", "Ensures", "A", "is", "an", "ndarray", "and", "does", "an", "assert_array", "with", "the", "given", "parameters" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L405-L420
train
204,133
markovmodel/PyEMMA
pyemma/util/types.py
ensure_ndarray_or_sparse
def ensure_ndarray_or_sparse(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): r""" Ensures A is an ndarray or a scipy sparse matrix and does an assert_array with the given parameters Returns ------- A : ndarray If A is already an ndarray, it is just returned. Otherwise this is an independent copy as an ndarray """ if not isinstance(A, np.ndarray) and not scisp.issparse(A): try: A = np.array(A) except: raise AssertionError('Given argument cannot be converted to an ndarray:\n'+str(A)) assert_array(A, shape=shape, uniform=uniform, ndim=ndim, size=size, dtype=dtype, kind=kind) return A
python
def ensure_ndarray_or_sparse(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): r""" Ensures A is an ndarray or a scipy sparse matrix and does an assert_array with the given parameters Returns ------- A : ndarray If A is already an ndarray, it is just returned. Otherwise this is an independent copy as an ndarray """ if not isinstance(A, np.ndarray) and not scisp.issparse(A): try: A = np.array(A) except: raise AssertionError('Given argument cannot be converted to an ndarray:\n'+str(A)) assert_array(A, shape=shape, uniform=uniform, ndim=ndim, size=size, dtype=dtype, kind=kind) return A
[ "def", "ensure_ndarray_or_sparse", "(", "A", ",", "shape", "=", "None", ",", "uniform", "=", "None", ",", "ndim", "=", "None", ",", "size", "=", "None", ",", "dtype", "=", "None", ",", "kind", "=", "None", ")", ":", "if", "not", "isinstance", "(", ...
r""" Ensures A is an ndarray or a scipy sparse matrix and does an assert_array with the given parameters Returns ------- A : ndarray If A is already an ndarray, it is just returned. Otherwise this is an independent copy as an ndarray
[ "r", "Ensures", "A", "is", "an", "ndarray", "or", "a", "scipy", "sparse", "matrix", "and", "does", "an", "assert_array", "with", "the", "given", "parameters" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L422-L437
train
204,134
markovmodel/PyEMMA
pyemma/util/types.py
ensure_ndarray_or_None
def ensure_ndarray_or_None(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): r""" Ensures A is None or an ndarray and does an assert_array with the given parameters """ if A is not None: return ensure_ndarray(A, shape=shape, uniform=uniform, ndim=ndim, size=size, dtype=dtype, kind=kind) else: return None
python
def ensure_ndarray_or_None(A, shape=None, uniform=None, ndim=None, size=None, dtype=None, kind=None): r""" Ensures A is None or an ndarray and does an assert_array with the given parameters """ if A is not None: return ensure_ndarray(A, shape=shape, uniform=uniform, ndim=ndim, size=size, dtype=dtype, kind=kind) else: return None
[ "def", "ensure_ndarray_or_None", "(", "A", ",", "shape", "=", "None", ",", "uniform", "=", "None", ",", "ndim", "=", "None", ",", "size", "=", "None", ",", "dtype", "=", "None", ",", "kind", "=", "None", ")", ":", "if", "A", "is", "not", "None", ...
r""" Ensures A is None or an ndarray and does an assert_array with the given parameters
[ "r", "Ensures", "A", "is", "None", "or", "an", "ndarray", "and", "does", "an", "assert_array", "with", "the", "given", "parameters" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/types.py#L439-L444
train
204,135
markovmodel/PyEMMA
pyemma/coordinates/data/featurization/util.py
_describe_atom
def _describe_atom(topology, index): """ Returns a string describing the given atom :param topology: :param index: :return: """ at = topology.atom(index) if topology.n_chains > 1: return "%s %i %s %i %i" % (at.residue.name, at.residue.resSeq, at.name, at.index, at.residue.chain.index ) else: return "%s %i %s %i" % (at.residue.name, at.residue.resSeq, at.name, at.index)
python
def _describe_atom(topology, index): """ Returns a string describing the given atom :param topology: :param index: :return: """ at = topology.atom(index) if topology.n_chains > 1: return "%s %i %s %i %i" % (at.residue.name, at.residue.resSeq, at.name, at.index, at.residue.chain.index ) else: return "%s %i %s %i" % (at.residue.name, at.residue.resSeq, at.name, at.index)
[ "def", "_describe_atom", "(", "topology", ",", "index", ")", ":", "at", "=", "topology", ".", "atom", "(", "index", ")", "if", "topology", ".", "n_chains", ">", "1", ":", "return", "\"%s %i %s %i %i\"", "%", "(", "at", ".", "residue", ".", "name", ",",...
Returns a string describing the given atom :param topology: :param index: :return:
[ "Returns", "a", "string", "describing", "the", "given", "atom" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/featurization/util.py#L30-L42
train
204,136
markovmodel/PyEMMA
pyemma/_ext/sklearn/base.py
_first_and_last_element
def _first_and_last_element(arr): """Returns first and last element of numpy array or sparse matrix.""" if isinstance(arr, np.ndarray) or hasattr(arr, 'data'): # numpy array or sparse matrix with .data attribute data = arr.data if sparse.issparse(arr) else arr return data.flat[0], data.flat[-1] else: # Sparse matrices without .data attribute. Only dok_matrix at # the time of writing, in this case indexing is fast return arr[0, 0], arr[-1, -1]
python
def _first_and_last_element(arr): """Returns first and last element of numpy array or sparse matrix.""" if isinstance(arr, np.ndarray) or hasattr(arr, 'data'): # numpy array or sparse matrix with .data attribute data = arr.data if sparse.issparse(arr) else arr return data.flat[0], data.flat[-1] else: # Sparse matrices without .data attribute. Only dok_matrix at # the time of writing, in this case indexing is fast return arr[0, 0], arr[-1, -1]
[ "def", "_first_and_last_element", "(", "arr", ")", ":", "if", "isinstance", "(", "arr", ",", "np", ".", "ndarray", ")", "or", "hasattr", "(", "arr", ",", "'data'", ")", ":", "# numpy array or sparse matrix with .data attribute", "data", "=", "arr", ".", "data"...
Returns first and last element of numpy array or sparse matrix.
[ "Returns", "first", "and", "last", "element", "of", "numpy", "array", "or", "sparse", "matrix", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/sklearn/base.py#L27-L36
train
204,137
markovmodel/PyEMMA
pyemma/_ext/variational/estimators/running_moments.py
running_covar
def running_covar(xx=True, xy=False, yy=False, remove_mean=False, symmetrize=False, sparse_mode='auto', modify_data=False, column_selection=None, diag_only=False, nsave=5): """ Returns a running covariance estimator Returns an estimator object that can be fed chunks of X and Y data, and that can generate on-the-fly estimates of mean, covariance, running sum and second moment matrix. Parameters ---------- xx : bool Estimate the covariance of X xy : bool Estimate the cross-covariance of X and Y yy : bool Estimate the covariance of Y remove_mean : bool Remove the data mean in the covariance estimation symmetrize : bool Use symmetric estimates with sum defined by sum_t x_t + y_t and second moment matrices defined by X'X + Y'Y and Y'X + X'Y. modify_data : bool If remove_mean=True, the mean will be removed in the input data, without creating an independent copy. This option is faster but should only be selected if the input data is not used elsewhere. sparse_mode : str one of: * 'dense' : always use dense mode * 'sparse' : always use sparse mode if possible * 'auto' : automatic column_selection: ndarray(k, dtype=int) or None Indices of those columns that are to be computed. If None, all columns are computed. diag_only: bool If True, the computation is restricted to the diagonal entries (autocorrelations) only. nsave : int Depth of Moment storage. Moments computed from each chunk will be combined with Moments of similar statistical weight using the pairwise combination algorithm described in [1]_. References ---------- .. [1] http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf """ return RunningCovar(compute_XX=xx, compute_XY=xy, compute_YY=yy, sparse_mode=sparse_mode, modify_data=modify_data, remove_mean=remove_mean, symmetrize=symmetrize, column_selection=column_selection, diag_only=diag_only, nsave=nsave)
python
def running_covar(xx=True, xy=False, yy=False, remove_mean=False, symmetrize=False, sparse_mode='auto', modify_data=False, column_selection=None, diag_only=False, nsave=5): """ Returns a running covariance estimator Returns an estimator object that can be fed chunks of X and Y data, and that can generate on-the-fly estimates of mean, covariance, running sum and second moment matrix. Parameters ---------- xx : bool Estimate the covariance of X xy : bool Estimate the cross-covariance of X and Y yy : bool Estimate the covariance of Y remove_mean : bool Remove the data mean in the covariance estimation symmetrize : bool Use symmetric estimates with sum defined by sum_t x_t + y_t and second moment matrices defined by X'X + Y'Y and Y'X + X'Y. modify_data : bool If remove_mean=True, the mean will be removed in the input data, without creating an independent copy. This option is faster but should only be selected if the input data is not used elsewhere. sparse_mode : str one of: * 'dense' : always use dense mode * 'sparse' : always use sparse mode if possible * 'auto' : automatic column_selection: ndarray(k, dtype=int) or None Indices of those columns that are to be computed. If None, all columns are computed. diag_only: bool If True, the computation is restricted to the diagonal entries (autocorrelations) only. nsave : int Depth of Moment storage. Moments computed from each chunk will be combined with Moments of similar statistical weight using the pairwise combination algorithm described in [1]_. References ---------- .. [1] http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf """ return RunningCovar(compute_XX=xx, compute_XY=xy, compute_YY=yy, sparse_mode=sparse_mode, modify_data=modify_data, remove_mean=remove_mean, symmetrize=symmetrize, column_selection=column_selection, diag_only=diag_only, nsave=nsave)
[ "def", "running_covar", "(", "xx", "=", "True", ",", "xy", "=", "False", ",", "yy", "=", "False", ",", "remove_mean", "=", "False", ",", "symmetrize", "=", "False", ",", "sparse_mode", "=", "'auto'", ",", "modify_data", "=", "False", ",", "column_selecti...
Returns a running covariance estimator Returns an estimator object that can be fed chunks of X and Y data, and that can generate on-the-fly estimates of mean, covariance, running sum and second moment matrix. Parameters ---------- xx : bool Estimate the covariance of X xy : bool Estimate the cross-covariance of X and Y yy : bool Estimate the covariance of Y remove_mean : bool Remove the data mean in the covariance estimation symmetrize : bool Use symmetric estimates with sum defined by sum_t x_t + y_t and second moment matrices defined by X'X + Y'Y and Y'X + X'Y. modify_data : bool If remove_mean=True, the mean will be removed in the input data, without creating an independent copy. This option is faster but should only be selected if the input data is not used elsewhere. sparse_mode : str one of: * 'dense' : always use dense mode * 'sparse' : always use sparse mode if possible * 'auto' : automatic column_selection: ndarray(k, dtype=int) or None Indices of those columns that are to be computed. If None, all columns are computed. diag_only: bool If True, the computation is restricted to the diagonal entries (autocorrelations) only. nsave : int Depth of Moment storage. Moments computed from each chunk will be combined with Moments of similar statistical weight using the pairwise combination algorithm described in [1]_. References ---------- .. [1] http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf
[ "Returns", "a", "running", "covariance", "estimator" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/variational/estimators/running_moments.py#L370-L416
train
204,138
markovmodel/PyEMMA
pyemma/_ext/variational/estimators/running_moments.py
MomentsStorage._can_merge_tail
def _can_merge_tail(self): """ Checks if the two last list elements can be merged """ if len(self.storage) < 2: return False return self.storage[-2].w <= self.storage[-1].w * self.rtol
python
def _can_merge_tail(self): """ Checks if the two last list elements can be merged """ if len(self.storage) < 2: return False return self.storage[-2].w <= self.storage[-1].w * self.rtol
[ "def", "_can_merge_tail", "(", "self", ")", ":", "if", "len", "(", "self", ".", "storage", ")", "<", "2", ":", "return", "False", "return", "self", ".", "storage", "[", "-", "2", "]", ".", "w", "<=", "self", ".", "storage", "[", "-", "1", "]", ...
Checks if the two last list elements can be merged
[ "Checks", "if", "the", "two", "last", "list", "elements", "can", "be", "merged" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/variational/estimators/running_moments.py#L114-L119
train
204,139
markovmodel/PyEMMA
pyemma/_ext/variational/estimators/running_moments.py
MomentsStorage.store
def store(self, moments): """ Store object X with weight w """ if len(self.storage) == self.nsave: # merge if we must # print 'must merge' self.storage[-1].combine(moments, mean_free=self.remove_mean) else: # append otherwise # print 'append' self.storage.append(moments) # merge if possible while self._can_merge_tail(): # print 'merge: ',self.storage M = self.storage.pop() # print 'pop last: ',self.storage self.storage[-1].combine(M, mean_free=self.remove_mean)
python
def store(self, moments): """ Store object X with weight w """ if len(self.storage) == self.nsave: # merge if we must # print 'must merge' self.storage[-1].combine(moments, mean_free=self.remove_mean) else: # append otherwise # print 'append' self.storage.append(moments) # merge if possible while self._can_merge_tail(): # print 'merge: ',self.storage M = self.storage.pop() # print 'pop last: ',self.storage self.storage[-1].combine(M, mean_free=self.remove_mean)
[ "def", "store", "(", "self", ",", "moments", ")", ":", "if", "len", "(", "self", ".", "storage", ")", "==", "self", ".", "nsave", ":", "# merge if we must", "# print 'must merge'", "self", ".", "storage", "[", "-", "1", "]", ".", "combine", "(", "momen...
Store object X with weight w
[ "Store", "object", "X", "with", "weight", "w" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/variational/estimators/running_moments.py#L121-L135
train
204,140
markovmodel/PyEMMA
pyemma/msm/models/hmsm_sampled.py
SampledHMSM.submodel
def submodel(self, states=None, obs=None): """Returns a HMM with restricted state space Parameters ---------- states : None or int-array Hidden states to restrict the model to (if not None). obs : None, str or int-array Observed states to restrict the model to (if not None). Returns ------- hmm : HMM The restricted HMM. """ # get the reference HMM submodel ref = super(SampledHMSM, self).submodel(states=states, obs=obs) # get the sample submodels samples_sub = [sample.submodel(states=states, obs=obs) for sample in self.samples] # new model return SampledHMSM(samples_sub, ref=ref, conf=self.conf)
python
def submodel(self, states=None, obs=None): """Returns a HMM with restricted state space Parameters ---------- states : None or int-array Hidden states to restrict the model to (if not None). obs : None, str or int-array Observed states to restrict the model to (if not None). Returns ------- hmm : HMM The restricted HMM. """ # get the reference HMM submodel ref = super(SampledHMSM, self).submodel(states=states, obs=obs) # get the sample submodels samples_sub = [sample.submodel(states=states, obs=obs) for sample in self.samples] # new model return SampledHMSM(samples_sub, ref=ref, conf=self.conf)
[ "def", "submodel", "(", "self", ",", "states", "=", "None", ",", "obs", "=", "None", ")", ":", "# get the reference HMM submodel", "ref", "=", "super", "(", "SampledHMSM", ",", "self", ")", ".", "submodel", "(", "states", "=", "states", ",", "obs", "=", ...
Returns a HMM with restricted state space Parameters ---------- states : None or int-array Hidden states to restrict the model to (if not None). obs : None, str or int-array Observed states to restrict the model to (if not None). Returns ------- hmm : HMM The restricted HMM.
[ "Returns", "a", "HMM", "with", "restricted", "state", "space" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/models/hmsm_sampled.py#L56-L77
train
204,141
markovmodel/PyEMMA
pyemma/msm/estimators/implied_timescales.py
_generate_lags
def _generate_lags(maxlag, multiplier): r"""Generate a set of lag times starting from 1 to maxlag, using the given multiplier between successive lags """ # determine lag times lags = [1] # build default lag list lag = 1.0 import decimal while lag <= maxlag: lag = lag*multiplier # round up, like python 2 lag = int(decimal.Decimal(lag).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP)) if lag <= maxlag: ilag = int(lag) lags.append(ilag) # always include the maximal requested lag time. if maxlag not in lags: lags.append(maxlag) return np.array(lags)
python
def _generate_lags(maxlag, multiplier): r"""Generate a set of lag times starting from 1 to maxlag, using the given multiplier between successive lags """ # determine lag times lags = [1] # build default lag list lag = 1.0 import decimal while lag <= maxlag: lag = lag*multiplier # round up, like python 2 lag = int(decimal.Decimal(lag).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_HALF_UP)) if lag <= maxlag: ilag = int(lag) lags.append(ilag) # always include the maximal requested lag time. if maxlag not in lags: lags.append(maxlag) return np.array(lags)
[ "def", "_generate_lags", "(", "maxlag", ",", "multiplier", ")", ":", "# determine lag times", "lags", "=", "[", "1", "]", "# build default lag list", "lag", "=", "1.0", "import", "decimal", "while", "lag", "<=", "maxlag", ":", "lag", "=", "lag", "*", "multip...
r"""Generate a set of lag times starting from 1 to maxlag, using the given multiplier between successive lags
[ "r", "Generate", "a", "set", "of", "lag", "times", "starting", "from", "1", "to", "maxlag", "using", "the", "given", "multiplier", "between", "successive", "lags" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/estimators/implied_timescales.py#L47-L68
train
204,142
markovmodel/PyEMMA
pyemma/util/indices.py
combinations
def combinations(seq, k): """ Return j length subsequences of elements from the input iterable. This version uses Numpy/Scipy and should be preferred over itertools. It avoids the creation of all intermediate Python objects. Examples -------- >>> import numpy as np >>> from itertools import combinations as iter_comb >>> x = np.arange(3) >>> c1 = combinations(x, 2) >>> print(c1) [[0 1] [0 2] [1 2]] >>> c2 = np.array(tuple(iter_comb(x, 2))) >>> print(c2) [[0 1] [0 2] [1 2]] """ from itertools import combinations as _combinations, chain from scipy.special import comb count = comb(len(seq), k, exact=True) res = np.fromiter(chain.from_iterable(_combinations(seq, k)), int, count=count*k) return res.reshape(-1, k)
python
def combinations(seq, k): """ Return j length subsequences of elements from the input iterable. This version uses Numpy/Scipy and should be preferred over itertools. It avoids the creation of all intermediate Python objects. Examples -------- >>> import numpy as np >>> from itertools import combinations as iter_comb >>> x = np.arange(3) >>> c1 = combinations(x, 2) >>> print(c1) [[0 1] [0 2] [1 2]] >>> c2 = np.array(tuple(iter_comb(x, 2))) >>> print(c2) [[0 1] [0 2] [1 2]] """ from itertools import combinations as _combinations, chain from scipy.special import comb count = comb(len(seq), k, exact=True) res = np.fromiter(chain.from_iterable(_combinations(seq, k)), int, count=count*k) return res.reshape(-1, k)
[ "def", "combinations", "(", "seq", ",", "k", ")", ":", "from", "itertools", "import", "combinations", "as", "_combinations", ",", "chain", "from", "scipy", ".", "special", "import", "comb", "count", "=", "comb", "(", "len", "(", "seq", ")", ",", "k", "...
Return j length subsequences of elements from the input iterable. This version uses Numpy/Scipy and should be preferred over itertools. It avoids the creation of all intermediate Python objects. Examples -------- >>> import numpy as np >>> from itertools import combinations as iter_comb >>> x = np.arange(3) >>> c1 = combinations(x, 2) >>> print(c1) [[0 1] [0 2] [1 2]] >>> c2 = np.array(tuple(iter_comb(x, 2))) >>> print(c2) [[0 1] [0 2] [1 2]]
[ "Return", "j", "length", "subsequences", "of", "elements", "from", "the", "input", "iterable", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/indices.py#L22-L51
train
204,143
markovmodel/PyEMMA
pyemma/datasets/potentials.py
folding_model_energy
def folding_model_energy(rvec, rcut): r"""computes the potential energy at point rvec""" r = np.linalg.norm(rvec) - rcut rr = r ** 2 if r < 0.0: return -2.5 * rr return 0.5 * (r - 2.0) * rr
python
def folding_model_energy(rvec, rcut): r"""computes the potential energy at point rvec""" r = np.linalg.norm(rvec) - rcut rr = r ** 2 if r < 0.0: return -2.5 * rr return 0.5 * (r - 2.0) * rr
[ "def", "folding_model_energy", "(", "rvec", ",", "rcut", ")", ":", "r", "=", "np", ".", "linalg", ".", "norm", "(", "rvec", ")", "-", "rcut", "rr", "=", "r", "**", "2", "if", "r", "<", "0.0", ":", "return", "-", "2.5", "*", "rr", "return", "0.5...
r"""computes the potential energy at point rvec
[ "r", "computes", "the", "potential", "energy", "at", "point", "rvec" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/potentials.py#L76-L82
train
204,144
markovmodel/PyEMMA
pyemma/datasets/potentials.py
folding_model_gradient
def folding_model_gradient(rvec, rcut): r"""computes the potential's gradient at point rvec""" rnorm = np.linalg.norm(rvec) if rnorm == 0.0: return np.zeros(rvec.shape) r = rnorm - rcut if r < 0.0: return -5.0 * r * rvec / rnorm return (1.5 * r - 2.0) * rvec / rnorm
python
def folding_model_gradient(rvec, rcut): r"""computes the potential's gradient at point rvec""" rnorm = np.linalg.norm(rvec) if rnorm == 0.0: return np.zeros(rvec.shape) r = rnorm - rcut if r < 0.0: return -5.0 * r * rvec / rnorm return (1.5 * r - 2.0) * rvec / rnorm
[ "def", "folding_model_gradient", "(", "rvec", ",", "rcut", ")", ":", "rnorm", "=", "np", ".", "linalg", ".", "norm", "(", "rvec", ")", "if", "rnorm", "==", "0.0", ":", "return", "np", ".", "zeros", "(", "rvec", ".", "shape", ")", "r", "=", "rnorm",...
r"""computes the potential's gradient at point rvec
[ "r", "computes", "the", "potential", "s", "gradient", "at", "point", "rvec" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/potentials.py#L85-L93
train
204,145
markovmodel/PyEMMA
pyemma/datasets/potentials.py
get_asymmetric_double_well_data
def get_asymmetric_double_well_data(nstep, x0=0., nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0): r"""wrapper for the asymmetric double well generator""" adw = AsymmetricDoubleWell(dt, kT, mass=mass, damping=damping) return adw.sample(x0, nstep, nskip=nskip)
python
def get_asymmetric_double_well_data(nstep, x0=0., nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0): r"""wrapper for the asymmetric double well generator""" adw = AsymmetricDoubleWell(dt, kT, mass=mass, damping=damping) return adw.sample(x0, nstep, nskip=nskip)
[ "def", "get_asymmetric_double_well_data", "(", "nstep", ",", "x0", "=", "0.", ",", "nskip", "=", "1", ",", "dt", "=", "0.01", ",", "kT", "=", "10.0", ",", "mass", "=", "1.0", ",", "damping", "=", "1.0", ")", ":", "adw", "=", "AsymmetricDoubleWell", "...
r"""wrapper for the asymmetric double well generator
[ "r", "wrapper", "for", "the", "asymmetric", "double", "well", "generator" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/potentials.py#L171-L174
train
204,146
markovmodel/PyEMMA
pyemma/datasets/potentials.py
get_folding_model_data
def get_folding_model_data( nstep, rvec0=np.zeros((5)), nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0, rcut=3.0): r"""wrapper for the folding model generator""" fm = FoldingModel(dt, kT, mass=mass, damping=damping, rcut=rcut) return fm.sample(rvec0, nstep, nskip=nskip)
python
def get_folding_model_data( nstep, rvec0=np.zeros((5)), nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0, rcut=3.0): r"""wrapper for the folding model generator""" fm = FoldingModel(dt, kT, mass=mass, damping=damping, rcut=rcut) return fm.sample(rvec0, nstep, nskip=nskip)
[ "def", "get_folding_model_data", "(", "nstep", ",", "rvec0", "=", "np", ".", "zeros", "(", "(", "5", ")", ")", ",", "nskip", "=", "1", ",", "dt", "=", "0.01", ",", "kT", "=", "10.0", ",", "mass", "=", "1.0", ",", "damping", "=", "1.0", ",", "rc...
r"""wrapper for the folding model generator
[ "r", "wrapper", "for", "the", "folding", "model", "generator" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/potentials.py#L177-L181
train
204,147
markovmodel/PyEMMA
pyemma/datasets/potentials.py
get_prinz_pot
def get_prinz_pot(nstep, x0=0., nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0): r"""wrapper for the Prinz model generator""" pw = PrinzModel(dt, kT, mass=mass, damping=damping) return pw.sample(x0, nstep, nskip=nskip)
python
def get_prinz_pot(nstep, x0=0., nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0): r"""wrapper for the Prinz model generator""" pw = PrinzModel(dt, kT, mass=mass, damping=damping) return pw.sample(x0, nstep, nskip=nskip)
[ "def", "get_prinz_pot", "(", "nstep", ",", "x0", "=", "0.", ",", "nskip", "=", "1", ",", "dt", "=", "0.01", ",", "kT", "=", "10.0", ",", "mass", "=", "1.0", ",", "damping", "=", "1.0", ")", ":", "pw", "=", "PrinzModel", "(", "dt", ",", "kT", ...
r"""wrapper for the Prinz model generator
[ "r", "wrapper", "for", "the", "Prinz", "model", "generator" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/potentials.py#L184-L187
train
204,148
markovmodel/PyEMMA
pyemma/datasets/potentials.py
BrownianDynamics.step
def step(self, x): r"""perform a single Brownian dynamics step""" return x - self.coeff_A * self.gradient(x) \ + self.coeff_B * np.random.normal(size=self.dim)
python
def step(self, x): r"""perform a single Brownian dynamics step""" return x - self.coeff_A * self.gradient(x) \ + self.coeff_B * np.random.normal(size=self.dim)
[ "def", "step", "(", "self", ",", "x", ")", ":", "return", "x", "-", "self", ".", "coeff_A", "*", "self", ".", "gradient", "(", "x", ")", "+", "self", ".", "coeff_B", "*", "np", ".", "random", ".", "normal", "(", "size", "=", "self", ".", "dim",...
r"""perform a single Brownian dynamics step
[ "r", "perform", "a", "single", "Brownian", "dynamics", "step" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/datasets/potentials.py#L42-L45
train
204,149
markovmodel/PyEMMA
pyemma/plots/networks.py
plot_markov_model
def plot_markov_model( P, pos=None, state_sizes=None, state_scale=1.0, state_colors='#ff5500', state_labels='auto', minflux=1e-6, arrow_scale=1.0, arrow_curvature=1.0, arrow_labels='weights', arrow_label_format='%2.e', max_width=12, max_height=12, figpadding=0.2, show_frame=False, ax=None, **textkwargs): r"""Network representation of MSM transition matrix This visualization is not optimized for large matrices. It is meant to be used for the visualization of small models with up to 10-20 states, e.g. obtained by a HMM coarse-graining. If used with large network, the automatic node positioning will be very slow and may still look ugly. Parameters ---------- P : ndarray(n,n) or MSM object with attribute 'transition matrix' Transition matrix or MSM object pos : ndarray(n,2), optional, default=None User-defined positions to draw the states on. If not given, will try to place them automatically. state_sizes : ndarray(n), optional, default=None User-defined areas of the discs drawn for each state. If not given, the stationary probability of P will be used. state_colors : string, ndarray(n), or list, optional, default='#ff5500' (orange) string : a Hex code for a single color used for all states array : n values in [0,1] which will result in a grayscale plot list : of len = nstates, with a color for each state. The list can mix strings, RGB values and hex codes, e.g. :py:obj:`state_colors` = ['g', 'red', [.23, .34, .35], '#ff5500'] is possible. state_labels : list of strings, optional, default is 'auto' A list with a label for each state, to be displayed at the center of each node/state. If left to 'auto', the labels are automatically set to the state indices. minflux : float, optional, default=1e-6 The minimal flux (p_i * p_ij) for a transition to be drawn arrow_scale : float, optional, default=1.0 Relative arrow scale. Set to a value different from 1 to increase or decrease the arrow width. arrow_curvature : float, optional, default=1.0 Relative arrow curvature. Set to a value different from 1 to make arrows more or less curved. arrow_labels : 'weights', None or a ndarray(n,n) with label strings. Optional, default='weights' Strings to be placed upon arrows. If None, no labels will be used. If 'weights', the elements of P will be used. If a matrix of strings is given by the user these will be used. arrow_label_format : str, optional, default='%10.2f' The numeric format to print the arrow labels max_width = 12 The maximum figure width max_height = 12 The maximum figure height figpadding = 0.2 The relative figure size used for the padding show_frame: boolean (default=False) Draw a frame around the network. ax : matplotlib Axes object, optional, default=None The axes to plot to. When set to None a new Axes (and Figure) object will be used. textkwargs : optional argument for the text of the state and arrow labels. See http://matplotlib.org/api/text_api.html#matplotlib.text.Text for more info. The parameter 'size' refers to the size of the state and arrow labels and overwrites the matplotlib default. The parameter 'arrow_label_size' is only used for the arrow labels; please note that 'arrow_label_size' is not part of matplotlib.text.Text's set of parameters and will raise an exception when passed to matplotlib.text.Text directly. Returns ------- fig, pos : matplotlib.Figure, ndarray(n,2) a Figure object containing the plot and the positions of states. Can be used later to plot a different network representation (e.g. the flux) Examples -------- >>> import numpy as np >>> P = np.array([[0.8, 0.15, 0.05, 0.0, 0.0], ... [0.1, 0.75, 0.05, 0.05, 0.05], ... [0.05, 0.1, 0.8, 0.0, 0.05], ... [0.0, 0.2, 0.0, 0.8, 0.0], ... [0.0, 0.02, 0.02, 0.0, 0.96]]) >>> plot_markov_model(P) # doctest:+ELLIPSIS (<...Figure..., array...) """ from msmtools import analysis as msmana if isinstance(P, _np.ndarray): P = P.copy() else: # MSM object? then get transition matrix first P = P.transition_matrix.copy() if state_sizes is None: state_sizes = msmana.stationary_distribution(P) if minflux > 0: F = _np.dot(_np.diag(msmana.stationary_distribution(P)), P) I, J = _np.where(F < minflux) P[I, J] = 0.0 plot = NetworkPlot(P, pos=pos, ax=ax) fig = plot.plot_network( state_sizes=state_sizes, state_scale=state_scale, state_colors=state_colors, state_labels=state_labels, arrow_scale=arrow_scale, arrow_curvature=arrow_curvature, arrow_labels=arrow_labels, arrow_label_format=arrow_label_format, max_width=max_width, max_height=max_height, figpadding=figpadding, xticks=False, yticks=False, show_frame=show_frame, **textkwargs) return fig, plot.pos
python
def plot_markov_model( P, pos=None, state_sizes=None, state_scale=1.0, state_colors='#ff5500', state_labels='auto', minflux=1e-6, arrow_scale=1.0, arrow_curvature=1.0, arrow_labels='weights', arrow_label_format='%2.e', max_width=12, max_height=12, figpadding=0.2, show_frame=False, ax=None, **textkwargs): r"""Network representation of MSM transition matrix This visualization is not optimized for large matrices. It is meant to be used for the visualization of small models with up to 10-20 states, e.g. obtained by a HMM coarse-graining. If used with large network, the automatic node positioning will be very slow and may still look ugly. Parameters ---------- P : ndarray(n,n) or MSM object with attribute 'transition matrix' Transition matrix or MSM object pos : ndarray(n,2), optional, default=None User-defined positions to draw the states on. If not given, will try to place them automatically. state_sizes : ndarray(n), optional, default=None User-defined areas of the discs drawn for each state. If not given, the stationary probability of P will be used. state_colors : string, ndarray(n), or list, optional, default='#ff5500' (orange) string : a Hex code for a single color used for all states array : n values in [0,1] which will result in a grayscale plot list : of len = nstates, with a color for each state. The list can mix strings, RGB values and hex codes, e.g. :py:obj:`state_colors` = ['g', 'red', [.23, .34, .35], '#ff5500'] is possible. state_labels : list of strings, optional, default is 'auto' A list with a label for each state, to be displayed at the center of each node/state. If left to 'auto', the labels are automatically set to the state indices. minflux : float, optional, default=1e-6 The minimal flux (p_i * p_ij) for a transition to be drawn arrow_scale : float, optional, default=1.0 Relative arrow scale. Set to a value different from 1 to increase or decrease the arrow width. arrow_curvature : float, optional, default=1.0 Relative arrow curvature. Set to a value different from 1 to make arrows more or less curved. arrow_labels : 'weights', None or a ndarray(n,n) with label strings. Optional, default='weights' Strings to be placed upon arrows. If None, no labels will be used. If 'weights', the elements of P will be used. If a matrix of strings is given by the user these will be used. arrow_label_format : str, optional, default='%10.2f' The numeric format to print the arrow labels max_width = 12 The maximum figure width max_height = 12 The maximum figure height figpadding = 0.2 The relative figure size used for the padding show_frame: boolean (default=False) Draw a frame around the network. ax : matplotlib Axes object, optional, default=None The axes to plot to. When set to None a new Axes (and Figure) object will be used. textkwargs : optional argument for the text of the state and arrow labels. See http://matplotlib.org/api/text_api.html#matplotlib.text.Text for more info. The parameter 'size' refers to the size of the state and arrow labels and overwrites the matplotlib default. The parameter 'arrow_label_size' is only used for the arrow labels; please note that 'arrow_label_size' is not part of matplotlib.text.Text's set of parameters and will raise an exception when passed to matplotlib.text.Text directly. Returns ------- fig, pos : matplotlib.Figure, ndarray(n,2) a Figure object containing the plot and the positions of states. Can be used later to plot a different network representation (e.g. the flux) Examples -------- >>> import numpy as np >>> P = np.array([[0.8, 0.15, 0.05, 0.0, 0.0], ... [0.1, 0.75, 0.05, 0.05, 0.05], ... [0.05, 0.1, 0.8, 0.0, 0.05], ... [0.0, 0.2, 0.0, 0.8, 0.0], ... [0.0, 0.02, 0.02, 0.0, 0.96]]) >>> plot_markov_model(P) # doctest:+ELLIPSIS (<...Figure..., array...) """ from msmtools import analysis as msmana if isinstance(P, _np.ndarray): P = P.copy() else: # MSM object? then get transition matrix first P = P.transition_matrix.copy() if state_sizes is None: state_sizes = msmana.stationary_distribution(P) if minflux > 0: F = _np.dot(_np.diag(msmana.stationary_distribution(P)), P) I, J = _np.where(F < minflux) P[I, J] = 0.0 plot = NetworkPlot(P, pos=pos, ax=ax) fig = plot.plot_network( state_sizes=state_sizes, state_scale=state_scale, state_colors=state_colors, state_labels=state_labels, arrow_scale=arrow_scale, arrow_curvature=arrow_curvature, arrow_labels=arrow_labels, arrow_label_format=arrow_label_format, max_width=max_width, max_height=max_height, figpadding=figpadding, xticks=False, yticks=False, show_frame=show_frame, **textkwargs) return fig, plot.pos
[ "def", "plot_markov_model", "(", "P", ",", "pos", "=", "None", ",", "state_sizes", "=", "None", ",", "state_scale", "=", "1.0", ",", "state_colors", "=", "'#ff5500'", ",", "state_labels", "=", "'auto'", ",", "minflux", "=", "1e-6", ",", "arrow_scale", "=",...
r"""Network representation of MSM transition matrix This visualization is not optimized for large matrices. It is meant to be used for the visualization of small models with up to 10-20 states, e.g. obtained by a HMM coarse-graining. If used with large network, the automatic node positioning will be very slow and may still look ugly. Parameters ---------- P : ndarray(n,n) or MSM object with attribute 'transition matrix' Transition matrix or MSM object pos : ndarray(n,2), optional, default=None User-defined positions to draw the states on. If not given, will try to place them automatically. state_sizes : ndarray(n), optional, default=None User-defined areas of the discs drawn for each state. If not given, the stationary probability of P will be used. state_colors : string, ndarray(n), or list, optional, default='#ff5500' (orange) string : a Hex code for a single color used for all states array : n values in [0,1] which will result in a grayscale plot list : of len = nstates, with a color for each state. The list can mix strings, RGB values and hex codes, e.g. :py:obj:`state_colors` = ['g', 'red', [.23, .34, .35], '#ff5500'] is possible. state_labels : list of strings, optional, default is 'auto' A list with a label for each state, to be displayed at the center of each node/state. If left to 'auto', the labels are automatically set to the state indices. minflux : float, optional, default=1e-6 The minimal flux (p_i * p_ij) for a transition to be drawn arrow_scale : float, optional, default=1.0 Relative arrow scale. Set to a value different from 1 to increase or decrease the arrow width. arrow_curvature : float, optional, default=1.0 Relative arrow curvature. Set to a value different from 1 to make arrows more or less curved. arrow_labels : 'weights', None or a ndarray(n,n) with label strings. Optional, default='weights' Strings to be placed upon arrows. If None, no labels will be used. If 'weights', the elements of P will be used. If a matrix of strings is given by the user these will be used. arrow_label_format : str, optional, default='%10.2f' The numeric format to print the arrow labels max_width = 12 The maximum figure width max_height = 12 The maximum figure height figpadding = 0.2 The relative figure size used for the padding show_frame: boolean (default=False) Draw a frame around the network. ax : matplotlib Axes object, optional, default=None The axes to plot to. When set to None a new Axes (and Figure) object will be used. textkwargs : optional argument for the text of the state and arrow labels. See http://matplotlib.org/api/text_api.html#matplotlib.text.Text for more info. The parameter 'size' refers to the size of the state and arrow labels and overwrites the matplotlib default. The parameter 'arrow_label_size' is only used for the arrow labels; please note that 'arrow_label_size' is not part of matplotlib.text.Text's set of parameters and will raise an exception when passed to matplotlib.text.Text directly. Returns ------- fig, pos : matplotlib.Figure, ndarray(n,2) a Figure object containing the plot and the positions of states. Can be used later to plot a different network representation (e.g. the flux) Examples -------- >>> import numpy as np >>> P = np.array([[0.8, 0.15, 0.05, 0.0, 0.0], ... [0.1, 0.75, 0.05, 0.05, 0.05], ... [0.05, 0.1, 0.8, 0.0, 0.05], ... [0.0, 0.2, 0.0, 0.8, 0.0], ... [0.0, 0.02, 0.02, 0.0, 0.96]]) >>> plot_markov_model(P) # doctest:+ELLIPSIS (<...Figure..., array...)
[ "r", "Network", "representation", "of", "MSM", "transition", "matrix" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/plots/networks.py#L334-L437
train
204,150
markovmodel/PyEMMA
pyemma/plots/networks.py
plot_flux
def plot_flux( flux, pos=None, state_sizes=None, flux_scale=1.0, state_scale=1.0, state_colors='#ff5500', state_labels='auto', minflux=1e-9, arrow_scale=1.0, arrow_curvature=1.0, arrow_labels='weights', arrow_label_format='%2.e', max_width=12, max_height=12, figpadding=0.2, attribute_to_plot='net_flux', show_frame=False, show_committor=True, ax=None, **textkwargs): r"""Network representation of reactive flux This visualization is not optimized for large fluxes. It is meant to be used for the visualization of small models with up to 10-20 states, e.g. obtained by a PCCA-based coarse-graining of the full flux. If used with large network, the automatic node positioning will be very slow and may still look ugly. Parameters ---------- flux : :class:`ReactiveFlux <pyemma.msm.flux.ReactiveFlux>` reactive flux object pos : ndarray(n,2), optional, default=None User-defined positions to draw the states on. If not given, will set the x coordinates equal to the committor probability and try to place the y coordinates automatically state_sizes : ndarray(n), optional, default=None User-defined areas of the discs drawn for each state. If not given, the stationary probability of P will be used flux_scale : float, optional, default=1.0 scaling of the flux values state_scale : float, optional, default=1.0 scaling of the state circles state_colors : string, ndarray(n), or list, optional, default='#ff5500' (orange) string : a Hex code for a single color used for all states array : n values in [0,1] which will result in a grayscale plot list : of len = nstates, with a color for each state. The list can mix strings, RGB values and hex codes, e.g. :py:obj:`state_colors` = ['g', 'red', [.23, .34, .35], '#ff5500'] is possible. state_labels : list of strings, optional, default is 'auto' A list with a label for each state, to be displayed at the center of each node/state. If left to 'auto', the labels are automatically set to the state indices. minflux : float, optional, default=1e-9 The minimal flux for a transition to be drawn arrow_scale : float, optional, default=1.0 Relative arrow scale. Set to a value different from 1 to increase or decrease the arrow width. arrow_curvature : float, optional, default=1.0 Relative arrow curvature. Set to a value different from 1 to make arrows more or less curved. arrow_labels : 'weights', None or a ndarray(n,n) with label strings. Optional, default='weights' Strings to be placed upon arrows. If None, no labels will be used. If 'weights', the elements of P will be used. If a matrix of strings is given by the user these will be used. arrow_label_format : str, optional, default='%10.2f' The numeric format to print the arrow labels max_width : int (default = 12) The maximum figure width max_height: int (default = 12) The maximum figure height figpadding: float (default = 0.2) The relative figure size used for the padding attribute_to_plot : str, optional, default='net_flux' specify the attribute of the flux object to plot. show_frame: boolean (default=False) Draw a frame around the network. show_committor: boolean (default=False) Print the committor value on the x-axis. ax : matplotlib Axes object, optional, default=None The axes to plot to. When set to None a new Axes (and Figure) object will be used. textkwargs : optional argument for the text of the state and arrow labels. See http://matplotlib.org/api/text_api.html#matplotlib.text.Text for more info. The parameter 'size' refers to the size of the state and arrow labels and overwrites the matplotlib default. The parameter 'arrow_label_size' is only used for the arrow labels; please note that 'arrow_label_size' is not part of matplotlib.text.Text's set of parameters and will raise an exception when passed to matplotlib.text.Text directly. Returns ------- (fig, pos) : matpotlib.Figure instance, ndarray Axes instances containing the plot. Use pyplot.show() to display it. The positions of states. Can be used later to plot a different network representation (e.g. the flux). Examples -------- We define first define a reactive flux by taking the following transition matrix and computing TPT from state 2 to 3 >>> import numpy as np >>> P = np.array([[0.8, 0.15, 0.05, 0.0, 0.0], ... [0.1, 0.75, 0.05, 0.05, 0.05], ... [0.05, 0.1, 0.8, 0.0, 0.05], ... [0.0, 0.2, 0.0, 0.8, 0.0], ... [0.0, 0.02, 0.02, 0.0, 0.96]]) >>> from pyemma import msm >>> F = msm.tpt(msm.markov_model(P), [2], [3]) >>> F.flux[:] *= 100 Scale the flux by 100 is basically a change of units to get numbers close to 1 (avoid printing many zeros). Now we visualize the flux: >>> plot_flux(F) # doctest:+ELLIPSIS (<...Figure..., array...) """ from matplotlib import pylab as plt F = flux_scale * getattr(flux, attribute_to_plot) c = flux.committor if state_sizes is None: state_sizes = flux.stationary_distribution plot = NetworkPlot(F, pos=pos, xpos=c, ax=ax) if minflux > 0: I, J = _np.where(F < minflux) F[I, J] = 0.0 if isinstance(state_labels, str) and state_labels == 'auto': # the first and last element correspond to A and B in ReactiveFlux state_labels = _np.array([str(i) for i in range(flux.nstates)]) state_labels[_np.array(flux.A)] = "A" state_labels[_np.array(flux.B)] = "B" elif isinstance(state_labels, (_np.ndarray, list, tuple)): if len(state_labels) != flux.nstates: raise ValueError("length of state_labels({}) has to match length of states({})." .format(len(state_labels), flux.nstates)) fig = plot.plot_network( state_sizes=state_sizes, state_scale=state_scale, state_colors=state_colors, state_labels=state_labels, arrow_scale=arrow_scale, arrow_curvature=arrow_curvature, arrow_labels=arrow_labels, arrow_label_format=arrow_label_format, max_width=max_width, max_height=max_height, figpadding=figpadding, xticks=show_committor, yticks=False, show_frame=show_frame, **textkwargs) if show_committor: plt.xlabel('Committor probability') return fig, plot.pos
python
def plot_flux( flux, pos=None, state_sizes=None, flux_scale=1.0, state_scale=1.0, state_colors='#ff5500', state_labels='auto', minflux=1e-9, arrow_scale=1.0, arrow_curvature=1.0, arrow_labels='weights', arrow_label_format='%2.e', max_width=12, max_height=12, figpadding=0.2, attribute_to_plot='net_flux', show_frame=False, show_committor=True, ax=None, **textkwargs): r"""Network representation of reactive flux This visualization is not optimized for large fluxes. It is meant to be used for the visualization of small models with up to 10-20 states, e.g. obtained by a PCCA-based coarse-graining of the full flux. If used with large network, the automatic node positioning will be very slow and may still look ugly. Parameters ---------- flux : :class:`ReactiveFlux <pyemma.msm.flux.ReactiveFlux>` reactive flux object pos : ndarray(n,2), optional, default=None User-defined positions to draw the states on. If not given, will set the x coordinates equal to the committor probability and try to place the y coordinates automatically state_sizes : ndarray(n), optional, default=None User-defined areas of the discs drawn for each state. If not given, the stationary probability of P will be used flux_scale : float, optional, default=1.0 scaling of the flux values state_scale : float, optional, default=1.0 scaling of the state circles state_colors : string, ndarray(n), or list, optional, default='#ff5500' (orange) string : a Hex code for a single color used for all states array : n values in [0,1] which will result in a grayscale plot list : of len = nstates, with a color for each state. The list can mix strings, RGB values and hex codes, e.g. :py:obj:`state_colors` = ['g', 'red', [.23, .34, .35], '#ff5500'] is possible. state_labels : list of strings, optional, default is 'auto' A list with a label for each state, to be displayed at the center of each node/state. If left to 'auto', the labels are automatically set to the state indices. minflux : float, optional, default=1e-9 The minimal flux for a transition to be drawn arrow_scale : float, optional, default=1.0 Relative arrow scale. Set to a value different from 1 to increase or decrease the arrow width. arrow_curvature : float, optional, default=1.0 Relative arrow curvature. Set to a value different from 1 to make arrows more or less curved. arrow_labels : 'weights', None or a ndarray(n,n) with label strings. Optional, default='weights' Strings to be placed upon arrows. If None, no labels will be used. If 'weights', the elements of P will be used. If a matrix of strings is given by the user these will be used. arrow_label_format : str, optional, default='%10.2f' The numeric format to print the arrow labels max_width : int (default = 12) The maximum figure width max_height: int (default = 12) The maximum figure height figpadding: float (default = 0.2) The relative figure size used for the padding attribute_to_plot : str, optional, default='net_flux' specify the attribute of the flux object to plot. show_frame: boolean (default=False) Draw a frame around the network. show_committor: boolean (default=False) Print the committor value on the x-axis. ax : matplotlib Axes object, optional, default=None The axes to plot to. When set to None a new Axes (and Figure) object will be used. textkwargs : optional argument for the text of the state and arrow labels. See http://matplotlib.org/api/text_api.html#matplotlib.text.Text for more info. The parameter 'size' refers to the size of the state and arrow labels and overwrites the matplotlib default. The parameter 'arrow_label_size' is only used for the arrow labels; please note that 'arrow_label_size' is not part of matplotlib.text.Text's set of parameters and will raise an exception when passed to matplotlib.text.Text directly. Returns ------- (fig, pos) : matpotlib.Figure instance, ndarray Axes instances containing the plot. Use pyplot.show() to display it. The positions of states. Can be used later to plot a different network representation (e.g. the flux). Examples -------- We define first define a reactive flux by taking the following transition matrix and computing TPT from state 2 to 3 >>> import numpy as np >>> P = np.array([[0.8, 0.15, 0.05, 0.0, 0.0], ... [0.1, 0.75, 0.05, 0.05, 0.05], ... [0.05, 0.1, 0.8, 0.0, 0.05], ... [0.0, 0.2, 0.0, 0.8, 0.0], ... [0.0, 0.02, 0.02, 0.0, 0.96]]) >>> from pyemma import msm >>> F = msm.tpt(msm.markov_model(P), [2], [3]) >>> F.flux[:] *= 100 Scale the flux by 100 is basically a change of units to get numbers close to 1 (avoid printing many zeros). Now we visualize the flux: >>> plot_flux(F) # doctest:+ELLIPSIS (<...Figure..., array...) """ from matplotlib import pylab as plt F = flux_scale * getattr(flux, attribute_to_plot) c = flux.committor if state_sizes is None: state_sizes = flux.stationary_distribution plot = NetworkPlot(F, pos=pos, xpos=c, ax=ax) if minflux > 0: I, J = _np.where(F < minflux) F[I, J] = 0.0 if isinstance(state_labels, str) and state_labels == 'auto': # the first and last element correspond to A and B in ReactiveFlux state_labels = _np.array([str(i) for i in range(flux.nstates)]) state_labels[_np.array(flux.A)] = "A" state_labels[_np.array(flux.B)] = "B" elif isinstance(state_labels, (_np.ndarray, list, tuple)): if len(state_labels) != flux.nstates: raise ValueError("length of state_labels({}) has to match length of states({})." .format(len(state_labels), flux.nstates)) fig = plot.plot_network( state_sizes=state_sizes, state_scale=state_scale, state_colors=state_colors, state_labels=state_labels, arrow_scale=arrow_scale, arrow_curvature=arrow_curvature, arrow_labels=arrow_labels, arrow_label_format=arrow_label_format, max_width=max_width, max_height=max_height, figpadding=figpadding, xticks=show_committor, yticks=False, show_frame=show_frame, **textkwargs) if show_committor: plt.xlabel('Committor probability') return fig, plot.pos
[ "def", "plot_flux", "(", "flux", ",", "pos", "=", "None", ",", "state_sizes", "=", "None", ",", "flux_scale", "=", "1.0", ",", "state_scale", "=", "1.0", ",", "state_colors", "=", "'#ff5500'", ",", "state_labels", "=", "'auto'", ",", "minflux", "=", "1e-...
r"""Network representation of reactive flux This visualization is not optimized for large fluxes. It is meant to be used for the visualization of small models with up to 10-20 states, e.g. obtained by a PCCA-based coarse-graining of the full flux. If used with large network, the automatic node positioning will be very slow and may still look ugly. Parameters ---------- flux : :class:`ReactiveFlux <pyemma.msm.flux.ReactiveFlux>` reactive flux object pos : ndarray(n,2), optional, default=None User-defined positions to draw the states on. If not given, will set the x coordinates equal to the committor probability and try to place the y coordinates automatically state_sizes : ndarray(n), optional, default=None User-defined areas of the discs drawn for each state. If not given, the stationary probability of P will be used flux_scale : float, optional, default=1.0 scaling of the flux values state_scale : float, optional, default=1.0 scaling of the state circles state_colors : string, ndarray(n), or list, optional, default='#ff5500' (orange) string : a Hex code for a single color used for all states array : n values in [0,1] which will result in a grayscale plot list : of len = nstates, with a color for each state. The list can mix strings, RGB values and hex codes, e.g. :py:obj:`state_colors` = ['g', 'red', [.23, .34, .35], '#ff5500'] is possible. state_labels : list of strings, optional, default is 'auto' A list with a label for each state, to be displayed at the center of each node/state. If left to 'auto', the labels are automatically set to the state indices. minflux : float, optional, default=1e-9 The minimal flux for a transition to be drawn arrow_scale : float, optional, default=1.0 Relative arrow scale. Set to a value different from 1 to increase or decrease the arrow width. arrow_curvature : float, optional, default=1.0 Relative arrow curvature. Set to a value different from 1 to make arrows more or less curved. arrow_labels : 'weights', None or a ndarray(n,n) with label strings. Optional, default='weights' Strings to be placed upon arrows. If None, no labels will be used. If 'weights', the elements of P will be used. If a matrix of strings is given by the user these will be used. arrow_label_format : str, optional, default='%10.2f' The numeric format to print the arrow labels max_width : int (default = 12) The maximum figure width max_height: int (default = 12) The maximum figure height figpadding: float (default = 0.2) The relative figure size used for the padding attribute_to_plot : str, optional, default='net_flux' specify the attribute of the flux object to plot. show_frame: boolean (default=False) Draw a frame around the network. show_committor: boolean (default=False) Print the committor value on the x-axis. ax : matplotlib Axes object, optional, default=None The axes to plot to. When set to None a new Axes (and Figure) object will be used. textkwargs : optional argument for the text of the state and arrow labels. See http://matplotlib.org/api/text_api.html#matplotlib.text.Text for more info. The parameter 'size' refers to the size of the state and arrow labels and overwrites the matplotlib default. The parameter 'arrow_label_size' is only used for the arrow labels; please note that 'arrow_label_size' is not part of matplotlib.text.Text's set of parameters and will raise an exception when passed to matplotlib.text.Text directly. Returns ------- (fig, pos) : matpotlib.Figure instance, ndarray Axes instances containing the plot. Use pyplot.show() to display it. The positions of states. Can be used later to plot a different network representation (e.g. the flux). Examples -------- We define first define a reactive flux by taking the following transition matrix and computing TPT from state 2 to 3 >>> import numpy as np >>> P = np.array([[0.8, 0.15, 0.05, 0.0, 0.0], ... [0.1, 0.75, 0.05, 0.05, 0.05], ... [0.05, 0.1, 0.8, 0.0, 0.05], ... [0.0, 0.2, 0.0, 0.8, 0.0], ... [0.0, 0.02, 0.02, 0.0, 0.96]]) >>> from pyemma import msm >>> F = msm.tpt(msm.markov_model(P), [2], [3]) >>> F.flux[:] *= 100 Scale the flux by 100 is basically a change of units to get numbers close to 1 (avoid printing many zeros). Now we visualize the flux: >>> plot_flux(F) # doctest:+ELLIPSIS (<...Figure..., array...)
[ "r", "Network", "representation", "of", "reactive", "flux" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/plots/networks.py#L440-L574
train
204,151
markovmodel/PyEMMA
pyemma/plots/networks.py
plot_network
def plot_network( weights, pos=None, xpos=None, ypos=None, state_sizes=None, state_scale=1.0, state_colors='#ff5500', state_labels='auto', arrow_scale=1.0, arrow_curvature=1.0, arrow_labels='weights', arrow_label_format='%2.e', max_width=12, max_height=12, figpadding=0.2, attribute_to_plot='net_flux', show_frame=False, xticks=False, yticks=False, ax=None, **textkwargs): r"""Network representation of given matrix This visualization is not optimized for large networks. It is meant to be used for the visualization of small models with up to 10-20 states. If used with large network, the automatic node positioning will be very slow and may still look ugly. Parameters ---------- weights : ndarray(n, n) weight matrix pos : ndarray(n,2), optional, default=None User-defined positions to draw the states on. xpos : ndarray(n,), optional, default=None Fixes the x positions while the y positions are optimized ypos : ndarray(n,), optional, default=None Fixes the y positions while the x positions are optimized state_sizes : ndarray(n), optional, default=None User-defined areas of the discs drawn for each state. If not given, the stationary probability of P will be used state_colors : string, ndarray(n), or list, optional, default='#ff5500' (orange) string : a Hex code for a single color used for all states array : n values in [0,1] which will result in a grayscale plot list : of len = nstates, with a color for each state. The list can mix strings, RGB values and hex codes, e.g. :py:obj:`state_colors` = ['g', 'red', [.23, .34, .35], '#ff5500'] is possible. state_labels : list of strings, optional, default is 'auto' A list with a label for each state, to be displayed at the center of each node/state. If left to 'auto', the labels are automatically set to the state indices. arrow_scale : float, optional, default=1.0 Relative arrow scale. Set to a value different from 1 to increase or decrease the arrow width. arrow_curvature : float, optional, default=1.0 Relative arrow curvature. Set to a value different from 1 to make arrows more or less curved. arrow_labels : 'weights', None or a ndarray(n,n) with label strings. Optional, default='weights' Strings to be placed upon arrows. If None, no labels will be used. If 'weights', the elements of P will be used. If a matrix of strings is given by the user these will be used. arrow_label_format : str, optional, default='%10.2f' The numeric format to print the arrow labels max_width : int (default = 12) The maximum figure width max_height: int (default = 12) The maximum figure height figpadding: float (default = 0.2) The relative figure size used for the padding show_frame: boolean (default=False) Draw a frame around the network. xticks: boolean (default=False) Show x ticks yticks: boolean (default=False) Show y ticks ax : matplotlib Axes object, optional, default=None The axes to plot to. When set to None a new Axes (and Figure) object will be used. textkwargs : optional argument for the text of the state and arrow labels. See http://matplotlib.org/api/text_api.html#matplotlib.text.Text for more info. The parameter 'size' refers to the size of the state and arrow labels and overwrites the matplotlib default. The parameter 'arrow_label_size' is only used for the arrow labels; please note that 'arrow_label_size' is not part of matplotlib.text.Text's set of parameters and will raise an exception when passed to matplotlib.text.Text directly. Returns ------- (fig, pos) : matpotlib.Figure instance, ndarray Axes instances containing the plot. Use pyplot.show() to display it. The positions of states. Can be used later to plot a different network representation (e.g. the flux). Examples -------- We define first define a reactive flux by taking the following transition matrix and computing TPT from state 2 to 3 >>> import numpy as np >>> P = np.array([[0.8, 0.15, 0.05, 0.0, 0.0], ... [0.1, 0.75, 0.05, 0.05, 0.05], ... [0.05, 0.1, 0.8, 0.0, 0.05], ... [0.0, 0.2, 0.0, 0.8, 0.0], ... [0.0, 0.02, 0.02, 0.0, 0.96]]) Scale the flux by 100 is basically a change of units to get numbers close to 1 (avoid printing many zeros). Now we visualize the flux: >>> plot_network(P) # doctest:+ELLIPSIS (<...Figure..., array...) """ plot = NetworkPlot(weights, pos=pos, xpos=xpos, ypos=ypos, ax=ax) fig = plot.plot_network( state_sizes=state_sizes, state_scale=state_scale, state_colors=state_colors, state_labels=state_labels, arrow_scale=arrow_scale, arrow_curvature=arrow_curvature, arrow_labels=arrow_labels, arrow_label_format=arrow_label_format, max_width=max_width, max_height=max_height, figpadding=figpadding, xticks=xticks, yticks=yticks, show_frame=show_frame, **textkwargs) return fig, plot.pos
python
def plot_network( weights, pos=None, xpos=None, ypos=None, state_sizes=None, state_scale=1.0, state_colors='#ff5500', state_labels='auto', arrow_scale=1.0, arrow_curvature=1.0, arrow_labels='weights', arrow_label_format='%2.e', max_width=12, max_height=12, figpadding=0.2, attribute_to_plot='net_flux', show_frame=False, xticks=False, yticks=False, ax=None, **textkwargs): r"""Network representation of given matrix This visualization is not optimized for large networks. It is meant to be used for the visualization of small models with up to 10-20 states. If used with large network, the automatic node positioning will be very slow and may still look ugly. Parameters ---------- weights : ndarray(n, n) weight matrix pos : ndarray(n,2), optional, default=None User-defined positions to draw the states on. xpos : ndarray(n,), optional, default=None Fixes the x positions while the y positions are optimized ypos : ndarray(n,), optional, default=None Fixes the y positions while the x positions are optimized state_sizes : ndarray(n), optional, default=None User-defined areas of the discs drawn for each state. If not given, the stationary probability of P will be used state_colors : string, ndarray(n), or list, optional, default='#ff5500' (orange) string : a Hex code for a single color used for all states array : n values in [0,1] which will result in a grayscale plot list : of len = nstates, with a color for each state. The list can mix strings, RGB values and hex codes, e.g. :py:obj:`state_colors` = ['g', 'red', [.23, .34, .35], '#ff5500'] is possible. state_labels : list of strings, optional, default is 'auto' A list with a label for each state, to be displayed at the center of each node/state. If left to 'auto', the labels are automatically set to the state indices. arrow_scale : float, optional, default=1.0 Relative arrow scale. Set to a value different from 1 to increase or decrease the arrow width. arrow_curvature : float, optional, default=1.0 Relative arrow curvature. Set to a value different from 1 to make arrows more or less curved. arrow_labels : 'weights', None or a ndarray(n,n) with label strings. Optional, default='weights' Strings to be placed upon arrows. If None, no labels will be used. If 'weights', the elements of P will be used. If a matrix of strings is given by the user these will be used. arrow_label_format : str, optional, default='%10.2f' The numeric format to print the arrow labels max_width : int (default = 12) The maximum figure width max_height: int (default = 12) The maximum figure height figpadding: float (default = 0.2) The relative figure size used for the padding show_frame: boolean (default=False) Draw a frame around the network. xticks: boolean (default=False) Show x ticks yticks: boolean (default=False) Show y ticks ax : matplotlib Axes object, optional, default=None The axes to plot to. When set to None a new Axes (and Figure) object will be used. textkwargs : optional argument for the text of the state and arrow labels. See http://matplotlib.org/api/text_api.html#matplotlib.text.Text for more info. The parameter 'size' refers to the size of the state and arrow labels and overwrites the matplotlib default. The parameter 'arrow_label_size' is only used for the arrow labels; please note that 'arrow_label_size' is not part of matplotlib.text.Text's set of parameters and will raise an exception when passed to matplotlib.text.Text directly. Returns ------- (fig, pos) : matpotlib.Figure instance, ndarray Axes instances containing the plot. Use pyplot.show() to display it. The positions of states. Can be used later to plot a different network representation (e.g. the flux). Examples -------- We define first define a reactive flux by taking the following transition matrix and computing TPT from state 2 to 3 >>> import numpy as np >>> P = np.array([[0.8, 0.15, 0.05, 0.0, 0.0], ... [0.1, 0.75, 0.05, 0.05, 0.05], ... [0.05, 0.1, 0.8, 0.0, 0.05], ... [0.0, 0.2, 0.0, 0.8, 0.0], ... [0.0, 0.02, 0.02, 0.0, 0.96]]) Scale the flux by 100 is basically a change of units to get numbers close to 1 (avoid printing many zeros). Now we visualize the flux: >>> plot_network(P) # doctest:+ELLIPSIS (<...Figure..., array...) """ plot = NetworkPlot(weights, pos=pos, xpos=xpos, ypos=ypos, ax=ax) fig = plot.plot_network( state_sizes=state_sizes, state_scale=state_scale, state_colors=state_colors, state_labels=state_labels, arrow_scale=arrow_scale, arrow_curvature=arrow_curvature, arrow_labels=arrow_labels, arrow_label_format=arrow_label_format, max_width=max_width, max_height=max_height, figpadding=figpadding, xticks=xticks, yticks=yticks, show_frame=show_frame, **textkwargs) return fig, plot.pos
[ "def", "plot_network", "(", "weights", ",", "pos", "=", "None", ",", "xpos", "=", "None", ",", "ypos", "=", "None", ",", "state_sizes", "=", "None", ",", "state_scale", "=", "1.0", ",", "state_colors", "=", "'#ff5500'", ",", "state_labels", "=", "'auto'"...
r"""Network representation of given matrix This visualization is not optimized for large networks. It is meant to be used for the visualization of small models with up to 10-20 states. If used with large network, the automatic node positioning will be very slow and may still look ugly. Parameters ---------- weights : ndarray(n, n) weight matrix pos : ndarray(n,2), optional, default=None User-defined positions to draw the states on. xpos : ndarray(n,), optional, default=None Fixes the x positions while the y positions are optimized ypos : ndarray(n,), optional, default=None Fixes the y positions while the x positions are optimized state_sizes : ndarray(n), optional, default=None User-defined areas of the discs drawn for each state. If not given, the stationary probability of P will be used state_colors : string, ndarray(n), or list, optional, default='#ff5500' (orange) string : a Hex code for a single color used for all states array : n values in [0,1] which will result in a grayscale plot list : of len = nstates, with a color for each state. The list can mix strings, RGB values and hex codes, e.g. :py:obj:`state_colors` = ['g', 'red', [.23, .34, .35], '#ff5500'] is possible. state_labels : list of strings, optional, default is 'auto' A list with a label for each state, to be displayed at the center of each node/state. If left to 'auto', the labels are automatically set to the state indices. arrow_scale : float, optional, default=1.0 Relative arrow scale. Set to a value different from 1 to increase or decrease the arrow width. arrow_curvature : float, optional, default=1.0 Relative arrow curvature. Set to a value different from 1 to make arrows more or less curved. arrow_labels : 'weights', None or a ndarray(n,n) with label strings. Optional, default='weights' Strings to be placed upon arrows. If None, no labels will be used. If 'weights', the elements of P will be used. If a matrix of strings is given by the user these will be used. arrow_label_format : str, optional, default='%10.2f' The numeric format to print the arrow labels max_width : int (default = 12) The maximum figure width max_height: int (default = 12) The maximum figure height figpadding: float (default = 0.2) The relative figure size used for the padding show_frame: boolean (default=False) Draw a frame around the network. xticks: boolean (default=False) Show x ticks yticks: boolean (default=False) Show y ticks ax : matplotlib Axes object, optional, default=None The axes to plot to. When set to None a new Axes (and Figure) object will be used. textkwargs : optional argument for the text of the state and arrow labels. See http://matplotlib.org/api/text_api.html#matplotlib.text.Text for more info. The parameter 'size' refers to the size of the state and arrow labels and overwrites the matplotlib default. The parameter 'arrow_label_size' is only used for the arrow labels; please note that 'arrow_label_size' is not part of matplotlib.text.Text's set of parameters and will raise an exception when passed to matplotlib.text.Text directly. Returns ------- (fig, pos) : matpotlib.Figure instance, ndarray Axes instances containing the plot. Use pyplot.show() to display it. The positions of states. Can be used later to plot a different network representation (e.g. the flux). Examples -------- We define first define a reactive flux by taking the following transition matrix and computing TPT from state 2 to 3 >>> import numpy as np >>> P = np.array([[0.8, 0.15, 0.05, 0.0, 0.0], ... [0.1, 0.75, 0.05, 0.05, 0.05], ... [0.05, 0.1, 0.8, 0.0, 0.05], ... [0.0, 0.2, 0.0, 0.8, 0.0], ... [0.0, 0.02, 0.02, 0.0, 0.96]]) Scale the flux by 100 is basically a change of units to get numbers close to 1 (avoid printing many zeros). Now we visualize the flux: >>> plot_network(P) # doctest:+ELLIPSIS (<...Figure..., array...)
[ "r", "Network", "representation", "of", "given", "matrix" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/plots/networks.py#L577-L682
train
204,152
markovmodel/PyEMMA
pyemma/thermo/extensions/cset.py
compute_csets_TRAM
def compute_csets_TRAM( connectivity, state_counts, count_matrices, equilibrium_state_counts=None, ttrajs=None, dtrajs=None, bias_trajs=None, nn=None, factor=1.0, callback=None): r""" Computes the largest connected sets in the produce space of Markov state and thermodynamic states for TRAM data. Parameters ---------- connectivity : string one of None, 'reversible_pathways', 'post_hoc_RE' or 'BAR_variance', 'neighbors', 'summed_count_matrix' or None. Selects the algorithm for measuring overlap between thermodynamic and Markov states. * 'reversible_pathways' : requires that every state in the connected set can be reached by following a pathway of reversible transitions. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). A pathway of reversible transitions is a list of reversible transitions [(i_1, i_2), (i_2, i_3),..., (i_(N-2), i_(N-1)), (i_(N-1), i_N)]. The thermodynamic state where the reversible transitions happen, is ignored in constructing the reversible pathways. This is equivalent to assuming that two ensembles overlap at some Markov state whenever there exist frames from both ensembles in that Markov state. * 'largest' : alias for reversible_pathways * 'post_hoc_RE' : similar to 'reversible_pathways' but with a more strict requirement for the overlap between thermodynamic states. It is required that every state in the connected set can be reached by following a pathway of reversible transitions or jumping between overlapping thermodynamic states while staying in the same Markov state. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). Two thermodynamic states k and l are defined to overlap at Markov state n if a replica exchange simulation [2]_ restricted to state n would show at least one transition from k to l or one transition from from l to k. The expected number of replica exchanges is estimated from the simulation data. The minimal number required of replica exchanges per Markov state can be increased by decreasing `connectivity_factor`. * 'BAR_variance' : like 'post_hoc_RE' but with a different condition to define the thermodynamic overlap based on the variance of the BAR estimator [3]_. Two thermodynamic states k and l are defined to overlap at Markov state n if the variance of the free energy difference Delta f_{kl} computed with BAR (and restricted to conformations form Markov state n) is less or equal than one. The minimally required variance can be controlled with `connectivity_factor`. * 'neighbors' : like 'post_hoc_RE' or 'BAR_variance' but assume a overlap between "neighboring" thermodynamic states. It is assumed that the data comes from an Umbrella sampling simulation and the number of the thermodynamic state matches the position of the Umbrella along the order parameter. The overlap of thermodynamic states k and l within Markov state n is set according to the value of nn; if there are samples in both product-space states (k,n) and (l,n) and |l-n|<=nn, the states are overlapping. * 'summed_count_matrix' : all thermodynamic states are assumed to overlap. The connected set is then computed by summing the count matrices over all thermodynamic states and taking it's largest strongly connected set. Not recommended! * None : assume that everything is connected. For debugging. state_counts : numpy.ndarray((T, M), dtype=numpy.intc) Number of visits to the combinations of thermodynamic state t and Markov state m count_matrices : numpy.ndarray((T, M, M), dtype=numpy.intc) Count matrices for all T thermodynamic states. equilibrium_state_counts : numpy.dnarray((T, M)), optional Number of visits to the combinations of thermodynamic state t and Markov state m in the equilibrium data (for use with TRAMMBAR). ttrajs : list of numpy.ndarray(X_i, dtype=numpy.intc), optional List of generating thermodynamic state trajectories. dtrajs : list of numpy.ndarray(X_i, dtype=numpy.intc), optional List of configurational state trajectories (disctrajs). bias_trajs : list of numpy.ndarray((X_i, T), dtype=numpy.float64), optional List of bias energy trajectories. The last three parameters are only required for connectivity = 'post_hoc_RE' or connectivity = 'BAR_variance'. nn : int, optional Number of neighbors that are assumed to overlap when connectivity='neighbors' factor : int, default=1.0 scaling factor used for connectivity = 'post_hoc_RE' or 'BAR_variance'. Values greater than 1.0 weaken the connectivity conditions. For 'post_hoc_RE' this multiplies the number of hypothetically observed transitions. For 'BAR_variance' this scales the threshold for the minimal allowed variance of free energy differences. Returns ------- csets, projected_cset csets : list of ndarrays((X_i,), dtype=int) List indexed by thermodynamic state. Every element csets[k] is the largest connected set at thermodynamic state k. projected_cset : ndarray(M, dtype=int) The overall connected set. This is the union of the individual connected sets of the thermodynamic states. References: ----------- [1]_ Hukushima et al, Exchange Monte Carlo method and application to spin glass simulations, J. Phys. Soc. Jan. 65, 1604 (1996) [2]_ Shirts and Chodera, Statistically optimal analysis of samples from multiple equilibrium states, J. Chem. Phys. 129, 124105 (2008) """ return _compute_csets( connectivity, state_counts, count_matrices, ttrajs, dtrajs, bias_trajs, nn=nn, equilibrium_state_counts=equilibrium_state_counts, factor=factor, callback=callback)
python
def compute_csets_TRAM( connectivity, state_counts, count_matrices, equilibrium_state_counts=None, ttrajs=None, dtrajs=None, bias_trajs=None, nn=None, factor=1.0, callback=None): r""" Computes the largest connected sets in the produce space of Markov state and thermodynamic states for TRAM data. Parameters ---------- connectivity : string one of None, 'reversible_pathways', 'post_hoc_RE' or 'BAR_variance', 'neighbors', 'summed_count_matrix' or None. Selects the algorithm for measuring overlap between thermodynamic and Markov states. * 'reversible_pathways' : requires that every state in the connected set can be reached by following a pathway of reversible transitions. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). A pathway of reversible transitions is a list of reversible transitions [(i_1, i_2), (i_2, i_3),..., (i_(N-2), i_(N-1)), (i_(N-1), i_N)]. The thermodynamic state where the reversible transitions happen, is ignored in constructing the reversible pathways. This is equivalent to assuming that two ensembles overlap at some Markov state whenever there exist frames from both ensembles in that Markov state. * 'largest' : alias for reversible_pathways * 'post_hoc_RE' : similar to 'reversible_pathways' but with a more strict requirement for the overlap between thermodynamic states. It is required that every state in the connected set can be reached by following a pathway of reversible transitions or jumping between overlapping thermodynamic states while staying in the same Markov state. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). Two thermodynamic states k and l are defined to overlap at Markov state n if a replica exchange simulation [2]_ restricted to state n would show at least one transition from k to l or one transition from from l to k. The expected number of replica exchanges is estimated from the simulation data. The minimal number required of replica exchanges per Markov state can be increased by decreasing `connectivity_factor`. * 'BAR_variance' : like 'post_hoc_RE' but with a different condition to define the thermodynamic overlap based on the variance of the BAR estimator [3]_. Two thermodynamic states k and l are defined to overlap at Markov state n if the variance of the free energy difference Delta f_{kl} computed with BAR (and restricted to conformations form Markov state n) is less or equal than one. The minimally required variance can be controlled with `connectivity_factor`. * 'neighbors' : like 'post_hoc_RE' or 'BAR_variance' but assume a overlap between "neighboring" thermodynamic states. It is assumed that the data comes from an Umbrella sampling simulation and the number of the thermodynamic state matches the position of the Umbrella along the order parameter. The overlap of thermodynamic states k and l within Markov state n is set according to the value of nn; if there are samples in both product-space states (k,n) and (l,n) and |l-n|<=nn, the states are overlapping. * 'summed_count_matrix' : all thermodynamic states are assumed to overlap. The connected set is then computed by summing the count matrices over all thermodynamic states and taking it's largest strongly connected set. Not recommended! * None : assume that everything is connected. For debugging. state_counts : numpy.ndarray((T, M), dtype=numpy.intc) Number of visits to the combinations of thermodynamic state t and Markov state m count_matrices : numpy.ndarray((T, M, M), dtype=numpy.intc) Count matrices for all T thermodynamic states. equilibrium_state_counts : numpy.dnarray((T, M)), optional Number of visits to the combinations of thermodynamic state t and Markov state m in the equilibrium data (for use with TRAMMBAR). ttrajs : list of numpy.ndarray(X_i, dtype=numpy.intc), optional List of generating thermodynamic state trajectories. dtrajs : list of numpy.ndarray(X_i, dtype=numpy.intc), optional List of configurational state trajectories (disctrajs). bias_trajs : list of numpy.ndarray((X_i, T), dtype=numpy.float64), optional List of bias energy trajectories. The last three parameters are only required for connectivity = 'post_hoc_RE' or connectivity = 'BAR_variance'. nn : int, optional Number of neighbors that are assumed to overlap when connectivity='neighbors' factor : int, default=1.0 scaling factor used for connectivity = 'post_hoc_RE' or 'BAR_variance'. Values greater than 1.0 weaken the connectivity conditions. For 'post_hoc_RE' this multiplies the number of hypothetically observed transitions. For 'BAR_variance' this scales the threshold for the minimal allowed variance of free energy differences. Returns ------- csets, projected_cset csets : list of ndarrays((X_i,), dtype=int) List indexed by thermodynamic state. Every element csets[k] is the largest connected set at thermodynamic state k. projected_cset : ndarray(M, dtype=int) The overall connected set. This is the union of the individual connected sets of the thermodynamic states. References: ----------- [1]_ Hukushima et al, Exchange Monte Carlo method and application to spin glass simulations, J. Phys. Soc. Jan. 65, 1604 (1996) [2]_ Shirts and Chodera, Statistically optimal analysis of samples from multiple equilibrium states, J. Chem. Phys. 129, 124105 (2008) """ return _compute_csets( connectivity, state_counts, count_matrices, ttrajs, dtrajs, bias_trajs, nn=nn, equilibrium_state_counts=equilibrium_state_counts, factor=factor, callback=callback)
[ "def", "compute_csets_TRAM", "(", "connectivity", ",", "state_counts", ",", "count_matrices", ",", "equilibrium_state_counts", "=", "None", ",", "ttrajs", "=", "None", ",", "dtrajs", "=", "None", ",", "bias_trajs", "=", "None", ",", "nn", "=", "None", ",", "...
r""" Computes the largest connected sets in the produce space of Markov state and thermodynamic states for TRAM data. Parameters ---------- connectivity : string one of None, 'reversible_pathways', 'post_hoc_RE' or 'BAR_variance', 'neighbors', 'summed_count_matrix' or None. Selects the algorithm for measuring overlap between thermodynamic and Markov states. * 'reversible_pathways' : requires that every state in the connected set can be reached by following a pathway of reversible transitions. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). A pathway of reversible transitions is a list of reversible transitions [(i_1, i_2), (i_2, i_3),..., (i_(N-2), i_(N-1)), (i_(N-1), i_N)]. The thermodynamic state where the reversible transitions happen, is ignored in constructing the reversible pathways. This is equivalent to assuming that two ensembles overlap at some Markov state whenever there exist frames from both ensembles in that Markov state. * 'largest' : alias for reversible_pathways * 'post_hoc_RE' : similar to 'reversible_pathways' but with a more strict requirement for the overlap between thermodynamic states. It is required that every state in the connected set can be reached by following a pathway of reversible transitions or jumping between overlapping thermodynamic states while staying in the same Markov state. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). Two thermodynamic states k and l are defined to overlap at Markov state n if a replica exchange simulation [2]_ restricted to state n would show at least one transition from k to l or one transition from from l to k. The expected number of replica exchanges is estimated from the simulation data. The minimal number required of replica exchanges per Markov state can be increased by decreasing `connectivity_factor`. * 'BAR_variance' : like 'post_hoc_RE' but with a different condition to define the thermodynamic overlap based on the variance of the BAR estimator [3]_. Two thermodynamic states k and l are defined to overlap at Markov state n if the variance of the free energy difference Delta f_{kl} computed with BAR (and restricted to conformations form Markov state n) is less or equal than one. The minimally required variance can be controlled with `connectivity_factor`. * 'neighbors' : like 'post_hoc_RE' or 'BAR_variance' but assume a overlap between "neighboring" thermodynamic states. It is assumed that the data comes from an Umbrella sampling simulation and the number of the thermodynamic state matches the position of the Umbrella along the order parameter. The overlap of thermodynamic states k and l within Markov state n is set according to the value of nn; if there are samples in both product-space states (k,n) and (l,n) and |l-n|<=nn, the states are overlapping. * 'summed_count_matrix' : all thermodynamic states are assumed to overlap. The connected set is then computed by summing the count matrices over all thermodynamic states and taking it's largest strongly connected set. Not recommended! * None : assume that everything is connected. For debugging. state_counts : numpy.ndarray((T, M), dtype=numpy.intc) Number of visits to the combinations of thermodynamic state t and Markov state m count_matrices : numpy.ndarray((T, M, M), dtype=numpy.intc) Count matrices for all T thermodynamic states. equilibrium_state_counts : numpy.dnarray((T, M)), optional Number of visits to the combinations of thermodynamic state t and Markov state m in the equilibrium data (for use with TRAMMBAR). ttrajs : list of numpy.ndarray(X_i, dtype=numpy.intc), optional List of generating thermodynamic state trajectories. dtrajs : list of numpy.ndarray(X_i, dtype=numpy.intc), optional List of configurational state trajectories (disctrajs). bias_trajs : list of numpy.ndarray((X_i, T), dtype=numpy.float64), optional List of bias energy trajectories. The last three parameters are only required for connectivity = 'post_hoc_RE' or connectivity = 'BAR_variance'. nn : int, optional Number of neighbors that are assumed to overlap when connectivity='neighbors' factor : int, default=1.0 scaling factor used for connectivity = 'post_hoc_RE' or 'BAR_variance'. Values greater than 1.0 weaken the connectivity conditions. For 'post_hoc_RE' this multiplies the number of hypothetically observed transitions. For 'BAR_variance' this scales the threshold for the minimal allowed variance of free energy differences. Returns ------- csets, projected_cset csets : list of ndarrays((X_i,), dtype=int) List indexed by thermodynamic state. Every element csets[k] is the largest connected set at thermodynamic state k. projected_cset : ndarray(M, dtype=int) The overall connected set. This is the union of the individual connected sets of the thermodynamic states. References: ----------- [1]_ Hukushima et al, Exchange Monte Carlo method and application to spin glass simulations, J. Phys. Soc. Jan. 65, 1604 (1996) [2]_ Shirts and Chodera, Statistically optimal analysis of samples from multiple equilibrium states, J. Chem. Phys. 129, 124105 (2008)
[ "r", "Computes", "the", "largest", "connected", "sets", "in", "the", "produce", "space", "of", "Markov", "state", "and", "thermodynamic", "states", "for", "TRAM", "data", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/thermo/extensions/cset.py#L34-L150
train
204,153
markovmodel/PyEMMA
pyemma/thermo/extensions/cset.py
compute_csets_dTRAM
def compute_csets_dTRAM(connectivity, count_matrices, nn=None, callback=None): r""" Computes the largest connected sets for dTRAM data. Parameters ---------- connectivity : string one 'reversible_pathways', 'neighbors', 'summed_count_matrix' or None. Selects the algorithm for measuring overlap between thermodynamic and Markov states. * 'reversible_pathways' : requires that every state in the connected set can be reached by following a pathway of reversible transitions. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). A pathway of reversible transitions is a list of reversible transitions [(i_1, i_2), (i_2, i_3),..., (i_(N-2), i_(N-1)), (i_(N-1), i_N)]. The thermodynamic state where the reversible transitions happen, is ignored in constructing the reversible pathways. This is equivalent to assuming that two ensembles overlap at some Markov state whenever there exist frames from both ensembles in that Markov state. * 'largest' : alias for reversible_pathways * 'neighbors' : similar to 'reversible_pathways' but with a more strict requirement for the overlap between thermodynamic states. It is required that every state in the connected set can be reached by following a pathway of reversible transitions or jumping between overlapping thermodynamic states while staying in the same Markov state. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). It is assumed that the data comes from an Umbrella sampling simulation and the number of the thermodynamic state matches the position of the Umbrella along the order parameter. The overlap of thermodynamic states k and l within Markov state n is set according to the value of nn; if there are samples in both product-space states (k,n) and (l,n) and |l-n|<=nn, the states are overlapping. * 'summed_count_matrix' : all thermodynamic states are assumed to overlap. The connected set is then computed by summing the count matrices over all thermodynamic states and taking it's largest strongly connected set. Not recommended! * None : assume that everything is connected. For debugging. count_matrices : numpy.ndarray((T, M, M)) Count matrices for all T thermodynamic states. nn : int or None, optional Number of neighbors that are assumed to overlap when connectivity='neighbors' Returns ------- csets, projected_cset csets : list of numpy.ndarray((M_prime_k,), dtype=int) List indexed by thermodynamic state. Every element csets[k] is the largest connected set at thermodynamic state k. projected_cset : numpy.ndarray(M_prime, dtype=int) The overall connected set. This is the union of the individual connected sets of the thermodynamic states. """ if connectivity=='post_hoc_RE' or connectivity=='BAR_variance': raise Exception('Connectivity type %s not supported for dTRAM data.'%connectivity) state_counts = _np.maximum(count_matrices.sum(axis=1), count_matrices.sum(axis=2)) return _compute_csets( connectivity, state_counts, count_matrices, None, None, None, nn=nn, callback=callback)
python
def compute_csets_dTRAM(connectivity, count_matrices, nn=None, callback=None): r""" Computes the largest connected sets for dTRAM data. Parameters ---------- connectivity : string one 'reversible_pathways', 'neighbors', 'summed_count_matrix' or None. Selects the algorithm for measuring overlap between thermodynamic and Markov states. * 'reversible_pathways' : requires that every state in the connected set can be reached by following a pathway of reversible transitions. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). A pathway of reversible transitions is a list of reversible transitions [(i_1, i_2), (i_2, i_3),..., (i_(N-2), i_(N-1)), (i_(N-1), i_N)]. The thermodynamic state where the reversible transitions happen, is ignored in constructing the reversible pathways. This is equivalent to assuming that two ensembles overlap at some Markov state whenever there exist frames from both ensembles in that Markov state. * 'largest' : alias for reversible_pathways * 'neighbors' : similar to 'reversible_pathways' but with a more strict requirement for the overlap between thermodynamic states. It is required that every state in the connected set can be reached by following a pathway of reversible transitions or jumping between overlapping thermodynamic states while staying in the same Markov state. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). It is assumed that the data comes from an Umbrella sampling simulation and the number of the thermodynamic state matches the position of the Umbrella along the order parameter. The overlap of thermodynamic states k and l within Markov state n is set according to the value of nn; if there are samples in both product-space states (k,n) and (l,n) and |l-n|<=nn, the states are overlapping. * 'summed_count_matrix' : all thermodynamic states are assumed to overlap. The connected set is then computed by summing the count matrices over all thermodynamic states and taking it's largest strongly connected set. Not recommended! * None : assume that everything is connected. For debugging. count_matrices : numpy.ndarray((T, M, M)) Count matrices for all T thermodynamic states. nn : int or None, optional Number of neighbors that are assumed to overlap when connectivity='neighbors' Returns ------- csets, projected_cset csets : list of numpy.ndarray((M_prime_k,), dtype=int) List indexed by thermodynamic state. Every element csets[k] is the largest connected set at thermodynamic state k. projected_cset : numpy.ndarray(M_prime, dtype=int) The overall connected set. This is the union of the individual connected sets of the thermodynamic states. """ if connectivity=='post_hoc_RE' or connectivity=='BAR_variance': raise Exception('Connectivity type %s not supported for dTRAM data.'%connectivity) state_counts = _np.maximum(count_matrices.sum(axis=1), count_matrices.sum(axis=2)) return _compute_csets( connectivity, state_counts, count_matrices, None, None, None, nn=nn, callback=callback)
[ "def", "compute_csets_dTRAM", "(", "connectivity", ",", "count_matrices", ",", "nn", "=", "None", ",", "callback", "=", "None", ")", ":", "if", "connectivity", "==", "'post_hoc_RE'", "or", "connectivity", "==", "'BAR_variance'", ":", "raise", "Exception", "(", ...
r""" Computes the largest connected sets for dTRAM data. Parameters ---------- connectivity : string one 'reversible_pathways', 'neighbors', 'summed_count_matrix' or None. Selects the algorithm for measuring overlap between thermodynamic and Markov states. * 'reversible_pathways' : requires that every state in the connected set can be reached by following a pathway of reversible transitions. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). A pathway of reversible transitions is a list of reversible transitions [(i_1, i_2), (i_2, i_3),..., (i_(N-2), i_(N-1)), (i_(N-1), i_N)]. The thermodynamic state where the reversible transitions happen, is ignored in constructing the reversible pathways. This is equivalent to assuming that two ensembles overlap at some Markov state whenever there exist frames from both ensembles in that Markov state. * 'largest' : alias for reversible_pathways * 'neighbors' : similar to 'reversible_pathways' but with a more strict requirement for the overlap between thermodynamic states. It is required that every state in the connected set can be reached by following a pathway of reversible transitions or jumping between overlapping thermodynamic states while staying in the same Markov state. A reversible transition between two Markov states (within the same thermodynamic state k) is a pair of Markov states that belong to the same strongly connected component of the count matrix (from thermodynamic state k). It is assumed that the data comes from an Umbrella sampling simulation and the number of the thermodynamic state matches the position of the Umbrella along the order parameter. The overlap of thermodynamic states k and l within Markov state n is set according to the value of nn; if there are samples in both product-space states (k,n) and (l,n) and |l-n|<=nn, the states are overlapping. * 'summed_count_matrix' : all thermodynamic states are assumed to overlap. The connected set is then computed by summing the count matrices over all thermodynamic states and taking it's largest strongly connected set. Not recommended! * None : assume that everything is connected. For debugging. count_matrices : numpy.ndarray((T, M, M)) Count matrices for all T thermodynamic states. nn : int or None, optional Number of neighbors that are assumed to overlap when connectivity='neighbors' Returns ------- csets, projected_cset csets : list of numpy.ndarray((M_prime_k,), dtype=int) List indexed by thermodynamic state. Every element csets[k] is the largest connected set at thermodynamic state k. projected_cset : numpy.ndarray(M_prime, dtype=int) The overall connected set. This is the union of the individual connected sets of the thermodynamic states.
[ "r", "Computes", "the", "largest", "connected", "sets", "for", "dTRAM", "data", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/thermo/extensions/cset.py#L152-L220
train
204,154
markovmodel/PyEMMA
pyemma/util/statistics.py
_indexes
def _indexes(arr): """ Returns the list of all indexes of the given array. Currently works for one and two-dimensional arrays """ myarr = np.array(arr) if myarr.ndim == 1: return list(range(len(myarr))) elif myarr.ndim == 2: return tuple(itertools.product(list(range(arr.shape[0])), list(range(arr.shape[1])))) else: raise NotImplementedError('Only supporting arrays of dimension 1 and 2 as yet.')
python
def _indexes(arr): """ Returns the list of all indexes of the given array. Currently works for one and two-dimensional arrays """ myarr = np.array(arr) if myarr.ndim == 1: return list(range(len(myarr))) elif myarr.ndim == 2: return tuple(itertools.product(list(range(arr.shape[0])), list(range(arr.shape[1])))) else: raise NotImplementedError('Only supporting arrays of dimension 1 and 2 as yet.')
[ "def", "_indexes", "(", "arr", ")", ":", "myarr", "=", "np", ".", "array", "(", "arr", ")", "if", "myarr", ".", "ndim", "==", "1", ":", "return", "list", "(", "range", "(", "len", "(", "myarr", ")", ")", ")", "elif", "myarr", ".", "ndim", "==",...
Returns the list of all indexes of the given array. Currently works for one and two-dimensional arrays
[ "Returns", "the", "list", "of", "all", "indexes", "of", "the", "given", "array", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/statistics.py#L93-L106
train
204,155
markovmodel/PyEMMA
pyemma/util/statistics.py
_column
def _column(arr, indexes): """ Returns a column with given indexes from a deep array For example, if the array is a matrix and indexes is a single int, will return arr[:,indexes]. If the array is an order 3 tensor and indexes is a pair of ints, will return arr[:,indexes[0],indexes[1]], etc. """ if arr.ndim == 2 and types.is_int(indexes): return arr[:, indexes] elif arr.ndim == 3 and len(indexes) == 2: return arr[:, indexes[0], indexes[1]] else: raise NotImplementedError('Only supporting arrays of dimension 2 and 3 as yet.')
python
def _column(arr, indexes): """ Returns a column with given indexes from a deep array For example, if the array is a matrix and indexes is a single int, will return arr[:,indexes]. If the array is an order 3 tensor and indexes is a pair of ints, will return arr[:,indexes[0],indexes[1]], etc. """ if arr.ndim == 2 and types.is_int(indexes): return arr[:, indexes] elif arr.ndim == 3 and len(indexes) == 2: return arr[:, indexes[0], indexes[1]] else: raise NotImplementedError('Only supporting arrays of dimension 2 and 3 as yet.')
[ "def", "_column", "(", "arr", ",", "indexes", ")", ":", "if", "arr", ".", "ndim", "==", "2", "and", "types", ".", "is_int", "(", "indexes", ")", ":", "return", "arr", "[", ":", ",", "indexes", "]", "elif", "arr", ".", "ndim", "==", "3", "and", ...
Returns a column with given indexes from a deep array For example, if the array is a matrix and indexes is a single int, will return arr[:,indexes]. If the array is an order 3 tensor and indexes is a pair of ints, will return arr[:,indexes[0],indexes[1]], etc.
[ "Returns", "a", "column", "with", "given", "indexes", "from", "a", "deep", "array" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/statistics.py#L109-L122
train
204,156
markovmodel/PyEMMA
pyemma/util/statistics.py
statistical_inefficiency
def statistical_inefficiency(X, truncate_acf=True): """ Estimates the statistical inefficiency from univariate time series X The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal. Given a signal :math:`{x_t}` with :math:`N` samples and statistical inefficiency :math:`I \in (0,1]`, there are only :math:`I \cdot N` effective or uncorrelated samples in the signal. This means that :math:`I \cdot N` should be used in order to compute statistical uncertainties. See [2]_ for a review. The statistical inefficiency is computed as :math:`I = (2 \tau)^{-1}` using the damped autocorrelation time ..1: \tau = \frac{1}{2}+\sum_{K=1}^{N} A(k) \left(1-\frac{k}{N}\right) where ..1: A(k) = \frac{\langle x_t x_{t+k} \rangle_t - \langle x^2 \rangle_t}{\mathrm{var}(x)} is the autocorrelation function of the signal :math:`{x_t}`, which is computed either for a single or multiple trajectories. Parameters ---------- X : float array or list of float arrays Univariate time series (single or multiple trajectories) truncate_acf : bool, optional, default=True When the normalized autocorrelation function passes through 0, it is truncated in order to avoid integrating random noise References ---------- .. [1] Anderson, T. W.: The Statistical Analysis of Time Series (Wiley, New York, 1971) .. [2] Janke, W: Statistical Analysis of Simulations: Data Correlations and Error Estimation Quantum Simulations of Complex Many-Body Systems: From Theory to Algorithms, Lecture Notes, J. Grotendorst, D. Marx, A. Muramatsu (Eds.), John von Neumann Institute for Computing, Juelich NIC Series 10, pp. 423-445, 2002. """ # check input assert np.ndim(X[0]) == 1, 'Data must be 1-dimensional' N = _maxlength(X) # length # mean-free data xflat = np.concatenate(X) Xmean = np.mean(xflat) X0 = [x-Xmean for x in X] # moments x2m = np.mean(xflat ** 2) # integrate damped autocorrelation corrsum = 0.0 for lag in range(N): acf = 0.0 n = 0.0 for x in X0: Nx = len(x) # length of this trajectory if (Nx > lag): # only use trajectories that are long enough acf += np.sum(x[0:Nx-lag] * x[lag:Nx]) n += float(Nx-lag) acf /= n if acf <= 0 and truncate_acf: # zero autocorrelation. Exit break elif lag > 0: # start integrating at lag 1 (effect of lag 0 is contained in the 0.5 below corrsum += acf * (1.0 - (float(lag)/float(N))) # compute damped correlation time corrtime = 0.5 + corrsum / x2m # return statistical inefficiency return 1.0 / (2 * corrtime)
python
def statistical_inefficiency(X, truncate_acf=True): """ Estimates the statistical inefficiency from univariate time series X The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal. Given a signal :math:`{x_t}` with :math:`N` samples and statistical inefficiency :math:`I \in (0,1]`, there are only :math:`I \cdot N` effective or uncorrelated samples in the signal. This means that :math:`I \cdot N` should be used in order to compute statistical uncertainties. See [2]_ for a review. The statistical inefficiency is computed as :math:`I = (2 \tau)^{-1}` using the damped autocorrelation time ..1: \tau = \frac{1}{2}+\sum_{K=1}^{N} A(k) \left(1-\frac{k}{N}\right) where ..1: A(k) = \frac{\langle x_t x_{t+k} \rangle_t - \langle x^2 \rangle_t}{\mathrm{var}(x)} is the autocorrelation function of the signal :math:`{x_t}`, which is computed either for a single or multiple trajectories. Parameters ---------- X : float array or list of float arrays Univariate time series (single or multiple trajectories) truncate_acf : bool, optional, default=True When the normalized autocorrelation function passes through 0, it is truncated in order to avoid integrating random noise References ---------- .. [1] Anderson, T. W.: The Statistical Analysis of Time Series (Wiley, New York, 1971) .. [2] Janke, W: Statistical Analysis of Simulations: Data Correlations and Error Estimation Quantum Simulations of Complex Many-Body Systems: From Theory to Algorithms, Lecture Notes, J. Grotendorst, D. Marx, A. Muramatsu (Eds.), John von Neumann Institute for Computing, Juelich NIC Series 10, pp. 423-445, 2002. """ # check input assert np.ndim(X[0]) == 1, 'Data must be 1-dimensional' N = _maxlength(X) # length # mean-free data xflat = np.concatenate(X) Xmean = np.mean(xflat) X0 = [x-Xmean for x in X] # moments x2m = np.mean(xflat ** 2) # integrate damped autocorrelation corrsum = 0.0 for lag in range(N): acf = 0.0 n = 0.0 for x in X0: Nx = len(x) # length of this trajectory if (Nx > lag): # only use trajectories that are long enough acf += np.sum(x[0:Nx-lag] * x[lag:Nx]) n += float(Nx-lag) acf /= n if acf <= 0 and truncate_acf: # zero autocorrelation. Exit break elif lag > 0: # start integrating at lag 1 (effect of lag 0 is contained in the 0.5 below corrsum += acf * (1.0 - (float(lag)/float(N))) # compute damped correlation time corrtime = 0.5 + corrsum / x2m # return statistical inefficiency return 1.0 / (2 * corrtime)
[ "def", "statistical_inefficiency", "(", "X", ",", "truncate_acf", "=", "True", ")", ":", "# check input", "assert", "np", ".", "ndim", "(", "X", "[", "0", "]", ")", "==", "1", ",", "'Data must be 1-dimensional'", "N", "=", "_maxlength", "(", "X", ")", "#...
Estimates the statistical inefficiency from univariate time series X The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal. Given a signal :math:`{x_t}` with :math:`N` samples and statistical inefficiency :math:`I \in (0,1]`, there are only :math:`I \cdot N` effective or uncorrelated samples in the signal. This means that :math:`I \cdot N` should be used in order to compute statistical uncertainties. See [2]_ for a review. The statistical inefficiency is computed as :math:`I = (2 \tau)^{-1}` using the damped autocorrelation time ..1: \tau = \frac{1}{2}+\sum_{K=1}^{N} A(k) \left(1-\frac{k}{N}\right) where ..1: A(k) = \frac{\langle x_t x_{t+k} \rangle_t - \langle x^2 \rangle_t}{\mathrm{var}(x)} is the autocorrelation function of the signal :math:`{x_t}`, which is computed either for a single or multiple trajectories. Parameters ---------- X : float array or list of float arrays Univariate time series (single or multiple trajectories) truncate_acf : bool, optional, default=True When the normalized autocorrelation function passes through 0, it is truncated in order to avoid integrating random noise References ---------- .. [1] Anderson, T. W.: The Statistical Analysis of Time Series (Wiley, New York, 1971) .. [2] Janke, W: Statistical Analysis of Simulations: Data Correlations and Error Estimation Quantum Simulations of Complex Many-Body Systems: From Theory to Algorithms, Lecture Notes, J. Grotendorst, D. Marx, A. Muramatsu (Eds.), John von Neumann Institute for Computing, Juelich NIC Series 10, pp. 423-445, 2002.
[ "Estimates", "the", "statistical", "inefficiency", "from", "univariate", "time", "series", "X" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/statistics.py#L184-L248
train
204,157
markovmodel/PyEMMA
pyemma/coordinates/data/util/traj_info_backends.py
SqliteDB._database_from_key
def _database_from_key(self, key): """ gets the database name for the given key. Should ensure a uniform spread of keys over the databases in order to minimize waiting times. Since the database has to be locked for updates and multiple processes want to write, each process has to wait until the lock has been released. By default the LRU databases will be stored in a sub directory "traj_info_usage" lying next to the main database. :param key: hash of the TrajInfo instance :return: str, database path """ if not self.filename: return None from pyemma.util.files import mkdir_p hash_value_long = int(key, 16) # bin hash to one of either 10 different databases # TODO: make a configuration parameter out of this number db_name = str(hash_value_long)[-1] + '.db' directory = os.path.dirname(self.filename) + os.path.sep + 'traj_info_usage' mkdir_p(directory) return os.path.join(directory, db_name)
python
def _database_from_key(self, key): """ gets the database name for the given key. Should ensure a uniform spread of keys over the databases in order to minimize waiting times. Since the database has to be locked for updates and multiple processes want to write, each process has to wait until the lock has been released. By default the LRU databases will be stored in a sub directory "traj_info_usage" lying next to the main database. :param key: hash of the TrajInfo instance :return: str, database path """ if not self.filename: return None from pyemma.util.files import mkdir_p hash_value_long = int(key, 16) # bin hash to one of either 10 different databases # TODO: make a configuration parameter out of this number db_name = str(hash_value_long)[-1] + '.db' directory = os.path.dirname(self.filename) + os.path.sep + 'traj_info_usage' mkdir_p(directory) return os.path.join(directory, db_name)
[ "def", "_database_from_key", "(", "self", ",", "key", ")", ":", "if", "not", "self", ".", "filename", ":", "return", "None", "from", "pyemma", ".", "util", ".", "files", "import", "mkdir_p", "hash_value_long", "=", "int", "(", "key", ",", "16", ")", "#...
gets the database name for the given key. Should ensure a uniform spread of keys over the databases in order to minimize waiting times. Since the database has to be locked for updates and multiple processes want to write, each process has to wait until the lock has been released. By default the LRU databases will be stored in a sub directory "traj_info_usage" lying next to the main database. :param key: hash of the TrajInfo instance :return: str, database path
[ "gets", "the", "database", "name", "for", "the", "given", "key", ".", "Should", "ensure", "a", "uniform", "spread", "of", "keys", "over", "the", "databases", "in", "order", "to", "minimize", "waiting", "times", ".", "Since", "the", "database", "has", "to",...
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/util/traj_info_backends.py#L234-L257
train
204,158
markovmodel/PyEMMA
pyemma/coordinates/data/util/traj_info_backends.py
SqliteDB._clean
def _clean(self, n): """ obtain n% oldest entries by looking into the usage databases. Then these entries are deleted first from the traj_info db and afterwards from the associated LRU dbs. :param n: delete n% entries in traj_info db [and associated LRU (usage) dbs]. """ # delete the n % oldest entries in the database import sqlite3 num_delete = int(self.num_entries / 100.0 * n) logger.debug("removing %i entries from db" % num_delete) lru_dbs = self._database.execute("select hash, lru_db from traj_info").fetchall() lru_dbs.sort(key=itemgetter(1)) hashs_by_db = {} age_by_hash = [] for k, v in itertools.groupby(lru_dbs, key=itemgetter(1)): hashs_by_db[k] = list(x[0] for x in v) # debug: distribution len_by_db = {os.path.basename(db): len(hashs_by_db[db]) for db in hashs_by_db.keys()} logger.debug("distribution of lru: %s", str(len_by_db)) ### end dbg # collect timestamps from databases for db in hashs_by_db.keys(): with sqlite3.connect(db, timeout=self.lru_timeout) as conn: rows = conn.execute("select hash, last_read from usage").fetchall() for r in rows: age_by_hash.append((r[0], float(r[1]), db)) # sort by age age_by_hash.sort(key=itemgetter(1)) if len(age_by_hash)>=2: assert[age_by_hash[-1] > age_by_hash[-2]] ids = map(itemgetter(0), age_by_hash[:num_delete]) ids = tuple(map(str, ids)) sql_compatible_ids = SqliteDB._format_tuple_for_sql(ids) with self._database as c: c.execute("DELETE FROM traj_info WHERE hash in (%s)" % sql_compatible_ids) # iterate over all LRU databases and delete those ids, we've just deleted from the main db. # Do this within the same execution block of the main database, because we do not want the entry to be deleted, # in case of a subsequent failure. age_by_hash.sort(key=itemgetter(2)) for db, values in itertools.groupby(age_by_hash, key=itemgetter(2)): values = tuple(v[0] for v in values) with sqlite3.connect(db, timeout=self.lru_timeout) as conn: stmnt = "DELETE FROM usage WHERE hash IN (%s)" \ % SqliteDB._format_tuple_for_sql(values) curr = conn.execute(stmnt) assert curr.rowcount == len(values), curr.rowcount
python
def _clean(self, n): """ obtain n% oldest entries by looking into the usage databases. Then these entries are deleted first from the traj_info db and afterwards from the associated LRU dbs. :param n: delete n% entries in traj_info db [and associated LRU (usage) dbs]. """ # delete the n % oldest entries in the database import sqlite3 num_delete = int(self.num_entries / 100.0 * n) logger.debug("removing %i entries from db" % num_delete) lru_dbs = self._database.execute("select hash, lru_db from traj_info").fetchall() lru_dbs.sort(key=itemgetter(1)) hashs_by_db = {} age_by_hash = [] for k, v in itertools.groupby(lru_dbs, key=itemgetter(1)): hashs_by_db[k] = list(x[0] for x in v) # debug: distribution len_by_db = {os.path.basename(db): len(hashs_by_db[db]) for db in hashs_by_db.keys()} logger.debug("distribution of lru: %s", str(len_by_db)) ### end dbg # collect timestamps from databases for db in hashs_by_db.keys(): with sqlite3.connect(db, timeout=self.lru_timeout) as conn: rows = conn.execute("select hash, last_read from usage").fetchall() for r in rows: age_by_hash.append((r[0], float(r[1]), db)) # sort by age age_by_hash.sort(key=itemgetter(1)) if len(age_by_hash)>=2: assert[age_by_hash[-1] > age_by_hash[-2]] ids = map(itemgetter(0), age_by_hash[:num_delete]) ids = tuple(map(str, ids)) sql_compatible_ids = SqliteDB._format_tuple_for_sql(ids) with self._database as c: c.execute("DELETE FROM traj_info WHERE hash in (%s)" % sql_compatible_ids) # iterate over all LRU databases and delete those ids, we've just deleted from the main db. # Do this within the same execution block of the main database, because we do not want the entry to be deleted, # in case of a subsequent failure. age_by_hash.sort(key=itemgetter(2)) for db, values in itertools.groupby(age_by_hash, key=itemgetter(2)): values = tuple(v[0] for v in values) with sqlite3.connect(db, timeout=self.lru_timeout) as conn: stmnt = "DELETE FROM usage WHERE hash IN (%s)" \ % SqliteDB._format_tuple_for_sql(values) curr = conn.execute(stmnt) assert curr.rowcount == len(values), curr.rowcount
[ "def", "_clean", "(", "self", ",", "n", ")", ":", "# delete the n % oldest entries in the database", "import", "sqlite3", "num_delete", "=", "int", "(", "self", ".", "num_entries", "/", "100.0", "*", "n", ")", "logger", ".", "debug", "(", "\"removing %i entries ...
obtain n% oldest entries by looking into the usage databases. Then these entries are deleted first from the traj_info db and afterwards from the associated LRU dbs. :param n: delete n% entries in traj_info db [and associated LRU (usage) dbs].
[ "obtain", "n%", "oldest", "entries", "by", "looking", "into", "the", "usage", "databases", ".", "Then", "these", "entries", "are", "deleted", "first", "from", "the", "traj_info", "db", "and", "afterwards", "from", "the", "associated", "LRU", "dbs", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/util/traj_info_backends.py#L322-L374
train
204,159
markovmodel/PyEMMA
pyemma/thermo/estimators/TRAM_estimator.py
TRAM.log_likelihood
def log_likelihood(self): r""" Returns the value of the log-likelihood of the converged TRAM estimate. """ # TODO: check that we are estimated... return _tram.log_likelihood_lower_bound( self.log_lagrangian_mult, self.biased_conf_energies, self.count_matrices, self.btrajs, self.dtrajs, self.state_counts, None, None, None, None, None)
python
def log_likelihood(self): r""" Returns the value of the log-likelihood of the converged TRAM estimate. """ # TODO: check that we are estimated... return _tram.log_likelihood_lower_bound( self.log_lagrangian_mult, self.biased_conf_energies, self.count_matrices, self.btrajs, self.dtrajs, self.state_counts, None, None, None, None, None)
[ "def", "log_likelihood", "(", "self", ")", ":", "# TODO: check that we are estimated...", "return", "_tram", ".", "log_likelihood_lower_bound", "(", "self", ".", "log_lagrangian_mult", ",", "self", ".", "biased_conf_energies", ",", "self", ".", "count_matrices", ",", ...
r""" Returns the value of the log-likelihood of the converged TRAM estimate.
[ "r", "Returns", "the", "value", "of", "the", "log", "-", "likelihood", "of", "the", "converged", "TRAM", "estimate", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/thermo/estimators/TRAM_estimator.py#L451-L459
train
204,160
markovmodel/PyEMMA
pyemma/coordinates/util/stat.py
histogram
def histogram(transform, dimensions, nbins): '''Computes the N-dimensional histogram of the transformed data. Parameters ---------- transform : pyemma.coordinates.transfrom.Transformer object transform that provides the input data dimensions : tuple of indices indices of the dimensions you want to examine nbins : tuple of ints number of bins along each dimension Returns ------- counts : (bins[0],bins[1],...) ndarray of ints counts compatible with pyplot.pcolormesh and pyplot.bar edges : list of (bins[i]) ndarrays bin edges compatible with pyplot.pcolormesh and pyplot.bar, see below. Examples -------- >>> import matplotlib.pyplot as plt # doctest: +SKIP Only for ipython notebook >> %matplotlib inline # doctest: +SKIP >>> counts, edges=histogram(transform, dimensions=(0,1), nbins=(20, 30)) # doctest: +SKIP >>> plt.pcolormesh(edges[0], edges[1], counts.T) # doctest: +SKIP >>> counts, edges=histogram(transform, dimensions=(1,), nbins=(50,)) # doctest: +SKIP >>> plt.bar(edges[0][:-1], counts, width=edges[0][1:]-edges[0][:-1]) # doctest: +SKIP ''' maximum = np.ones(len(dimensions)) * (-np.inf) minimum = np.ones(len(dimensions)) * np.inf # compute min and max for _, chunk in transform: maximum = np.max( np.vstack(( maximum, np.max(chunk[:, dimensions], axis=0))), axis=0) minimum = np.min( np.vstack(( minimum, np.min(chunk[:, dimensions], axis=0))), axis=0) # define bins bins = [np.linspace(m, M, num=n) for m, M, n in zip(minimum, maximum, nbins)] res = np.zeros(np.array(nbins) - 1) # compute actual histogram for _, chunk in transform: part, _ = np.histogramdd(chunk[:, dimensions], bins=bins) res += part return res, bins
python
def histogram(transform, dimensions, nbins): '''Computes the N-dimensional histogram of the transformed data. Parameters ---------- transform : pyemma.coordinates.transfrom.Transformer object transform that provides the input data dimensions : tuple of indices indices of the dimensions you want to examine nbins : tuple of ints number of bins along each dimension Returns ------- counts : (bins[0],bins[1],...) ndarray of ints counts compatible with pyplot.pcolormesh and pyplot.bar edges : list of (bins[i]) ndarrays bin edges compatible with pyplot.pcolormesh and pyplot.bar, see below. Examples -------- >>> import matplotlib.pyplot as plt # doctest: +SKIP Only for ipython notebook >> %matplotlib inline # doctest: +SKIP >>> counts, edges=histogram(transform, dimensions=(0,1), nbins=(20, 30)) # doctest: +SKIP >>> plt.pcolormesh(edges[0], edges[1], counts.T) # doctest: +SKIP >>> counts, edges=histogram(transform, dimensions=(1,), nbins=(50,)) # doctest: +SKIP >>> plt.bar(edges[0][:-1], counts, width=edges[0][1:]-edges[0][:-1]) # doctest: +SKIP ''' maximum = np.ones(len(dimensions)) * (-np.inf) minimum = np.ones(len(dimensions)) * np.inf # compute min and max for _, chunk in transform: maximum = np.max( np.vstack(( maximum, np.max(chunk[:, dimensions], axis=0))), axis=0) minimum = np.min( np.vstack(( minimum, np.min(chunk[:, dimensions], axis=0))), axis=0) # define bins bins = [np.linspace(m, M, num=n) for m, M, n in zip(minimum, maximum, nbins)] res = np.zeros(np.array(nbins) - 1) # compute actual histogram for _, chunk in transform: part, _ = np.histogramdd(chunk[:, dimensions], bins=bins) res += part return res, bins
[ "def", "histogram", "(", "transform", ",", "dimensions", ",", "nbins", ")", ":", "maximum", "=", "np", ".", "ones", "(", "len", "(", "dimensions", ")", ")", "*", "(", "-", "np", ".", "inf", ")", "minimum", "=", "np", ".", "ones", "(", "len", "(",...
Computes the N-dimensional histogram of the transformed data. Parameters ---------- transform : pyemma.coordinates.transfrom.Transformer object transform that provides the input data dimensions : tuple of indices indices of the dimensions you want to examine nbins : tuple of ints number of bins along each dimension Returns ------- counts : (bins[0],bins[1],...) ndarray of ints counts compatible with pyplot.pcolormesh and pyplot.bar edges : list of (bins[i]) ndarrays bin edges compatible with pyplot.pcolormesh and pyplot.bar, see below. Examples -------- >>> import matplotlib.pyplot as plt # doctest: +SKIP Only for ipython notebook >> %matplotlib inline # doctest: +SKIP >>> counts, edges=histogram(transform, dimensions=(0,1), nbins=(20, 30)) # doctest: +SKIP >>> plt.pcolormesh(edges[0], edges[1], counts.T) # doctest: +SKIP >>> counts, edges=histogram(transform, dimensions=(1,), nbins=(50,)) # doctest: +SKIP >>> plt.bar(edges[0][:-1], counts, width=edges[0][1:]-edges[0][:-1]) # doctest: +SKIP
[ "Computes", "the", "N", "-", "dimensional", "histogram", "of", "the", "transformed", "data", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/util/stat.py#L34-L90
train
204,161
markovmodel/PyEMMA
pyemma/util/_config.py
Config.load
def load(self, filename=None): """ load runtime configuration from given filename. If filename is None try to read from default file from default location. """ if not filename: filename = self.default_config_file files = self._cfgs_to_read() # insert last, so it will override all values, # which have already been set in previous files. files.insert(-1, filename) try: config = self.__read_cfg(files) except ReadConfigException as e: print(Config._format_msg('config.load("{file}") failed with {error}'.format(file=filename, error=e))) else: self._conf_values = config # notice user? if self.show_config_notification and not self.cfg_dir: print(Config._format_msg("no configuration directory set or usable." " Falling back to defaults."))
python
def load(self, filename=None): """ load runtime configuration from given filename. If filename is None try to read from default file from default location. """ if not filename: filename = self.default_config_file files = self._cfgs_to_read() # insert last, so it will override all values, # which have already been set in previous files. files.insert(-1, filename) try: config = self.__read_cfg(files) except ReadConfigException as e: print(Config._format_msg('config.load("{file}") failed with {error}'.format(file=filename, error=e))) else: self._conf_values = config # notice user? if self.show_config_notification and not self.cfg_dir: print(Config._format_msg("no configuration directory set or usable." " Falling back to defaults."))
[ "def", "load", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "default_config_file", "files", "=", "self", ".", "_cfgs_to_read", "(", ")", "# insert last, so it will override all values,", "# whic...
load runtime configuration from given filename. If filename is None try to read from default file from default location.
[ "load", "runtime", "configuration", "from", "given", "filename", ".", "If", "filename", "is", "None", "try", "to", "read", "from", "default", "file", "from", "default", "location", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/_config.py#L100-L122
train
204,162
markovmodel/PyEMMA
pyemma/util/_config.py
Config.save
def save(self, filename=None): """ Saves the runtime configuration to disk. Parameters ---------- filename: str or None, default=None writeable path to configuration filename. If None, use default location and filename. """ if not filename: filename = self.DEFAULT_CONFIG_FILE_NAME else: filename = str(filename) # try to extract the path from filename and use is as cfg_dir head, tail = os.path.split(filename) if head: self._cfg_dir = head # we are search for .cfg files in cfg_dir so make sure it contains the proper extension. base, ext = os.path.splitext(tail) if ext != ".cfg": filename += ".cfg" # if we have no cfg dir, try to create it first. Return if it failed. if not self.cfg_dir or not os.path.isdir(self.cfg_dir) or not os.stat(self.cfg_dir) != os.W_OK: try: self.cfg_dir = self.DEFAULT_CONFIG_DIR except ConfigDirectoryException as cde: print(Config._format_msg('Could not create configuration directory "{dir}"! config.save() failed.' ' Please set a writeable location with config.cfg_dir = val. Error was {exc}' .format(dir=self.cfg_dir, exc=cde))) return filename = os.path.join(self.cfg_dir, filename) try: with open(filename, 'w') as fh: self._conf_values.write(fh) except IOError as ioe: print(Config._format_msg("Save failed with error %s" % ioe))
python
def save(self, filename=None): """ Saves the runtime configuration to disk. Parameters ---------- filename: str or None, default=None writeable path to configuration filename. If None, use default location and filename. """ if not filename: filename = self.DEFAULT_CONFIG_FILE_NAME else: filename = str(filename) # try to extract the path from filename and use is as cfg_dir head, tail = os.path.split(filename) if head: self._cfg_dir = head # we are search for .cfg files in cfg_dir so make sure it contains the proper extension. base, ext = os.path.splitext(tail) if ext != ".cfg": filename += ".cfg" # if we have no cfg dir, try to create it first. Return if it failed. if not self.cfg_dir or not os.path.isdir(self.cfg_dir) or not os.stat(self.cfg_dir) != os.W_OK: try: self.cfg_dir = self.DEFAULT_CONFIG_DIR except ConfigDirectoryException as cde: print(Config._format_msg('Could not create configuration directory "{dir}"! config.save() failed.' ' Please set a writeable location with config.cfg_dir = val. Error was {exc}' .format(dir=self.cfg_dir, exc=cde))) return filename = os.path.join(self.cfg_dir, filename) try: with open(filename, 'w') as fh: self._conf_values.write(fh) except IOError as ioe: print(Config._format_msg("Save failed with error %s" % ioe))
[ "def", "save", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "DEFAULT_CONFIG_FILE_NAME", "else", ":", "filename", "=", "str", "(", "filename", ")", "# try to extract the path from filename and us...
Saves the runtime configuration to disk. Parameters ---------- filename: str or None, default=None writeable path to configuration filename. If None, use default location and filename.
[ "Saves", "the", "runtime", "configuration", "to", "disk", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/_config.py#L128-L168
train
204,163
markovmodel/PyEMMA
pyemma/util/_config.py
Config.default_config_file
def default_config_file(self): """ default config file living in PyEMMA package """ import os.path as p import pyemma return p.join(pyemma.__path__[0], Config.DEFAULT_CONFIG_FILE_NAME)
python
def default_config_file(self): """ default config file living in PyEMMA package """ import os.path as p import pyemma return p.join(pyemma.__path__[0], Config.DEFAULT_CONFIG_FILE_NAME)
[ "def", "default_config_file", "(", "self", ")", ":", "import", "os", ".", "path", "as", "p", "import", "pyemma", "return", "p", ".", "join", "(", "pyemma", ".", "__path__", "[", "0", "]", ",", "Config", ".", "DEFAULT_CONFIG_FILE_NAME", ")" ]
default config file living in PyEMMA package
[ "default", "config", "file", "living", "in", "PyEMMA", "package" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/_config.py#L176-L180
train
204,164
markovmodel/PyEMMA
pyemma/util/_config.py
Config.default_logging_file
def default_logging_file(self): """ default logging configuration""" import os.path as p import pyemma return p.join(pyemma.__path__[0], Config.DEFAULT_LOGGING_FILE_NAME)
python
def default_logging_file(self): """ default logging configuration""" import os.path as p import pyemma return p.join(pyemma.__path__[0], Config.DEFAULT_LOGGING_FILE_NAME)
[ "def", "default_logging_file", "(", "self", ")", ":", "import", "os", ".", "path", "as", "p", "import", "pyemma", "return", "p", ".", "join", "(", "pyemma", ".", "__path__", "[", "0", "]", ",", "Config", ".", "DEFAULT_LOGGING_FILE_NAME", ")" ]
default logging configuration
[ "default", "logging", "configuration" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/_config.py#L182-L186
train
204,165
markovmodel/PyEMMA
pyemma/util/_config.py
Config.cfg_dir
def cfg_dir(self, pyemma_cfg_dir): """ Sets PyEMMAs configuration directory. Also creates it with some default files, if does not exists. """ if not os.path.exists(pyemma_cfg_dir): try: mkdir_p(pyemma_cfg_dir) except NotADirectoryError: # on Python 3 raise ConfigDirectoryException("pyemma cfg dir (%s) is not a directory" % pyemma_cfg_dir) except EnvironmentError: raise ConfigDirectoryException("could not create configuration directory '%s'" % pyemma_cfg_dir) if not os.path.isdir(pyemma_cfg_dir): raise ConfigDirectoryException("%s is no valid directory" % pyemma_cfg_dir) if not os.access(pyemma_cfg_dir, os.W_OK): raise ConfigDirectoryException("%s is not writeable" % pyemma_cfg_dir) # give user the default cfg file, if its not there self.__copy_default_files_to_cfg_dir(pyemma_cfg_dir) self._cfg_dir = pyemma_cfg_dir if self.show_config_notification: stars = '*' * 80 print(stars, '\n', 'Changed PyEMMAs config directory to "{dir}".\n' 'To make this change permanent, export the environment variable' ' "PYEMMA_CFG_DIR" \nto point to this location. Eg. edit your .bashrc file!' .format(dir=pyemma_cfg_dir), '\n', stars, sep='')
python
def cfg_dir(self, pyemma_cfg_dir): """ Sets PyEMMAs configuration directory. Also creates it with some default files, if does not exists. """ if not os.path.exists(pyemma_cfg_dir): try: mkdir_p(pyemma_cfg_dir) except NotADirectoryError: # on Python 3 raise ConfigDirectoryException("pyemma cfg dir (%s) is not a directory" % pyemma_cfg_dir) except EnvironmentError: raise ConfigDirectoryException("could not create configuration directory '%s'" % pyemma_cfg_dir) if not os.path.isdir(pyemma_cfg_dir): raise ConfigDirectoryException("%s is no valid directory" % pyemma_cfg_dir) if not os.access(pyemma_cfg_dir, os.W_OK): raise ConfigDirectoryException("%s is not writeable" % pyemma_cfg_dir) # give user the default cfg file, if its not there self.__copy_default_files_to_cfg_dir(pyemma_cfg_dir) self._cfg_dir = pyemma_cfg_dir if self.show_config_notification: stars = '*' * 80 print(stars, '\n', 'Changed PyEMMAs config directory to "{dir}".\n' 'To make this change permanent, export the environment variable' ' "PYEMMA_CFG_DIR" \nto point to this location. Eg. edit your .bashrc file!' .format(dir=pyemma_cfg_dir), '\n', stars, sep='')
[ "def", "cfg_dir", "(", "self", ",", "pyemma_cfg_dir", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "pyemma_cfg_dir", ")", ":", "try", ":", "mkdir_p", "(", "pyemma_cfg_dir", ")", "except", "NotADirectoryError", ":", "# on Python 3", "raise", ...
Sets PyEMMAs configuration directory. Also creates it with some default files, if does not exists.
[ "Sets", "PyEMMAs", "configuration", "directory", ".", "Also", "creates", "it", "with", "some", "default", "files", "if", "does", "not", "exists", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/_config.py#L198-L224
train
204,166
markovmodel/PyEMMA
pyemma/util/_config.py
Config.logging_config
def logging_config(self): """ currently used logging configuration file. Can not be changed during runtime. """ cfg = self._conf_values.get('pyemma', 'logging_config') if cfg == 'DEFAULT': cfg = os.path.join(self.cfg_dir, Config.DEFAULT_LOGGING_FILE_NAME) return cfg
python
def logging_config(self): """ currently used logging configuration file. Can not be changed during runtime. """ cfg = self._conf_values.get('pyemma', 'logging_config') if cfg == 'DEFAULT': cfg = os.path.join(self.cfg_dir, Config.DEFAULT_LOGGING_FILE_NAME) return cfg
[ "def", "logging_config", "(", "self", ")", ":", "cfg", "=", "self", ".", "_conf_values", ".", "get", "(", "'pyemma'", ",", "'logging_config'", ")", "if", "cfg", "==", "'DEFAULT'", ":", "cfg", "=", "os", ".", "path", ".", "join", "(", "self", ".", "cf...
currently used logging configuration file. Can not be changed during runtime.
[ "currently", "used", "logging", "configuration", "file", ".", "Can", "not", "be", "changed", "during", "runtime", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/_config.py#L228-L233
train
204,167
markovmodel/PyEMMA
pyemma/util/_config.py
Config._cfgs_to_read
def _cfgs_to_read(self): """ reads config files from various locations to build final config. """ # use these files to extend/overwrite the conf_values. # Last red file always overwrites existing values! cfg = Config.DEFAULT_CONFIG_FILE_NAME filenames = [ self.default_config_file, cfg, # conf_values in current directory os.path.join(os.path.expanduser('~' + os.path.sep), cfg), # config in user dir '.pyemma.cfg', ] # look for user defined files if self.cfg_dir: from glob import glob filenames.extend(glob(self.cfg_dir + os.path.sep + "*.cfg")) return filenames
python
def _cfgs_to_read(self): """ reads config files from various locations to build final config. """ # use these files to extend/overwrite the conf_values. # Last red file always overwrites existing values! cfg = Config.DEFAULT_CONFIG_FILE_NAME filenames = [ self.default_config_file, cfg, # conf_values in current directory os.path.join(os.path.expanduser('~' + os.path.sep), cfg), # config in user dir '.pyemma.cfg', ] # look for user defined files if self.cfg_dir: from glob import glob filenames.extend(glob(self.cfg_dir + os.path.sep + "*.cfg")) return filenames
[ "def", "_cfgs_to_read", "(", "self", ")", ":", "# use these files to extend/overwrite the conf_values.", "# Last red file always overwrites existing values!", "cfg", "=", "Config", ".", "DEFAULT_CONFIG_FILE_NAME", "filenames", "=", "[", "self", ".", "default_config_file", ",", ...
reads config files from various locations to build final config.
[ "reads", "config", "files", "from", "various", "locations", "to", "build", "final", "config", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/_config.py#L418-L436
train
204,168
markovmodel/PyEMMA
pyemma/coordinates/data/fragmented_trajectory_reader.py
_FragmentedTrajectoryIterator._calculate_new_overlap
def _calculate_new_overlap(stride, traj_len, skip): """ Given two trajectories T_1 and T_2, this function calculates for the first trajectory an overlap, i.e., a skip parameter for T_2 such that the trajectory fragments T_1 and T_2 appear as one under the given stride. Idea for deriving the formula: It is K = ((traj_len - skip - 1) // stride + 1) = #(data points in trajectory of length (traj_len - skip)). Therefore, the first point's position that is not contained in T_1 anymore is given by pos = skip + s * K. Thus the needed skip of T_2 such that the same stride parameter makes T_1 and T_2 "look as one" is overlap = pos - traj_len. :param stride: the (global) stride parameter :param traj_len: length of T_1 :param skip: skip of T_1 :return: skip of T_2 """ overlap = stride * ((traj_len - skip - 1) // stride + 1) - traj_len + skip return overlap
python
def _calculate_new_overlap(stride, traj_len, skip): """ Given two trajectories T_1 and T_2, this function calculates for the first trajectory an overlap, i.e., a skip parameter for T_2 such that the trajectory fragments T_1 and T_2 appear as one under the given stride. Idea for deriving the formula: It is K = ((traj_len - skip - 1) // stride + 1) = #(data points in trajectory of length (traj_len - skip)). Therefore, the first point's position that is not contained in T_1 anymore is given by pos = skip + s * K. Thus the needed skip of T_2 such that the same stride parameter makes T_1 and T_2 "look as one" is overlap = pos - traj_len. :param stride: the (global) stride parameter :param traj_len: length of T_1 :param skip: skip of T_1 :return: skip of T_2 """ overlap = stride * ((traj_len - skip - 1) // stride + 1) - traj_len + skip return overlap
[ "def", "_calculate_new_overlap", "(", "stride", ",", "traj_len", ",", "skip", ")", ":", "overlap", "=", "stride", "*", "(", "(", "traj_len", "-", "skip", "-", "1", ")", "//", "stride", "+", "1", ")", "-", "traj_len", "+", "skip", "return", "overlap" ]
Given two trajectories T_1 and T_2, this function calculates for the first trajectory an overlap, i.e., a skip parameter for T_2 such that the trajectory fragments T_1 and T_2 appear as one under the given stride. Idea for deriving the formula: It is K = ((traj_len - skip - 1) // stride + 1) = #(data points in trajectory of length (traj_len - skip)). Therefore, the first point's position that is not contained in T_1 anymore is given by pos = skip + s * K. Thus the needed skip of T_2 such that the same stride parameter makes T_1 and T_2 "look as one" is overlap = pos - traj_len. :param stride: the (global) stride parameter :param traj_len: length of T_1 :param skip: skip of T_1 :return: skip of T_2
[ "Given", "two", "trajectories", "T_1", "and", "T_2", "this", "function", "calculates", "for", "the", "first", "trajectory", "an", "overlap", "i", ".", "e", ".", "a", "skip", "parameter", "for", "T_2", "such", "that", "the", "trajectory", "fragments", "T_1", ...
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/data/fragmented_trajectory_reader.py#L218-L241
train
204,169
markovmodel/PyEMMA
pyemma/util/numeric.py
assert_allclose
def assert_allclose(actual, desired, rtol=1.e-5, atol=1.e-8, err_msg='', verbose=True): r"""wrapper for numpy.testing.allclose with default tolerances of numpy.allclose. Needed since testing method has different values.""" return assert_allclose_np(actual, desired, rtol=rtol, atol=atol, err_msg=err_msg, verbose=verbose)
python
def assert_allclose(actual, desired, rtol=1.e-5, atol=1.e-8, err_msg='', verbose=True): r"""wrapper for numpy.testing.allclose with default tolerances of numpy.allclose. Needed since testing method has different values.""" return assert_allclose_np(actual, desired, rtol=rtol, atol=atol, err_msg=err_msg, verbose=verbose)
[ "def", "assert_allclose", "(", "actual", ",", "desired", ",", "rtol", "=", "1.e-5", ",", "atol", "=", "1.e-8", ",", "err_msg", "=", "''", ",", "verbose", "=", "True", ")", ":", "return", "assert_allclose_np", "(", "actual", ",", "desired", ",", "rtol", ...
r"""wrapper for numpy.testing.allclose with default tolerances of numpy.allclose. Needed since testing method has different values.
[ "r", "wrapper", "for", "numpy", ".", "testing", ".", "allclose", "with", "default", "tolerances", "of", "numpy", ".", "allclose", ".", "Needed", "since", "testing", "method", "has", "different", "values", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/numeric.py#L30-L35
train
204,170
markovmodel/PyEMMA
pyemma/_base/serialization/mdtraj_helpers.py
topology_to_numpy
def topology_to_numpy(top): """Convert this topology into a pandas dataframe Returns ------- atoms : np.ndarray dtype=[("serial", 'i4'), ("name", 'S4'), ("element", 'S3'), ("resSeq", 'i4'), ("resName",'S4'), ("chainID", 'i4'), ("segmentID", 'S4')] The atoms in the topology, represented as a data frame. bonds : np.ndarray The bonds in this topology, represented as an n_bonds x 2 array of the indices of the atoms involved in each bond. """ data = [(atom.serial, atom.name, atom.element.symbol, atom.residue.resSeq, atom.residue.name, atom.residue.chain.index, atom.segment_id) for atom in top.atoms] atoms = np.array(data, dtype=[("serial", 'i4'), ("name", 'S4'), ("element", 'S3'), ("resSeq", 'i4'), ("resName", 'S4'), ("chainID", 'i4'), ("segmentID", 'S4')]) bonds = np.fromiter(((a.index, b.index) for (a, b) in top.bonds), dtype='i4,i4', count=top.n_bonds) return atoms, bonds
python
def topology_to_numpy(top): """Convert this topology into a pandas dataframe Returns ------- atoms : np.ndarray dtype=[("serial", 'i4'), ("name", 'S4'), ("element", 'S3'), ("resSeq", 'i4'), ("resName",'S4'), ("chainID", 'i4'), ("segmentID", 'S4')] The atoms in the topology, represented as a data frame. bonds : np.ndarray The bonds in this topology, represented as an n_bonds x 2 array of the indices of the atoms involved in each bond. """ data = [(atom.serial, atom.name, atom.element.symbol, atom.residue.resSeq, atom.residue.name, atom.residue.chain.index, atom.segment_id) for atom in top.atoms] atoms = np.array(data, dtype=[("serial", 'i4'), ("name", 'S4'), ("element", 'S3'), ("resSeq", 'i4'), ("resName", 'S4'), ("chainID", 'i4'), ("segmentID", 'S4')]) bonds = np.fromiter(((a.index, b.index) for (a, b) in top.bonds), dtype='i4,i4', count=top.n_bonds) return atoms, bonds
[ "def", "topology_to_numpy", "(", "top", ")", ":", "data", "=", "[", "(", "atom", ".", "serial", ",", "atom", ".", "name", ",", "atom", ".", "element", ".", "symbol", ",", "atom", ".", "residue", ".", "resSeq", ",", "atom", ".", "residue", ".", "nam...
Convert this topology into a pandas dataframe Returns ------- atoms : np.ndarray dtype=[("serial", 'i4'), ("name", 'S4'), ("element", 'S3'), ("resSeq", 'i4'), ("resName",'S4'), ("chainID", 'i4'), ("segmentID", 'S4')] The atoms in the topology, represented as a data frame. bonds : np.ndarray The bonds in this topology, represented as an n_bonds x 2 array of the indices of the atoms involved in each bond.
[ "Convert", "this", "topology", "into", "a", "pandas", "dataframe" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/serialization/mdtraj_helpers.py#L24-L44
train
204,171
markovmodel/PyEMMA
pyemma/_base/serialization/mdtraj_helpers.py
topology_from_numpy
def topology_from_numpy(atoms, bonds=None): """Create a mdtraj topology from numpy arrays Parameters ---------- atoms : np.ndarray The atoms in the topology, represented as a data frame. This data frame should have columns "serial" (atom index), "name" (atom name), "element" (atom's element), "resSeq" (index of the residue) "resName" (name of the residue), "chainID" (index of the chain), and optionally "segmentID", following the same conventions as wwPDB 3.0 format. bonds : np.ndarray, shape=(n_bonds, 2), dtype=int, optional The bonds in the topology, represented as an n_bonds x 2 array of the indices of the atoms involved in each bond. Specifiying bonds here is optional. To create standard protein bonds, you can use `create_standard_bonds` to "fill in" the bonds on your newly created Topology object See Also -------- create_standard_bonds """ if bonds is None: bonds = np.zeros((0, 2)) for col in ["name", "element", "resSeq", "resName", "chainID", "serial"]: if col not in atoms.dtype.names: raise ValueError('dataframe must have column %s' % col) if "segmentID" not in atoms.dtype.names: atoms["segmentID"] = "" from mdtraj.core.topology import Atom from mdtraj.core import element as elem out = mdtraj.Topology() # TODO: allow for h5py data sets here, is there a way to check generic ndarray interface? #if not isinstance(bonds, np.ndarray): # raise TypeError('bonds must be an instance of numpy.ndarray. ' # 'You supplied a %s' % type(bonds)) out._atoms = [None for _ in range(len(atoms))] N = np.arange(0, len(atoms)) for ci in np.unique(atoms['chainID']): chain_atoms = atoms[atoms['chainID'] == ci] subN = N[atoms['chainID'] == ci] c = out.add_chain() for ri in np.unique(chain_atoms['resSeq']): residue_atoms = chain_atoms[chain_atoms['resSeq'] == ri] mask = subN[chain_atoms['resSeq'] == ri] indices = N[mask] rnames = residue_atoms['resName'] residue_name = np.array(rnames)[0] segids = residue_atoms['segmentID'] segment_id = np.array(segids)[0] if not np.all(rnames == residue_name): raise ValueError('All of the atoms with residue index %d ' 'do not share the same residue name' % ri) r = out.add_residue(residue_name.decode('ascii'), c, ri, segment_id.decode('ascii')) for ix, atom in enumerate(residue_atoms): e = atom['element'].decode('ascii') a = Atom(atom['name'].decode('ascii'), elem.get_by_symbol(e), int(indices[ix]), r, serial=atom['serial']) out._atoms[indices[ix]] = a r._atoms.append(a) for ai1, ai2 in bonds: out.add_bond(out.atom(ai1), out.atom(ai2)) out._numAtoms = out.n_atoms return out
python
def topology_from_numpy(atoms, bonds=None): """Create a mdtraj topology from numpy arrays Parameters ---------- atoms : np.ndarray The atoms in the topology, represented as a data frame. This data frame should have columns "serial" (atom index), "name" (atom name), "element" (atom's element), "resSeq" (index of the residue) "resName" (name of the residue), "chainID" (index of the chain), and optionally "segmentID", following the same conventions as wwPDB 3.0 format. bonds : np.ndarray, shape=(n_bonds, 2), dtype=int, optional The bonds in the topology, represented as an n_bonds x 2 array of the indices of the atoms involved in each bond. Specifiying bonds here is optional. To create standard protein bonds, you can use `create_standard_bonds` to "fill in" the bonds on your newly created Topology object See Also -------- create_standard_bonds """ if bonds is None: bonds = np.zeros((0, 2)) for col in ["name", "element", "resSeq", "resName", "chainID", "serial"]: if col not in atoms.dtype.names: raise ValueError('dataframe must have column %s' % col) if "segmentID" not in atoms.dtype.names: atoms["segmentID"] = "" from mdtraj.core.topology import Atom from mdtraj.core import element as elem out = mdtraj.Topology() # TODO: allow for h5py data sets here, is there a way to check generic ndarray interface? #if not isinstance(bonds, np.ndarray): # raise TypeError('bonds must be an instance of numpy.ndarray. ' # 'You supplied a %s' % type(bonds)) out._atoms = [None for _ in range(len(atoms))] N = np.arange(0, len(atoms)) for ci in np.unique(atoms['chainID']): chain_atoms = atoms[atoms['chainID'] == ci] subN = N[atoms['chainID'] == ci] c = out.add_chain() for ri in np.unique(chain_atoms['resSeq']): residue_atoms = chain_atoms[chain_atoms['resSeq'] == ri] mask = subN[chain_atoms['resSeq'] == ri] indices = N[mask] rnames = residue_atoms['resName'] residue_name = np.array(rnames)[0] segids = residue_atoms['segmentID'] segment_id = np.array(segids)[0] if not np.all(rnames == residue_name): raise ValueError('All of the atoms with residue index %d ' 'do not share the same residue name' % ri) r = out.add_residue(residue_name.decode('ascii'), c, ri, segment_id.decode('ascii')) for ix, atom in enumerate(residue_atoms): e = atom['element'].decode('ascii') a = Atom(atom['name'].decode('ascii'), elem.get_by_symbol(e), int(indices[ix]), r, serial=atom['serial']) out._atoms[indices[ix]] = a r._atoms.append(a) for ai1, ai2 in bonds: out.add_bond(out.atom(ai1), out.atom(ai2)) out._numAtoms = out.n_atoms return out
[ "def", "topology_from_numpy", "(", "atoms", ",", "bonds", "=", "None", ")", ":", "if", "bonds", "is", "None", ":", "bonds", "=", "np", ".", "zeros", "(", "(", "0", ",", "2", ")", ")", "for", "col", "in", "[", "\"name\"", ",", "\"element\"", ",", ...
Create a mdtraj topology from numpy arrays Parameters ---------- atoms : np.ndarray The atoms in the topology, represented as a data frame. This data frame should have columns "serial" (atom index), "name" (atom name), "element" (atom's element), "resSeq" (index of the residue) "resName" (name of the residue), "chainID" (index of the chain), and optionally "segmentID", following the same conventions as wwPDB 3.0 format. bonds : np.ndarray, shape=(n_bonds, 2), dtype=int, optional The bonds in the topology, represented as an n_bonds x 2 array of the indices of the atoms involved in each bond. Specifiying bonds here is optional. To create standard protein bonds, you can use `create_standard_bonds` to "fill in" the bonds on your newly created Topology object See Also -------- create_standard_bonds
[ "Create", "a", "mdtraj", "topology", "from", "numpy", "arrays" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_base/serialization/mdtraj_helpers.py#L47-L123
train
204,172
markovmodel/PyEMMA
pyemma/util/discrete_trajectories.py
read_discrete_trajectory
def read_discrete_trajectory(filename): """Read discrete trajectory from ascii file. The ascii file containing a single column with integer entries is read into an array of integers. Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the relative path to the file. Returns ------- dtraj : (M, ) ndarray Discrete state trajectory. """ with open(filename, "r") as f: lines=f.read() dtraj=np.fromstring(lines, dtype=int, sep="\n") return dtraj
python
def read_discrete_trajectory(filename): """Read discrete trajectory from ascii file. The ascii file containing a single column with integer entries is read into an array of integers. Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the relative path to the file. Returns ------- dtraj : (M, ) ndarray Discrete state trajectory. """ with open(filename, "r") as f: lines=f.read() dtraj=np.fromstring(lines, dtype=int, sep="\n") return dtraj
[ "def", "read_discrete_trajectory", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "f", ":", "lines", "=", "f", ".", "read", "(", ")", "dtraj", "=", "np", ".", "fromstring", "(", "lines", ",", "dtype", "=", "int",...
Read discrete trajectory from ascii file. The ascii file containing a single column with integer entries is read into an array of integers. Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the relative path to the file. Returns ------- dtraj : (M, ) ndarray Discrete state trajectory.
[ "Read", "discrete", "trajectory", "from", "ascii", "file", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/discrete_trajectories.py#L40-L62
train
204,173
markovmodel/PyEMMA
pyemma/util/discrete_trajectories.py
write_discrete_trajectory
def write_discrete_trajectory(filename, dtraj): r"""Write discrete trajectory to ascii file. The discrete trajectory is written to a single column ascii file with integer entries Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the relative path to the file. dtraj : array-like Discrete state trajectory. """ dtraj=np.asarray(dtraj) with open(filename, 'w') as f: dtraj.tofile(f, sep='\n', format='%d')
python
def write_discrete_trajectory(filename, dtraj): r"""Write discrete trajectory to ascii file. The discrete trajectory is written to a single column ascii file with integer entries Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the relative path to the file. dtraj : array-like Discrete state trajectory. """ dtraj=np.asarray(dtraj) with open(filename, 'w') as f: dtraj.tofile(f, sep='\n', format='%d')
[ "def", "write_discrete_trajectory", "(", "filename", ",", "dtraj", ")", ":", "dtraj", "=", "np", ".", "asarray", "(", "dtraj", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "dtraj", ".", "tofile", "(", "f", ",", "sep", "=", ...
r"""Write discrete trajectory to ascii file. The discrete trajectory is written to a single column ascii file with integer entries Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the relative path to the file. dtraj : array-like Discrete state trajectory.
[ "r", "Write", "discrete", "trajectory", "to", "ascii", "file", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/discrete_trajectories.py#L66-L85
train
204,174
markovmodel/PyEMMA
pyemma/util/discrete_trajectories.py
save_discrete_trajectory
def save_discrete_trajectory(filename, dtraj): r"""Write discrete trajectory to binary file. The discrete trajectory is stored as ndarray of integers in numpy .npy format. Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the relative path to the file. dtraj : array-like Discrete state trajectory. """ dtraj=np.asarray(dtraj) np.save(filename, dtraj)
python
def save_discrete_trajectory(filename, dtraj): r"""Write discrete trajectory to binary file. The discrete trajectory is stored as ndarray of integers in numpy .npy format. Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the relative path to the file. dtraj : array-like Discrete state trajectory. """ dtraj=np.asarray(dtraj) np.save(filename, dtraj)
[ "def", "save_discrete_trajectory", "(", "filename", ",", "dtraj", ")", ":", "dtraj", "=", "np", ".", "asarray", "(", "dtraj", ")", "np", ".", "save", "(", "filename", ",", "dtraj", ")" ]
r"""Write discrete trajectory to binary file. The discrete trajectory is stored as ndarray of integers in numpy .npy format. Parameters ---------- filename : str The filename of the discrete state trajectory file. The filename can either contain the full or the relative path to the file. dtraj : array-like Discrete state trajectory.
[ "r", "Write", "discrete", "trajectory", "to", "binary", "file", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/discrete_trajectories.py#L116-L135
train
204,175
markovmodel/PyEMMA
pyemma/util/discrete_trajectories.py
count_states
def count_states(dtrajs, ignore_negative=False): r"""returns a histogram count Parameters ---------- dtrajs : array_like or list of array_like Discretized trajectory or list of discretized trajectories ignore_negative, bool, default=False Ignore negative elements. By default, a negative element will cause an exception Returns ------- count : ndarray((n), dtype=int) the number of occurrences of each state. n=max+1 where max is the largest state index found. """ # format input dtrajs = _ensure_dtraj_list(dtrajs) # make bincounts for each input trajectory nmax = 0 bcs = [] for dtraj in dtrajs: if ignore_negative: dtraj = dtraj[np.where(dtraj >= 0)] bc = np.bincount(dtraj) nmax = max(nmax, bc.shape[0]) bcs.append(bc) # construct total bincount res = np.zeros(nmax, dtype=int) # add up individual bincounts for i, bc in enumerate(bcs): res[:bc.shape[0]] += bc return res
python
def count_states(dtrajs, ignore_negative=False): r"""returns a histogram count Parameters ---------- dtrajs : array_like or list of array_like Discretized trajectory or list of discretized trajectories ignore_negative, bool, default=False Ignore negative elements. By default, a negative element will cause an exception Returns ------- count : ndarray((n), dtype=int) the number of occurrences of each state. n=max+1 where max is the largest state index found. """ # format input dtrajs = _ensure_dtraj_list(dtrajs) # make bincounts for each input trajectory nmax = 0 bcs = [] for dtraj in dtrajs: if ignore_negative: dtraj = dtraj[np.where(dtraj >= 0)] bc = np.bincount(dtraj) nmax = max(nmax, bc.shape[0]) bcs.append(bc) # construct total bincount res = np.zeros(nmax, dtype=int) # add up individual bincounts for i, bc in enumerate(bcs): res[:bc.shape[0]] += bc return res
[ "def", "count_states", "(", "dtrajs", ",", "ignore_negative", "=", "False", ")", ":", "# format input", "dtrajs", "=", "_ensure_dtraj_list", "(", "dtrajs", ")", "# make bincounts for each input trajectory", "nmax", "=", "0", "bcs", "=", "[", "]", "for", "dtraj", ...
r"""returns a histogram count Parameters ---------- dtrajs : array_like or list of array_like Discretized trajectory or list of discretized trajectories ignore_negative, bool, default=False Ignore negative elements. By default, a negative element will cause an exception Returns ------- count : ndarray((n), dtype=int) the number of occurrences of each state. n=max+1 where max is the largest state index found.
[ "r", "returns", "a", "histogram", "count" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/discrete_trajectories.py#L144-L177
train
204,176
markovmodel/PyEMMA
pyemma/util/discrete_trajectories.py
number_of_states
def number_of_states(dtrajs, only_used = False): r"""returns the number of states in the given trajectories. Parameters ---------- dtraj : array_like or list of array_like Discretized trajectory or list of discretized trajectories only_used = False : boolean If False, will return max+1, where max is the largest index used. If True, will return the number of states that occur at least once. """ dtrajs = _ensure_dtraj_list(dtrajs) if only_used: # only states with counts > 0 wanted. Make a bincount and count nonzeros bc = count_states(dtrajs) return np.count_nonzero(bc) else: # all states wanted, included nonpopulated ones. return max + 1 imax = 0 for dtraj in dtrajs: imax = max(imax, np.max(dtraj)) return imax+1
python
def number_of_states(dtrajs, only_used = False): r"""returns the number of states in the given trajectories. Parameters ---------- dtraj : array_like or list of array_like Discretized trajectory or list of discretized trajectories only_used = False : boolean If False, will return max+1, where max is the largest index used. If True, will return the number of states that occur at least once. """ dtrajs = _ensure_dtraj_list(dtrajs) if only_used: # only states with counts > 0 wanted. Make a bincount and count nonzeros bc = count_states(dtrajs) return np.count_nonzero(bc) else: # all states wanted, included nonpopulated ones. return max + 1 imax = 0 for dtraj in dtrajs: imax = max(imax, np.max(dtraj)) return imax+1
[ "def", "number_of_states", "(", "dtrajs", ",", "only_used", "=", "False", ")", ":", "dtrajs", "=", "_ensure_dtraj_list", "(", "dtrajs", ")", "if", "only_used", ":", "# only states with counts > 0 wanted. Make a bincount and count nonzeros", "bc", "=", "count_states", "(...
r"""returns the number of states in the given trajectories. Parameters ---------- dtraj : array_like or list of array_like Discretized trajectory or list of discretized trajectories only_used = False : boolean If False, will return max+1, where max is the largest index used. If True, will return the number of states that occur at least once.
[ "r", "returns", "the", "number", "of", "states", "in", "the", "given", "trajectories", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/discrete_trajectories.py#L198-L219
train
204,177
markovmodel/PyEMMA
setup_util.py
stdchannel_redirected
def stdchannel_redirected(stdchannel, dest_filename, fake=False): """ A context manager to temporarily redirect stdout or stderr e.g.: with stdchannel_redirected(sys.stderr, os.devnull): if compiler.has_function('clock_gettime', libraries=['rt']): libraries.append('rt') """ if fake: yield return oldstdchannel = dest_file = None try: oldstdchannel = os.dup(stdchannel.fileno()) dest_file = open(dest_filename, 'w') os.dup2(dest_file.fileno(), stdchannel.fileno()) yield finally: if oldstdchannel is not None: os.dup2(oldstdchannel, stdchannel.fileno()) if dest_file is not None: dest_file.close()
python
def stdchannel_redirected(stdchannel, dest_filename, fake=False): """ A context manager to temporarily redirect stdout or stderr e.g.: with stdchannel_redirected(sys.stderr, os.devnull): if compiler.has_function('clock_gettime', libraries=['rt']): libraries.append('rt') """ if fake: yield return oldstdchannel = dest_file = None try: oldstdchannel = os.dup(stdchannel.fileno()) dest_file = open(dest_filename, 'w') os.dup2(dest_file.fileno(), stdchannel.fileno()) yield finally: if oldstdchannel is not None: os.dup2(oldstdchannel, stdchannel.fileno()) if dest_file is not None: dest_file.close()
[ "def", "stdchannel_redirected", "(", "stdchannel", ",", "dest_filename", ",", "fake", "=", "False", ")", ":", "if", "fake", ":", "yield", "return", "oldstdchannel", "=", "dest_file", "=", "None", "try", ":", "oldstdchannel", "=", "os", ".", "dup", "(", "st...
A context manager to temporarily redirect stdout or stderr e.g.: with stdchannel_redirected(sys.stderr, os.devnull): if compiler.has_function('clock_gettime', libraries=['rt']): libraries.append('rt')
[ "A", "context", "manager", "to", "temporarily", "redirect", "stdout", "or", "stderr" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/setup_util.py#L39-L63
train
204,178
markovmodel/PyEMMA
pyemma/coordinates/transform/_tica_base.py
TICABase._transform_array
def _transform_array(self, X): r"""Projects the data onto the dominant independent components. Parameters ---------- X : ndarray(n, m) the input data Returns ------- Y : ndarray(n,) the projected data """ X_meanfree = X - self.mean Y = np.dot(X_meanfree, self.eigenvectors[:, 0:self.dimension()]) return Y.astype(self.output_type())
python
def _transform_array(self, X): r"""Projects the data onto the dominant independent components. Parameters ---------- X : ndarray(n, m) the input data Returns ------- Y : ndarray(n,) the projected data """ X_meanfree = X - self.mean Y = np.dot(X_meanfree, self.eigenvectors[:, 0:self.dimension()]) return Y.astype(self.output_type())
[ "def", "_transform_array", "(", "self", ",", "X", ")", ":", "X_meanfree", "=", "X", "-", "self", ".", "mean", "Y", "=", "np", ".", "dot", "(", "X_meanfree", ",", "self", ".", "eigenvectors", "[", ":", ",", "0", ":", "self", ".", "dimension", "(", ...
r"""Projects the data onto the dominant independent components. Parameters ---------- X : ndarray(n, m) the input data Returns ------- Y : ndarray(n,) the projected data
[ "r", "Projects", "the", "data", "onto", "the", "dominant", "independent", "components", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/_tica_base.py#L117-L133
train
204,179
markovmodel/PyEMMA
pyemma/coordinates/transform/_tica_base.py
TICABase.timescales
def timescales(self): r"""Implied timescales of the TICA transformation For each :math:`i`-th eigenvalue, this returns .. math:: t_i = -\frac{\tau}{\log(|\lambda_i|)} where :math:`\tau` is the :py:obj:`lag` of the TICA object and :math:`\lambda_i` is the `i`-th :py:obj:`eigenvalue <eigenvalues>` of the TICA object. Returns ------- timescales: 1D np.array numpy array with the implied timescales. In principle, one should expect as many timescales as input coordinates were available. However, less eigenvalues will be returned if the TICA matrices were not full rank or :py:obj:`var_cutoff` was parsed """ return -self.lag / np.log(np.abs(self.eigenvalues))
python
def timescales(self): r"""Implied timescales of the TICA transformation For each :math:`i`-th eigenvalue, this returns .. math:: t_i = -\frac{\tau}{\log(|\lambda_i|)} where :math:`\tau` is the :py:obj:`lag` of the TICA object and :math:`\lambda_i` is the `i`-th :py:obj:`eigenvalue <eigenvalues>` of the TICA object. Returns ------- timescales: 1D np.array numpy array with the implied timescales. In principle, one should expect as many timescales as input coordinates were available. However, less eigenvalues will be returned if the TICA matrices were not full rank or :py:obj:`var_cutoff` was parsed """ return -self.lag / np.log(np.abs(self.eigenvalues))
[ "def", "timescales", "(", "self", ")", ":", "return", "-", "self", ".", "lag", "/", "np", ".", "log", "(", "np", ".", "abs", "(", "self", ".", "eigenvalues", ")", ")" ]
r"""Implied timescales of the TICA transformation For each :math:`i`-th eigenvalue, this returns .. math:: t_i = -\frac{\tau}{\log(|\lambda_i|)} where :math:`\tau` is the :py:obj:`lag` of the TICA object and :math:`\lambda_i` is the `i`-th :py:obj:`eigenvalue <eigenvalues>` of the TICA object. Returns ------- timescales: 1D np.array numpy array with the implied timescales. In principle, one should expect as many timescales as input coordinates were available. However, less eigenvalues will be returned if the TICA matrices were not full rank or :py:obj:`var_cutoff` was parsed
[ "r", "Implied", "timescales", "of", "the", "TICA", "transformation" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/_tica_base.py#L178-L197
train
204,180
markovmodel/PyEMMA
pyemma/coordinates/transform/_tica_base.py
TICABase.feature_TIC_correlation
def feature_TIC_correlation(self): r"""Instantaneous correlation matrix between mean-free input features and TICs Denoting the input features as :math:`X_i` and the TICs as :math:`\theta_j`, the instantaneous, linear correlation between them can be written as .. math:: \mathbf{Corr}(X_i - \mu_i, \mathbf{\theta}_j) = \frac{1}{\sigma_{X_i - \mu_i}}\sum_l \sigma_{(X_i - \mu_i)(X_l - \mu_l} \mathbf{U}_{li} The matrix :math:`\mathbf{U}` is the matrix containing, as column vectors, the eigenvectors of the TICA generalized eigenvalue problem . Returns ------- feature_TIC_correlation : ndarray(n,m) correlation matrix between input features and TICs. There is a row for each feature and a column for each TIC. """ feature_sigma = np.sqrt(np.diag(self.cov)) return np.dot(self.cov, self.eigenvectors[:, : self.dimension()]) / feature_sigma[:, np.newaxis]
python
def feature_TIC_correlation(self): r"""Instantaneous correlation matrix between mean-free input features and TICs Denoting the input features as :math:`X_i` and the TICs as :math:`\theta_j`, the instantaneous, linear correlation between them can be written as .. math:: \mathbf{Corr}(X_i - \mu_i, \mathbf{\theta}_j) = \frac{1}{\sigma_{X_i - \mu_i}}\sum_l \sigma_{(X_i - \mu_i)(X_l - \mu_l} \mathbf{U}_{li} The matrix :math:`\mathbf{U}` is the matrix containing, as column vectors, the eigenvectors of the TICA generalized eigenvalue problem . Returns ------- feature_TIC_correlation : ndarray(n,m) correlation matrix between input features and TICs. There is a row for each feature and a column for each TIC. """ feature_sigma = np.sqrt(np.diag(self.cov)) return np.dot(self.cov, self.eigenvectors[:, : self.dimension()]) / feature_sigma[:, np.newaxis]
[ "def", "feature_TIC_correlation", "(", "self", ")", ":", "feature_sigma", "=", "np", ".", "sqrt", "(", "np", ".", "diag", "(", "self", ".", "cov", ")", ")", "return", "np", ".", "dot", "(", "self", ".", "cov", ",", "self", ".", "eigenvectors", "[", ...
r"""Instantaneous correlation matrix between mean-free input features and TICs Denoting the input features as :math:`X_i` and the TICs as :math:`\theta_j`, the instantaneous, linear correlation between them can be written as .. math:: \mathbf{Corr}(X_i - \mu_i, \mathbf{\theta}_j) = \frac{1}{\sigma_{X_i - \mu_i}}\sum_l \sigma_{(X_i - \mu_i)(X_l - \mu_l} \mathbf{U}_{li} The matrix :math:`\mathbf{U}` is the matrix containing, as column vectors, the eigenvectors of the TICA generalized eigenvalue problem . Returns ------- feature_TIC_correlation : ndarray(n,m) correlation matrix between input features and TICs. There is a row for each feature and a column for each TIC.
[ "r", "Instantaneous", "correlation", "matrix", "between", "mean", "-", "free", "input", "features", "and", "TICs" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/coordinates/transform/_tica_base.py#L201-L221
train
204,181
markovmodel/PyEMMA
pyemma/util/metrics.py
_svd_sym_koopman
def _svd_sym_koopman(K, C00_train, Ctt_train): """ Computes the SVD of the symmetrized Koopman operator in the empirical distribution. """ from pyemma._ext.variational.solvers.direct import spd_inv_sqrt # reweight operator to empirical distribution C0t_re = mdot(C00_train, K) # symmetrized operator and SVD K_sym = mdot(spd_inv_sqrt(C00_train), C0t_re, spd_inv_sqrt(Ctt_train)) U, S, Vt = np.linalg.svd(K_sym, compute_uv=True, full_matrices=False) # projects back to singular functions of K U = mdot(spd_inv_sqrt(C00_train), U) Vt = mdot(Vt,spd_inv_sqrt(Ctt_train)) return U, S, Vt.T
python
def _svd_sym_koopman(K, C00_train, Ctt_train): """ Computes the SVD of the symmetrized Koopman operator in the empirical distribution. """ from pyemma._ext.variational.solvers.direct import spd_inv_sqrt # reweight operator to empirical distribution C0t_re = mdot(C00_train, K) # symmetrized operator and SVD K_sym = mdot(spd_inv_sqrt(C00_train), C0t_re, spd_inv_sqrt(Ctt_train)) U, S, Vt = np.linalg.svd(K_sym, compute_uv=True, full_matrices=False) # projects back to singular functions of K U = mdot(spd_inv_sqrt(C00_train), U) Vt = mdot(Vt,spd_inv_sqrt(Ctt_train)) return U, S, Vt.T
[ "def", "_svd_sym_koopman", "(", "K", ",", "C00_train", ",", "Ctt_train", ")", ":", "from", "pyemma", ".", "_ext", ".", "variational", ".", "solvers", ".", "direct", "import", "spd_inv_sqrt", "# reweight operator to empirical distribution", "C0t_re", "=", "mdot", "...
Computes the SVD of the symmetrized Koopman operator in the empirical distribution.
[ "Computes", "the", "SVD", "of", "the", "symmetrized", "Koopman", "operator", "in", "the", "empirical", "distribution", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/metrics.py#L11-L23
train
204,182
markovmodel/PyEMMA
pyemma/util/metrics.py
vamp_1_score
def vamp_1_score(K, C00_train, C0t_train, Ctt_train, C00_test, C0t_test, Ctt_test, k=None): """ Computes the VAMP-1 score of a kinetic model. Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt, defined by: :math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]` :math:`C_{tt}^{train} = E_t[x_{t+\tau} x_{t+\tau}^T]` These model covariances might have been subject to symmetrization or reweighting, depending on the type of model used. The covariances C00, C0t and Ctt of the test data are direct empirical estimates. singular vectors U and V using the test data with covariances C00, C0t, Ctt. U and V should come from the SVD of the symmetrized transition matrix or Koopman matrix: :math:`(C00^{train})^{-(1/2)} C0t^{train} (Ctt^{train})^{-(1/2)} = U S V.T` Parameters: ----------- K : ndarray(n, k) left singular vectors of the symmetrized transition matrix or Koopman matrix C00_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{00}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_train : ndarray(n, n) time-lagged covariance matrix of the training data, defined by :math:`C_{0t}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{tt}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` C00_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{00}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_test : ndarray(n, n) time-lagged covariance matrix of the test data, defined by :math:`C_{0t}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{tt}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` k : int number of slow processes to consider in the score Returns: -------- vamp1 : float VAMP-1 score """ from pyemma._ext.variational.solvers.direct import spd_inv_sqrt # SVD of symmetrized operator in empirical distribution U, S, V = _svd_sym_koopman(K, C00_train, Ctt_train) if k is not None: U = U[:, :k] # S = S[:k][:, :k] V = V[:, :k] A = spd_inv_sqrt(mdot(U.T, C00_test, U)) B = mdot(U.T, C0t_test, V) C = spd_inv_sqrt(mdot(V.T, Ctt_test, V)) # compute trace norm (nuclear norm), equal to the sum of singular values score = np.linalg.norm(mdot(A, B, C), ord='nuc') return score
python
def vamp_1_score(K, C00_train, C0t_train, Ctt_train, C00_test, C0t_test, Ctt_test, k=None): """ Computes the VAMP-1 score of a kinetic model. Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt, defined by: :math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]` :math:`C_{tt}^{train} = E_t[x_{t+\tau} x_{t+\tau}^T]` These model covariances might have been subject to symmetrization or reweighting, depending on the type of model used. The covariances C00, C0t and Ctt of the test data are direct empirical estimates. singular vectors U and V using the test data with covariances C00, C0t, Ctt. U and V should come from the SVD of the symmetrized transition matrix or Koopman matrix: :math:`(C00^{train})^{-(1/2)} C0t^{train} (Ctt^{train})^{-(1/2)} = U S V.T` Parameters: ----------- K : ndarray(n, k) left singular vectors of the symmetrized transition matrix or Koopman matrix C00_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{00}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_train : ndarray(n, n) time-lagged covariance matrix of the training data, defined by :math:`C_{0t}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{tt}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` C00_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{00}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_test : ndarray(n, n) time-lagged covariance matrix of the test data, defined by :math:`C_{0t}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{tt}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` k : int number of slow processes to consider in the score Returns: -------- vamp1 : float VAMP-1 score """ from pyemma._ext.variational.solvers.direct import spd_inv_sqrt # SVD of symmetrized operator in empirical distribution U, S, V = _svd_sym_koopman(K, C00_train, Ctt_train) if k is not None: U = U[:, :k] # S = S[:k][:, :k] V = V[:, :k] A = spd_inv_sqrt(mdot(U.T, C00_test, U)) B = mdot(U.T, C0t_test, V) C = spd_inv_sqrt(mdot(V.T, Ctt_test, V)) # compute trace norm (nuclear norm), equal to the sum of singular values score = np.linalg.norm(mdot(A, B, C), ord='nuc') return score
[ "def", "vamp_1_score", "(", "K", ",", "C00_train", ",", "C0t_train", ",", "Ctt_train", ",", "C00_test", ",", "C0t_test", ",", "Ctt_test", ",", "k", "=", "None", ")", ":", "from", "pyemma", ".", "_ext", ".", "variational", ".", "solvers", ".", "direct", ...
Computes the VAMP-1 score of a kinetic model. Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt, defined by: :math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]` :math:`C_{tt}^{train} = E_t[x_{t+\tau} x_{t+\tau}^T]` These model covariances might have been subject to symmetrization or reweighting, depending on the type of model used. The covariances C00, C0t and Ctt of the test data are direct empirical estimates. singular vectors U and V using the test data with covariances C00, C0t, Ctt. U and V should come from the SVD of the symmetrized transition matrix or Koopman matrix: :math:`(C00^{train})^{-(1/2)} C0t^{train} (Ctt^{train})^{-(1/2)} = U S V.T` Parameters: ----------- K : ndarray(n, k) left singular vectors of the symmetrized transition matrix or Koopman matrix C00_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{00}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_train : ndarray(n, n) time-lagged covariance matrix of the training data, defined by :math:`C_{0t}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{tt}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` C00_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{00}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_test : ndarray(n, n) time-lagged covariance matrix of the test data, defined by :math:`C_{0t}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{tt}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` k : int number of slow processes to consider in the score Returns: -------- vamp1 : float VAMP-1 score
[ "Computes", "the", "VAMP", "-", "1", "score", "of", "a", "kinetic", "model", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/metrics.py#L26-L91
train
204,183
markovmodel/PyEMMA
pyemma/util/metrics.py
vamp_e_score
def vamp_e_score(K, C00_train, C0t_train, Ctt_train, C00_test, C0t_test, Ctt_test, k=None): """ Computes the VAMP-E score of a kinetic model. Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt, defined by: :math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]` :math:`C_{tt}^{train} = E_t[x_{t+\tau} x_{t+\tau}^T]` These model covariances might have been subject to symmetrization or reweighting, depending on the type of model used. The covariances C00, C0t and Ctt of the test data are direct empirical estimates. singular vectors U and V using the test data with covariances C00, C0t, Ctt. U and V should come from the SVD of the symmetrized transition matrix or Koopman matrix: :math:`(C00^{train})^{-(1/2)} C0t^{train} (Ctt^{train})^{-(1/2)} = U S V.T` Parameters: ----------- K : ndarray(n, k) left singular vectors of the symmetrized transition matrix or Koopman matrix C00_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{00}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_train : ndarray(n, n) time-lagged covariance matrix of the training data, defined by :math:`C_{0t}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{tt}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` C00_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{00}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_test : ndarray(n, n) time-lagged covariance matrix of the test data, defined by :math:`C_{0t}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{tt}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` k : int number of slow processes to consider in the score Returns: -------- vampE : float VAMP-E score """ # SVD of symmetrized operator in empirical distribution U, s, V = _svd_sym_koopman(K, C00_train, Ctt_train) if k is not None: U = U[:, :k] S = np.diag(s[:k]) V = V[:, :k] score = np.trace(2.0 * mdot(V, S, U.T, C0t_test) - mdot(V, S, U.T, C00_test, U, S, V.T, Ctt_test)) return score
python
def vamp_e_score(K, C00_train, C0t_train, Ctt_train, C00_test, C0t_test, Ctt_test, k=None): """ Computes the VAMP-E score of a kinetic model. Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt, defined by: :math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]` :math:`C_{tt}^{train} = E_t[x_{t+\tau} x_{t+\tau}^T]` These model covariances might have been subject to symmetrization or reweighting, depending on the type of model used. The covariances C00, C0t and Ctt of the test data are direct empirical estimates. singular vectors U and V using the test data with covariances C00, C0t, Ctt. U and V should come from the SVD of the symmetrized transition matrix or Koopman matrix: :math:`(C00^{train})^{-(1/2)} C0t^{train} (Ctt^{train})^{-(1/2)} = U S V.T` Parameters: ----------- K : ndarray(n, k) left singular vectors of the symmetrized transition matrix or Koopman matrix C00_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{00}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_train : ndarray(n, n) time-lagged covariance matrix of the training data, defined by :math:`C_{0t}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{tt}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` C00_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{00}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_test : ndarray(n, n) time-lagged covariance matrix of the test data, defined by :math:`C_{0t}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{tt}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` k : int number of slow processes to consider in the score Returns: -------- vampE : float VAMP-E score """ # SVD of symmetrized operator in empirical distribution U, s, V = _svd_sym_koopman(K, C00_train, Ctt_train) if k is not None: U = U[:, :k] S = np.diag(s[:k]) V = V[:, :k] score = np.trace(2.0 * mdot(V, S, U.T, C0t_test) - mdot(V, S, U.T, C00_test, U, S, V.T, Ctt_test)) return score
[ "def", "vamp_e_score", "(", "K", ",", "C00_train", ",", "C0t_train", ",", "Ctt_train", ",", "C00_test", ",", "C0t_test", ",", "Ctt_test", ",", "k", "=", "None", ")", ":", "# SVD of symmetrized operator in empirical distribution", "U", ",", "s", ",", "V", "=", ...
Computes the VAMP-E score of a kinetic model. Ranks the kinetic model described by the estimation of covariances C00, C0t and Ctt, defined by: :math:`C_{0t}^{train} = E_t[x_t x_{t+\tau}^T]` :math:`C_{tt}^{train} = E_t[x_{t+\tau} x_{t+\tau}^T]` These model covariances might have been subject to symmetrization or reweighting, depending on the type of model used. The covariances C00, C0t and Ctt of the test data are direct empirical estimates. singular vectors U and V using the test data with covariances C00, C0t, Ctt. U and V should come from the SVD of the symmetrized transition matrix or Koopman matrix: :math:`(C00^{train})^{-(1/2)} C0t^{train} (Ctt^{train})^{-(1/2)} = U S V.T` Parameters: ----------- K : ndarray(n, k) left singular vectors of the symmetrized transition matrix or Koopman matrix C00_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{00}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_train : ndarray(n, n) time-lagged covariance matrix of the training data, defined by :math:`C_{0t}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_train : ndarray(n, n) covariance matrix of the training data, defined by :math:`C_{tt}^{train} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` C00_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{00}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_t^T` C0t_test : ndarray(n, n) time-lagged covariance matrix of the test data, defined by :math:`C_{0t}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_t x_{t+\tau}^T` Ctt_test : ndarray(n, n) covariance matrix of the test data, defined by :math:`C_{tt}^{test} = (T-\tau)^{-1} \sum_{t=0}^{T-\tau} x_{t+\tau} x_{t+\tau}^T` k : int number of slow processes to consider in the score Returns: -------- vampE : float VAMP-E score
[ "Computes", "the", "VAMP", "-", "E", "score", "of", "a", "kinetic", "model", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/metrics.py#L162-L220
train
204,184
markovmodel/PyEMMA
pyemma/util/annotators.py
get_culprit
def get_culprit(omit_top_frames=1): """get the filename and line number calling this. Parameters ---------- omit_top_frames: int, default=1 omit n frames from top of stack stack. Purpose is to get the real culprit and not intermediate functions on the stack. Returns ------- (filename: str, fileno: int) filename and line number of the culprit. """ try: caller_stack = stack()[omit_top_frames:] while len(caller_stack) > 0: frame = caller_stack.pop(0) filename = frame[1] # skip callee frames if they are other decorators or this file(func) if '<decorator' in filename or __file__ in filename: continue else: break lineno = frame[2] # avoid cyclic references! del caller_stack, frame except OSError: # eg. os.getcwd() fails in conda-test, since cwd gets deleted. filename = 'unknown' lineno = -1 return filename, lineno
python
def get_culprit(omit_top_frames=1): """get the filename and line number calling this. Parameters ---------- omit_top_frames: int, default=1 omit n frames from top of stack stack. Purpose is to get the real culprit and not intermediate functions on the stack. Returns ------- (filename: str, fileno: int) filename and line number of the culprit. """ try: caller_stack = stack()[omit_top_frames:] while len(caller_stack) > 0: frame = caller_stack.pop(0) filename = frame[1] # skip callee frames if they are other decorators or this file(func) if '<decorator' in filename or __file__ in filename: continue else: break lineno = frame[2] # avoid cyclic references! del caller_stack, frame except OSError: # eg. os.getcwd() fails in conda-test, since cwd gets deleted. filename = 'unknown' lineno = -1 return filename, lineno
[ "def", "get_culprit", "(", "omit_top_frames", "=", "1", ")", ":", "try", ":", "caller_stack", "=", "stack", "(", ")", "[", "omit_top_frames", ":", "]", "while", "len", "(", "caller_stack", ")", ">", "0", ":", "frame", "=", "caller_stack", ".", "pop", "...
get the filename and line number calling this. Parameters ---------- omit_top_frames: int, default=1 omit n frames from top of stack stack. Purpose is to get the real culprit and not intermediate functions on the stack. Returns ------- (filename: str, fileno: int) filename and line number of the culprit.
[ "get", "the", "filename", "and", "line", "number", "calling", "this", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/util/annotators.py#L164-L193
train
204,185
markovmodel/PyEMMA
pyemma/thermo/util/util.py
get_averaged_bias_matrix
def get_averaged_bias_matrix(bias_sequences, dtrajs, nstates=None): r""" Computes a bias matrix via an exponential average of the observed frame wise bias energies. Parameters ---------- bias_sequences : list of numpy.ndarray(T_i, num_therm_states) A single reduced bias energy trajectory or a list of reduced bias energy trajectories. For every simulation frame seen in trajectory i and time step t, btrajs[i][t, k] is the reduced bias energy of that frame evaluated in the k'th thermodynamic state (i.e. at the k'th Umbrella/Hamiltonian/temperature) dtrajs : list of numpy.ndarray(T_i) of int A single discrete trajectory or a list of discrete trajectories. The integers are indexes in 0,...,num_conf_states-1 enumerating the num_conf_states Markov states or the bins the trajectory is in at any time. nstates : int, optional, default=None Number of configuration states. Returns ------- bias_matrix : numpy.ndarray(shape=(num_therm_states, num_conf_states)) object bias_energies_full[j, i] is the bias energy in units of kT for each discrete state i at thermodynamic state j. """ from pyemma.thermo.extensions.util import (logsumexp as _logsumexp, logsumexp_pair as _logsumexp_pair) nmax = int(_np.max([dtraj.max() for dtraj in dtrajs])) if nstates is None: nstates = nmax + 1 elif nstates < nmax + 1: raise ValueError("nstates is smaller than the number of observed microstates") nthermo = bias_sequences[0].shape[1] bias_matrix = -_np.ones(shape=(nthermo, nstates), dtype=_np.float64) * _np.inf counts = _np.zeros(shape=(nstates,), dtype=_np.intc) for s in range(len(bias_sequences)): for i in range(nstates): idx = (dtrajs[s] == i) nidx = idx.sum() if nidx == 0: continue counts[i] += nidx selected_bias_sequence = bias_sequences[s][idx, :] for k in range(nthermo): bias_matrix[k, i] = _logsumexp_pair( bias_matrix[k, i], _logsumexp( _np.ascontiguousarray(-selected_bias_sequence[:, k]), inplace=False)) idx = counts.nonzero() log_counts = _np.log(counts[idx]) bias_matrix *= -1.0 bias_matrix[:, idx] += log_counts[_np.newaxis, :] return bias_matrix
python
def get_averaged_bias_matrix(bias_sequences, dtrajs, nstates=None): r""" Computes a bias matrix via an exponential average of the observed frame wise bias energies. Parameters ---------- bias_sequences : list of numpy.ndarray(T_i, num_therm_states) A single reduced bias energy trajectory or a list of reduced bias energy trajectories. For every simulation frame seen in trajectory i and time step t, btrajs[i][t, k] is the reduced bias energy of that frame evaluated in the k'th thermodynamic state (i.e. at the k'th Umbrella/Hamiltonian/temperature) dtrajs : list of numpy.ndarray(T_i) of int A single discrete trajectory or a list of discrete trajectories. The integers are indexes in 0,...,num_conf_states-1 enumerating the num_conf_states Markov states or the bins the trajectory is in at any time. nstates : int, optional, default=None Number of configuration states. Returns ------- bias_matrix : numpy.ndarray(shape=(num_therm_states, num_conf_states)) object bias_energies_full[j, i] is the bias energy in units of kT for each discrete state i at thermodynamic state j. """ from pyemma.thermo.extensions.util import (logsumexp as _logsumexp, logsumexp_pair as _logsumexp_pair) nmax = int(_np.max([dtraj.max() for dtraj in dtrajs])) if nstates is None: nstates = nmax + 1 elif nstates < nmax + 1: raise ValueError("nstates is smaller than the number of observed microstates") nthermo = bias_sequences[0].shape[1] bias_matrix = -_np.ones(shape=(nthermo, nstates), dtype=_np.float64) * _np.inf counts = _np.zeros(shape=(nstates,), dtype=_np.intc) for s in range(len(bias_sequences)): for i in range(nstates): idx = (dtrajs[s] == i) nidx = idx.sum() if nidx == 0: continue counts[i] += nidx selected_bias_sequence = bias_sequences[s][idx, :] for k in range(nthermo): bias_matrix[k, i] = _logsumexp_pair( bias_matrix[k, i], _logsumexp( _np.ascontiguousarray(-selected_bias_sequence[:, k]), inplace=False)) idx = counts.nonzero() log_counts = _np.log(counts[idx]) bias_matrix *= -1.0 bias_matrix[:, idx] += log_counts[_np.newaxis, :] return bias_matrix
[ "def", "get_averaged_bias_matrix", "(", "bias_sequences", ",", "dtrajs", ",", "nstates", "=", "None", ")", ":", "from", "pyemma", ".", "thermo", ".", "extensions", ".", "util", "import", "(", "logsumexp", "as", "_logsumexp", ",", "logsumexp_pair", "as", "_logs...
r""" Computes a bias matrix via an exponential average of the observed frame wise bias energies. Parameters ---------- bias_sequences : list of numpy.ndarray(T_i, num_therm_states) A single reduced bias energy trajectory or a list of reduced bias energy trajectories. For every simulation frame seen in trajectory i and time step t, btrajs[i][t, k] is the reduced bias energy of that frame evaluated in the k'th thermodynamic state (i.e. at the k'th Umbrella/Hamiltonian/temperature) dtrajs : list of numpy.ndarray(T_i) of int A single discrete trajectory or a list of discrete trajectories. The integers are indexes in 0,...,num_conf_states-1 enumerating the num_conf_states Markov states or the bins the trajectory is in at any time. nstates : int, optional, default=None Number of configuration states. Returns ------- bias_matrix : numpy.ndarray(shape=(num_therm_states, num_conf_states)) object bias_energies_full[j, i] is the bias energy in units of kT for each discrete state i at thermodynamic state j.
[ "r", "Computes", "a", "bias", "matrix", "via", "an", "exponential", "average", "of", "the", "observed", "frame", "wise", "bias", "energies", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/thermo/util/util.py#L31-L83
train
204,186
markovmodel/PyEMMA
pyemma/thermo/util/util.py
get_umbrella_sampling_data
def get_umbrella_sampling_data( us_trajs, us_centers, us_force_constants, md_trajs=None, kT=None, width=None): r""" Wraps umbrella sampling data or a mix of umbrella sampling and and direct molecular dynamics. Parameters ---------- us_trajs : list of N arrays, each of shape (T_i, d) List of arrays, each having T_i rows, one for each time step, and d columns where d is the dimension in which umbrella sampling was applied. Often d=1, and thus us_trajs will be a list of 1d-arrays. us_centers : array-like of size N List or array of N center positions. Each position must be a d-dimensional vector. For 1d umbrella sampling, one can simply pass a list of centers, e.g. [-5.0, -4.0, -3.0, ... ]. us_force_constants : float or array-like of float The force constants used in the umbrellas, unit-less (e.g. kT per length unit). If different force constants were used for different umbrellas, a list or array of N force constants can be given. For multidimensional umbrella sampling, the force matrix must be used. md_trajs : list of M arrays, each of shape (T_i, d), optional, default=None Unbiased molecular dynamics simulations. Format like umbrella_trajs. kT : float (optinal) Use this attribute if the supplied force constants are NOT unit-less. width : array-like of float, optional, default=None Specify periodicity for individual us_traj dimensions. Each positive entry will make the corresponding feature periodic and use the given value as width. None/zero values will be treated as non-periodic. Returns ------- ttrajs : list of N+M int arrays, each of shape (T_i,) The integers are indexes in 0,...,K-1 enumerating the thermodynamic states the trajectories are in at any time. btrajs : list of N+M float arrays, each of shape (T_i, K) The floats are the reduced bias energies for each thermodynamic state and configuration. umbrella_centers : float array of shape (K, d) The individual umbrella centers labelled accordingly to ttrajs. force_constants : float array of shape (K, d, d) The individual force matrices labelled accordingly to ttrajs. unbiased_state : int or None Index of the unbiased thermodynamic state (if present). """ ttrajs, umbrella_centers, force_constants, unbiased_state = _get_umbrella_sampling_parameters( us_trajs, us_centers, us_force_constants, md_trajs=md_trajs, kT=kT) if md_trajs is None: md_trajs = [] if width is None: width = _np.zeros(shape=(umbrella_centers.shape[1],), dtype=_np.float64) else: width = _np.asarray( map(lambda w: w if w is not None and w > 0.0 else 0.0, width), dtype=_np.float64) if width.shape[0] != umbrella_centers.shape[1]: raise ValueError('Unmatching number of width components.') btrajs = _get_umbrella_bias_sequences( us_trajs + md_trajs, umbrella_centers, force_constants, width) return ttrajs, btrajs, umbrella_centers, force_constants, unbiased_state
python
def get_umbrella_sampling_data( us_trajs, us_centers, us_force_constants, md_trajs=None, kT=None, width=None): r""" Wraps umbrella sampling data or a mix of umbrella sampling and and direct molecular dynamics. Parameters ---------- us_trajs : list of N arrays, each of shape (T_i, d) List of arrays, each having T_i rows, one for each time step, and d columns where d is the dimension in which umbrella sampling was applied. Often d=1, and thus us_trajs will be a list of 1d-arrays. us_centers : array-like of size N List or array of N center positions. Each position must be a d-dimensional vector. For 1d umbrella sampling, one can simply pass a list of centers, e.g. [-5.0, -4.0, -3.0, ... ]. us_force_constants : float or array-like of float The force constants used in the umbrellas, unit-less (e.g. kT per length unit). If different force constants were used for different umbrellas, a list or array of N force constants can be given. For multidimensional umbrella sampling, the force matrix must be used. md_trajs : list of M arrays, each of shape (T_i, d), optional, default=None Unbiased molecular dynamics simulations. Format like umbrella_trajs. kT : float (optinal) Use this attribute if the supplied force constants are NOT unit-less. width : array-like of float, optional, default=None Specify periodicity for individual us_traj dimensions. Each positive entry will make the corresponding feature periodic and use the given value as width. None/zero values will be treated as non-periodic. Returns ------- ttrajs : list of N+M int arrays, each of shape (T_i,) The integers are indexes in 0,...,K-1 enumerating the thermodynamic states the trajectories are in at any time. btrajs : list of N+M float arrays, each of shape (T_i, K) The floats are the reduced bias energies for each thermodynamic state and configuration. umbrella_centers : float array of shape (K, d) The individual umbrella centers labelled accordingly to ttrajs. force_constants : float array of shape (K, d, d) The individual force matrices labelled accordingly to ttrajs. unbiased_state : int or None Index of the unbiased thermodynamic state (if present). """ ttrajs, umbrella_centers, force_constants, unbiased_state = _get_umbrella_sampling_parameters( us_trajs, us_centers, us_force_constants, md_trajs=md_trajs, kT=kT) if md_trajs is None: md_trajs = [] if width is None: width = _np.zeros(shape=(umbrella_centers.shape[1],), dtype=_np.float64) else: width = _np.asarray( map(lambda w: w if w is not None and w > 0.0 else 0.0, width), dtype=_np.float64) if width.shape[0] != umbrella_centers.shape[1]: raise ValueError('Unmatching number of width components.') btrajs = _get_umbrella_bias_sequences( us_trajs + md_trajs, umbrella_centers, force_constants, width) return ttrajs, btrajs, umbrella_centers, force_constants, unbiased_state
[ "def", "get_umbrella_sampling_data", "(", "us_trajs", ",", "us_centers", ",", "us_force_constants", ",", "md_trajs", "=", "None", ",", "kT", "=", "None", ",", "width", "=", "None", ")", ":", "ttrajs", ",", "umbrella_centers", ",", "force_constants", ",", "unbi...
r""" Wraps umbrella sampling data or a mix of umbrella sampling and and direct molecular dynamics. Parameters ---------- us_trajs : list of N arrays, each of shape (T_i, d) List of arrays, each having T_i rows, one for each time step, and d columns where d is the dimension in which umbrella sampling was applied. Often d=1, and thus us_trajs will be a list of 1d-arrays. us_centers : array-like of size N List or array of N center positions. Each position must be a d-dimensional vector. For 1d umbrella sampling, one can simply pass a list of centers, e.g. [-5.0, -4.0, -3.0, ... ]. us_force_constants : float or array-like of float The force constants used in the umbrellas, unit-less (e.g. kT per length unit). If different force constants were used for different umbrellas, a list or array of N force constants can be given. For multidimensional umbrella sampling, the force matrix must be used. md_trajs : list of M arrays, each of shape (T_i, d), optional, default=None Unbiased molecular dynamics simulations. Format like umbrella_trajs. kT : float (optinal) Use this attribute if the supplied force constants are NOT unit-less. width : array-like of float, optional, default=None Specify periodicity for individual us_traj dimensions. Each positive entry will make the corresponding feature periodic and use the given value as width. None/zero values will be treated as non-periodic. Returns ------- ttrajs : list of N+M int arrays, each of shape (T_i,) The integers are indexes in 0,...,K-1 enumerating the thermodynamic states the trajectories are in at any time. btrajs : list of N+M float arrays, each of shape (T_i, K) The floats are the reduced bias energies for each thermodynamic state and configuration. umbrella_centers : float array of shape (K, d) The individual umbrella centers labelled accordingly to ttrajs. force_constants : float array of shape (K, d, d) The individual force matrices labelled accordingly to ttrajs. unbiased_state : int or None Index of the unbiased thermodynamic state (if present).
[ "r", "Wraps", "umbrella", "sampling", "data", "or", "a", "mix", "of", "umbrella", "sampling", "and", "and", "direct", "molecular", "dynamics", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/thermo/util/util.py#L225-L280
train
204,187
markovmodel/PyEMMA
pyemma/thermo/util/util.py
get_multi_temperature_data
def get_multi_temperature_data( energy_trajs, temp_trajs, energy_unit, temp_unit, reference_temperature=None): r""" Wraps data from multi-temperature molecular dynamics. Parameters ---------- energy_trajs : list of N arrays, each of shape (T_i,) List of arrays, each having T_i rows, one for each time step, containing the potential energies time series in units of kT, kcal/mol or kJ/mol. temp_trajs : list of N int arrays, each of shape (T_i,) List of arrays, each having T_i rows, one for each time step, containing the heat bath temperature time series (at which temperatures the frames were created) in units of K or C. Alternatively, these trajectories may contain kT values instead of temperatures. energy_unit: str, optional, default='kcal/mol' The physical unit used for energies. Current options: kcal/mol, kJ/mol, kT. temp_unit : str, optional, default='K' The physical unit used for the temperature. Current options: K, C, kT reference_temperature : float or None, optional, default=None Reference temperature against which the bias energies are computed. If not given, the lowest temperature or kT value is used. If given, this parameter must have the same unit as the temp_trajs. Returns ------- ttrajs : list of N+M int arrays, each of shape (T_i,) The integers are indexes in 0,...,K-1 enumerating the thermodynamic states the trajectories are in at any time. btrajs : list of N+M float arrays, each of shape (T_i, K) The floats are the reduced bias energies for each thermodynamic state and configuration. temperatures : float array of length K The individual temperatures labelled accordingly to ttrajs. unbiased_state : int or None Index of the unbiased thermodynamic state (if present). """ ttrajs, temperatures = _get_multi_temperature_parameters(temp_trajs) if reference_temperature is None: reference_temperature = temperatures.min() else: assert isinstance(reference_temperature, (int, float)), \ 'reference_temperature must be numeric' assert reference_temperature > 0.0, 'reference_temperature must be positive' btrajs = _get_multi_temperature_bias_sequences( energy_trajs, temp_trajs, temperatures, reference_temperature, energy_unit, temp_unit) if reference_temperature in temperatures: unbiased_state = _np.where(temperatures == reference_temperature)[0] try: unbiased_state = unbiased_state[0] except IndexError: unbiased_state = None else: unbiased_state = None return ttrajs, btrajs, temperatures, unbiased_state
python
def get_multi_temperature_data( energy_trajs, temp_trajs, energy_unit, temp_unit, reference_temperature=None): r""" Wraps data from multi-temperature molecular dynamics. Parameters ---------- energy_trajs : list of N arrays, each of shape (T_i,) List of arrays, each having T_i rows, one for each time step, containing the potential energies time series in units of kT, kcal/mol or kJ/mol. temp_trajs : list of N int arrays, each of shape (T_i,) List of arrays, each having T_i rows, one for each time step, containing the heat bath temperature time series (at which temperatures the frames were created) in units of K or C. Alternatively, these trajectories may contain kT values instead of temperatures. energy_unit: str, optional, default='kcal/mol' The physical unit used for energies. Current options: kcal/mol, kJ/mol, kT. temp_unit : str, optional, default='K' The physical unit used for the temperature. Current options: K, C, kT reference_temperature : float or None, optional, default=None Reference temperature against which the bias energies are computed. If not given, the lowest temperature or kT value is used. If given, this parameter must have the same unit as the temp_trajs. Returns ------- ttrajs : list of N+M int arrays, each of shape (T_i,) The integers are indexes in 0,...,K-1 enumerating the thermodynamic states the trajectories are in at any time. btrajs : list of N+M float arrays, each of shape (T_i, K) The floats are the reduced bias energies for each thermodynamic state and configuration. temperatures : float array of length K The individual temperatures labelled accordingly to ttrajs. unbiased_state : int or None Index of the unbiased thermodynamic state (if present). """ ttrajs, temperatures = _get_multi_temperature_parameters(temp_trajs) if reference_temperature is None: reference_temperature = temperatures.min() else: assert isinstance(reference_temperature, (int, float)), \ 'reference_temperature must be numeric' assert reference_temperature > 0.0, 'reference_temperature must be positive' btrajs = _get_multi_temperature_bias_sequences( energy_trajs, temp_trajs, temperatures, reference_temperature, energy_unit, temp_unit) if reference_temperature in temperatures: unbiased_state = _np.where(temperatures == reference_temperature)[0] try: unbiased_state = unbiased_state[0] except IndexError: unbiased_state = None else: unbiased_state = None return ttrajs, btrajs, temperatures, unbiased_state
[ "def", "get_multi_temperature_data", "(", "energy_trajs", ",", "temp_trajs", ",", "energy_unit", ",", "temp_unit", ",", "reference_temperature", "=", "None", ")", ":", "ttrajs", ",", "temperatures", "=", "_get_multi_temperature_parameters", "(", "temp_trajs", ")", "if...
r""" Wraps data from multi-temperature molecular dynamics. Parameters ---------- energy_trajs : list of N arrays, each of shape (T_i,) List of arrays, each having T_i rows, one for each time step, containing the potential energies time series in units of kT, kcal/mol or kJ/mol. temp_trajs : list of N int arrays, each of shape (T_i,) List of arrays, each having T_i rows, one for each time step, containing the heat bath temperature time series (at which temperatures the frames were created) in units of K or C. Alternatively, these trajectories may contain kT values instead of temperatures. energy_unit: str, optional, default='kcal/mol' The physical unit used for energies. Current options: kcal/mol, kJ/mol, kT. temp_unit : str, optional, default='K' The physical unit used for the temperature. Current options: K, C, kT reference_temperature : float or None, optional, default=None Reference temperature against which the bias energies are computed. If not given, the lowest temperature or kT value is used. If given, this parameter must have the same unit as the temp_trajs. Returns ------- ttrajs : list of N+M int arrays, each of shape (T_i,) The integers are indexes in 0,...,K-1 enumerating the thermodynamic states the trajectories are in at any time. btrajs : list of N+M float arrays, each of shape (T_i, K) The floats are the reduced bias energies for each thermodynamic state and configuration. temperatures : float array of length K The individual temperatures labelled accordingly to ttrajs. unbiased_state : int or None Index of the unbiased thermodynamic state (if present).
[ "r", "Wraps", "data", "from", "multi", "-", "temperature", "molecular", "dynamics", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/thermo/util/util.py#L343-L395
train
204,188
markovmodel/PyEMMA
pyemma/thermo/util/util.py
assign_unbiased_state_label
def assign_unbiased_state_label(memm_list, unbiased_state): r""" Sets the msm label for the given list of estimated MEMM objects. Parameters ---------- memm_list : list of estimated MEMM objects The MEMM objects which shall have the msm label set. unbiased_state : int or None Index of the unbiased thermodynamic state (if present). """ if unbiased_state is None: return for memm in memm_list: assert 0 <= unbiased_state < len(memm.models), "invalid state: " + str(unbiased_state) memm._unbiased_state = unbiased_state
python
def assign_unbiased_state_label(memm_list, unbiased_state): r""" Sets the msm label for the given list of estimated MEMM objects. Parameters ---------- memm_list : list of estimated MEMM objects The MEMM objects which shall have the msm label set. unbiased_state : int or None Index of the unbiased thermodynamic state (if present). """ if unbiased_state is None: return for memm in memm_list: assert 0 <= unbiased_state < len(memm.models), "invalid state: " + str(unbiased_state) memm._unbiased_state = unbiased_state
[ "def", "assign_unbiased_state_label", "(", "memm_list", ",", "unbiased_state", ")", ":", "if", "unbiased_state", "is", "None", ":", "return", "for", "memm", "in", "memm_list", ":", "assert", "0", "<=", "unbiased_state", "<", "len", "(", "memm", ".", "models", ...
r""" Sets the msm label for the given list of estimated MEMM objects. Parameters ---------- memm_list : list of estimated MEMM objects The MEMM objects which shall have the msm label set. unbiased_state : int or None Index of the unbiased thermodynamic state (if present).
[ "r", "Sets", "the", "msm", "label", "for", "the", "given", "list", "of", "estimated", "MEMM", "objects", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/thermo/util/util.py#L401-L416
train
204,189
markovmodel/PyEMMA
pyemma/msm/api.py
timescales_msm
def timescales_msm(dtrajs, lags=None, nits=None, reversible=True, connected=True, weights='empirical', errors=None, nsamples=50, n_jobs=None, show_progress=True, mincount_connectivity='1/n', only_timescales=False): # format data r""" Implied timescales from Markov state models estimated at a series of lag times. Parameters ---------- dtrajs : array-like or list of array-likes discrete trajectories lags : int, array-like with integers or None, optional integer lag times at which the implied timescales will be calculated. If set to None (default) as list of lag times will be automatically generated. For a single int, generate a set of lag times starting from 1 to lags, using a multiplier of 1.5 between successive lags. nits : int, optional number of implied timescales to be computed. Will compute less if the number of states are smaller. If None, the number of timescales will be automatically determined. reversible : boolean, optional Estimate transition matrix reversibly (True) or nonreversibly (False) connected : boolean, optional If true compute the connected set before transition matrix estimation at each lag separately weights : str, optional can be used to re-weight non-equilibrium data to equilibrium. Must be one of the following: * 'empirical': Each trajectory frame counts as one. (default) * 'oom': Each transition is re-weighted using OOM theory, see [5]_. errors : None | 'bayes', optional Specifies whether to compute statistical uncertainties (by default not), an which algorithm to use if yes. Currently the only option is: * 'bayes' for Bayesian sampling of the posterior Attention: * The Bayes mode will use an estimate for the effective count matrix that may produce somewhat different estimates than the 'sliding window' estimate used with ``errors=None`` by default. * Computing errors can be// slow if the MSM has many states. * There are still unsolved theoretical problems in the computation of effective count matrices, and therefore the uncertainty interval and the maximum likelihood estimator can be inconsistent. Use this as a rough guess for statistical uncertainties. nsamples : int, optional The number of approximately independent transition matrix samples generated for each lag time for uncertainty quantification. Only used if errors is not None. n_jobs : int, optional how many subprocesses to start to estimate the models for each lag time. show_progress : bool, default=True whether to show progress of estimation. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. only_timescales: bool, default=False If you are only interested in the timescales and its samples, you can consider turning this on in order to save memory. This can be useful to avoid blowing up memory with BayesianMSM and lots of samples. Returns ------- itsobj : :class:`ImpliedTimescales <pyemma.msm.estimators.implied_timescales.ImpliedTimescales>` object Example ------- >>> from pyemma import msm >>> dtraj = [0,1,1,2,2,2,1,2,2,2,1,0,0,1,1,1,2,2,1,1,2,1,1,0,0,0,1,1,2,2,1] # mini-trajectory >>> ts = msm.its(dtraj, [1,2,3,4,5], show_progress=False) >>> print(ts.timescales) # doctest: +ELLIPSIS [[ 1.5... 0.2...] [ 3.1... 1.0...] [ 2.03... 1.02...] [ 4.63... 3.42...] [ 5.13... 2.59...]] See also -------- ImpliedTimescales The object returned by this function. pyemma.plots.plot_implied_timescales Implied timescales plotting function. Just call it with the :class:`ImpliedTimescales <pyemma.msm.estimators.ImpliedTimescales>` object produced by this function as an argument. .. autoclass:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :attributes: References ---------- Implied timescales as a lagtime-selection and MSM-validation approach were suggested in [1]_. Error estimation is done either using moving block bootstrapping [2]_ or a Bayesian analysis using Metropolis-Hastings Monte Carlo sampling of the posterior. Nonreversible Bayesian sampling is done by independently sampling Dirichtlet distributions of the transition matrix rows. A Monte Carlo method for sampling reversible MSMs was introduced in [3]_. Here we employ a much more efficient algorithm introduced in [4]_. .. [1] Swope, W. C. and J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory. J. Phys. Chem. B 108: 6571-6581 (2004) .. [2] Kuensch, H. R.: The jackknife and the bootstrap for general stationary observations. Ann. Stat. 17, 1217-1241 (1989) .. [3] Noe, F.: Probability Distributions of Molecular Observables computed from Markov Models. J. Chem. Phys. 128, 244103 (2008) .. [4] Trendelkamp-Schroer, B, H. Wu, F. Paul and F. Noe: Estimation and uncertainty of reversible Markov models. http://arxiv.org/abs/1507.05990 .. [5] Nueske, F., Wu, H., Prinz, J.-H., Wehmeyer, C., Clementi, C. and Noe, F.: Markov State Models from short non-Equilibrium Simulations - Analysis and Correction of Estimation Bias J. Chem. Phys. (submitted) (2017) """ # Catch invalid inputs for weights: if isinstance(weights, str): if weights not in ['empirical', 'oom']: raise ValueError("Weights must be either \'empirical\' or \'oom\'") else: raise ValueError("Weights must be either \'empirical\' or \'oom\'") # Set errors to None if weights==oom: if weights == 'oom' and (errors is not None): errors = None # format data dtrajs = _types.ensure_dtraj_list(dtrajs) if connected: connectivity = 'largest' else: connectivity = 'none' # Choose estimator: if errors is None: if weights == 'empirical': estimator = _ML_MSM(reversible=reversible, connectivity=connectivity) else: estimator = _OOM_MSM(reversible=reversible, connectivity=connectivity) elif errors == 'bayes': estimator = _Bayes_MSM(reversible=reversible, connectivity=connectivity, nsamples=nsamples, show_progress=show_progress) else: raise NotImplementedError('Error estimation method {errors} currently not implemented'.format(errors=errors)) if hasattr(estimator, 'mincount_connectivity'): estimator.mincount_connectivity = mincount_connectivity # go itsobj = _ImpliedTimescales(estimator, lags=lags, nits=nits, n_jobs=n_jobs, show_progress=show_progress, only_timescales=only_timescales) itsobj.estimate(dtrajs) return itsobj
python
def timescales_msm(dtrajs, lags=None, nits=None, reversible=True, connected=True, weights='empirical', errors=None, nsamples=50, n_jobs=None, show_progress=True, mincount_connectivity='1/n', only_timescales=False): # format data r""" Implied timescales from Markov state models estimated at a series of lag times. Parameters ---------- dtrajs : array-like or list of array-likes discrete trajectories lags : int, array-like with integers or None, optional integer lag times at which the implied timescales will be calculated. If set to None (default) as list of lag times will be automatically generated. For a single int, generate a set of lag times starting from 1 to lags, using a multiplier of 1.5 between successive lags. nits : int, optional number of implied timescales to be computed. Will compute less if the number of states are smaller. If None, the number of timescales will be automatically determined. reversible : boolean, optional Estimate transition matrix reversibly (True) or nonreversibly (False) connected : boolean, optional If true compute the connected set before transition matrix estimation at each lag separately weights : str, optional can be used to re-weight non-equilibrium data to equilibrium. Must be one of the following: * 'empirical': Each trajectory frame counts as one. (default) * 'oom': Each transition is re-weighted using OOM theory, see [5]_. errors : None | 'bayes', optional Specifies whether to compute statistical uncertainties (by default not), an which algorithm to use if yes. Currently the only option is: * 'bayes' for Bayesian sampling of the posterior Attention: * The Bayes mode will use an estimate for the effective count matrix that may produce somewhat different estimates than the 'sliding window' estimate used with ``errors=None`` by default. * Computing errors can be// slow if the MSM has many states. * There are still unsolved theoretical problems in the computation of effective count matrices, and therefore the uncertainty interval and the maximum likelihood estimator can be inconsistent. Use this as a rough guess for statistical uncertainties. nsamples : int, optional The number of approximately independent transition matrix samples generated for each lag time for uncertainty quantification. Only used if errors is not None. n_jobs : int, optional how many subprocesses to start to estimate the models for each lag time. show_progress : bool, default=True whether to show progress of estimation. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. only_timescales: bool, default=False If you are only interested in the timescales and its samples, you can consider turning this on in order to save memory. This can be useful to avoid blowing up memory with BayesianMSM and lots of samples. Returns ------- itsobj : :class:`ImpliedTimescales <pyemma.msm.estimators.implied_timescales.ImpliedTimescales>` object Example ------- >>> from pyemma import msm >>> dtraj = [0,1,1,2,2,2,1,2,2,2,1,0,0,1,1,1,2,2,1,1,2,1,1,0,0,0,1,1,2,2,1] # mini-trajectory >>> ts = msm.its(dtraj, [1,2,3,4,5], show_progress=False) >>> print(ts.timescales) # doctest: +ELLIPSIS [[ 1.5... 0.2...] [ 3.1... 1.0...] [ 2.03... 1.02...] [ 4.63... 3.42...] [ 5.13... 2.59...]] See also -------- ImpliedTimescales The object returned by this function. pyemma.plots.plot_implied_timescales Implied timescales plotting function. Just call it with the :class:`ImpliedTimescales <pyemma.msm.estimators.ImpliedTimescales>` object produced by this function as an argument. .. autoclass:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :attributes: References ---------- Implied timescales as a lagtime-selection and MSM-validation approach were suggested in [1]_. Error estimation is done either using moving block bootstrapping [2]_ or a Bayesian analysis using Metropolis-Hastings Monte Carlo sampling of the posterior. Nonreversible Bayesian sampling is done by independently sampling Dirichtlet distributions of the transition matrix rows. A Monte Carlo method for sampling reversible MSMs was introduced in [3]_. Here we employ a much more efficient algorithm introduced in [4]_. .. [1] Swope, W. C. and J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory. J. Phys. Chem. B 108: 6571-6581 (2004) .. [2] Kuensch, H. R.: The jackknife and the bootstrap for general stationary observations. Ann. Stat. 17, 1217-1241 (1989) .. [3] Noe, F.: Probability Distributions of Molecular Observables computed from Markov Models. J. Chem. Phys. 128, 244103 (2008) .. [4] Trendelkamp-Schroer, B, H. Wu, F. Paul and F. Noe: Estimation and uncertainty of reversible Markov models. http://arxiv.org/abs/1507.05990 .. [5] Nueske, F., Wu, H., Prinz, J.-H., Wehmeyer, C., Clementi, C. and Noe, F.: Markov State Models from short non-Equilibrium Simulations - Analysis and Correction of Estimation Bias J. Chem. Phys. (submitted) (2017) """ # Catch invalid inputs for weights: if isinstance(weights, str): if weights not in ['empirical', 'oom']: raise ValueError("Weights must be either \'empirical\' or \'oom\'") else: raise ValueError("Weights must be either \'empirical\' or \'oom\'") # Set errors to None if weights==oom: if weights == 'oom' and (errors is not None): errors = None # format data dtrajs = _types.ensure_dtraj_list(dtrajs) if connected: connectivity = 'largest' else: connectivity = 'none' # Choose estimator: if errors is None: if weights == 'empirical': estimator = _ML_MSM(reversible=reversible, connectivity=connectivity) else: estimator = _OOM_MSM(reversible=reversible, connectivity=connectivity) elif errors == 'bayes': estimator = _Bayes_MSM(reversible=reversible, connectivity=connectivity, nsamples=nsamples, show_progress=show_progress) else: raise NotImplementedError('Error estimation method {errors} currently not implemented'.format(errors=errors)) if hasattr(estimator, 'mincount_connectivity'): estimator.mincount_connectivity = mincount_connectivity # go itsobj = _ImpliedTimescales(estimator, lags=lags, nits=nits, n_jobs=n_jobs, show_progress=show_progress, only_timescales=only_timescales) itsobj.estimate(dtrajs) return itsobj
[ "def", "timescales_msm", "(", "dtrajs", ",", "lags", "=", "None", ",", "nits", "=", "None", ",", "reversible", "=", "True", ",", "connected", "=", "True", ",", "weights", "=", "'empirical'", ",", "errors", "=", "None", ",", "nsamples", "=", "50", ",", ...
r""" Implied timescales from Markov state models estimated at a series of lag times. Parameters ---------- dtrajs : array-like or list of array-likes discrete trajectories lags : int, array-like with integers or None, optional integer lag times at which the implied timescales will be calculated. If set to None (default) as list of lag times will be automatically generated. For a single int, generate a set of lag times starting from 1 to lags, using a multiplier of 1.5 between successive lags. nits : int, optional number of implied timescales to be computed. Will compute less if the number of states are smaller. If None, the number of timescales will be automatically determined. reversible : boolean, optional Estimate transition matrix reversibly (True) or nonreversibly (False) connected : boolean, optional If true compute the connected set before transition matrix estimation at each lag separately weights : str, optional can be used to re-weight non-equilibrium data to equilibrium. Must be one of the following: * 'empirical': Each trajectory frame counts as one. (default) * 'oom': Each transition is re-weighted using OOM theory, see [5]_. errors : None | 'bayes', optional Specifies whether to compute statistical uncertainties (by default not), an which algorithm to use if yes. Currently the only option is: * 'bayes' for Bayesian sampling of the posterior Attention: * The Bayes mode will use an estimate for the effective count matrix that may produce somewhat different estimates than the 'sliding window' estimate used with ``errors=None`` by default. * Computing errors can be// slow if the MSM has many states. * There are still unsolved theoretical problems in the computation of effective count matrices, and therefore the uncertainty interval and the maximum likelihood estimator can be inconsistent. Use this as a rough guess for statistical uncertainties. nsamples : int, optional The number of approximately independent transition matrix samples generated for each lag time for uncertainty quantification. Only used if errors is not None. n_jobs : int, optional how many subprocesses to start to estimate the models for each lag time. show_progress : bool, default=True whether to show progress of estimation. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. only_timescales: bool, default=False If you are only interested in the timescales and its samples, you can consider turning this on in order to save memory. This can be useful to avoid blowing up memory with BayesianMSM and lots of samples. Returns ------- itsobj : :class:`ImpliedTimescales <pyemma.msm.estimators.implied_timescales.ImpliedTimescales>` object Example ------- >>> from pyemma import msm >>> dtraj = [0,1,1,2,2,2,1,2,2,2,1,0,0,1,1,1,2,2,1,1,2,1,1,0,0,0,1,1,2,2,1] # mini-trajectory >>> ts = msm.its(dtraj, [1,2,3,4,5], show_progress=False) >>> print(ts.timescales) # doctest: +ELLIPSIS [[ 1.5... 0.2...] [ 3.1... 1.0...] [ 2.03... 1.02...] [ 4.63... 3.42...] [ 5.13... 2.59...]] See also -------- ImpliedTimescales The object returned by this function. pyemma.plots.plot_implied_timescales Implied timescales plotting function. Just call it with the :class:`ImpliedTimescales <pyemma.msm.estimators.ImpliedTimescales>` object produced by this function as an argument. .. autoclass:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :attributes: References ---------- Implied timescales as a lagtime-selection and MSM-validation approach were suggested in [1]_. Error estimation is done either using moving block bootstrapping [2]_ or a Bayesian analysis using Metropolis-Hastings Monte Carlo sampling of the posterior. Nonreversible Bayesian sampling is done by independently sampling Dirichtlet distributions of the transition matrix rows. A Monte Carlo method for sampling reversible MSMs was introduced in [3]_. Here we employ a much more efficient algorithm introduced in [4]_. .. [1] Swope, W. C. and J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory. J. Phys. Chem. B 108: 6571-6581 (2004) .. [2] Kuensch, H. R.: The jackknife and the bootstrap for general stationary observations. Ann. Stat. 17, 1217-1241 (1989) .. [3] Noe, F.: Probability Distributions of Molecular Observables computed from Markov Models. J. Chem. Phys. 128, 244103 (2008) .. [4] Trendelkamp-Schroer, B, H. Wu, F. Paul and F. Noe: Estimation and uncertainty of reversible Markov models. http://arxiv.org/abs/1507.05990 .. [5] Nueske, F., Wu, H., Prinz, J.-H., Wehmeyer, C., Clementi, C. and Noe, F.: Markov State Models from short non-Equilibrium Simulations - Analysis and Correction of Estimation Bias J. Chem. Phys. (submitted) (2017)
[ "r", "Implied", "timescales", "from", "Markov", "state", "models", "estimated", "at", "a", "series", "of", "lag", "times", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/api.py#L61-L236
train
204,190
markovmodel/PyEMMA
pyemma/msm/api.py
estimate_markov_model
def estimate_markov_model(dtrajs, lag, reversible=True, statdist=None, count_mode='sliding', weights='empirical', sparse=False, connectivity='largest', dt_traj='1 step', maxiter=1000000, maxerr=1e-8, score_method='VAMP2', score_k=10, mincount_connectivity='1/n'): r""" Estimates a Markov model from discrete trajectories Returns a :class:`MaximumLikelihoodMSM` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lag time at which transitions are counted and the transition matrix is estimated. reversible : bool, optional If true compute reversible MSM, else non-reversible MSM statdist : (M,) ndarray, optional Stationary vector on the full state-space. Transition matrix will be estimated such that statdist is its equilibrium distribution. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/\tau)-1) \tau \rightarrow T) weights : str, optional can be used to re-weight non-equilibrium data to equilibrium. Must be one of the following: * 'empirical': Each trajectory frame counts as one. (default) * 'oom': Each transition is re-weighted using OOM theory, see [11]_. sparse : bool, optional If true compute count matrix, transition matrix and all derived quantities using sparse matrix algebra. In this case python sparse matrices will be returned by the corresponding functions instead of numpy arrays. This behavior is suggested for very large numbers of states (e.g. > 4000) because it is likely to be much more efficient. connectivity : str, optional Connectivity mode. Three methods are intended (currently only 'largest' is implemented) * 'largest' : The active set is the largest reversibly connected set. All estimation will be done on this subset and all quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than the full set of states * 'all' : The active set is the full set of states. Estimation will be conducted on each reversibly connected set separately. That means the transition matrix will decompose into disconnected submatrices, the stationary vector is only defined within subsets, etc. Currently not implemented. * 'none' : The active set is the full set of states. Estimation will be conducted on the full set of states without ensuring connectivity. This only permits nonreversible estimation. Currently not implemented. dt_traj : str, optional Description of the physical time corresponding to the lag. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): * 'fs', 'femtosecond*' * 'ps', 'picosecond*' * 'ns', 'nanosecond*' * 'us', 'microsecond*' * 'ms', 'millisecond*' * 's', 'second*' maxiter : int, optional Optional parameter with reversible = True. maximum number of iterations before the transition matrix estimation method exits maxerr : float, optional Optional parameter with reversible = True. convergence tolerance for transition matrix estimation. This specifies the maximum change of the Euclidean norm of relative stationary probabilities (:math:`x_i = \sum_k x_{ik}`). The relative stationary probability changes :math:`e_i = (x_i^{(1)} - x_i^{(2)})/(x_i^{(1)} + x_i^{(2)})` are used in order to track changes in small probabilities. The Euclidean norm of the change vector, :math:`|e_i|_2`, is compared to maxerr. score_method : str, optional, default='VAMP2' Score to be used with MSM score function. Available scores are based on the variational approach for Markov processes [13]_ [14]_: * 'VAMP1' Sum of singular values of the symmetrized transition matrix [14]_ . If the MSM is reversible, this is equal to the sum of transition matrix eigenvalues, also called Rayleigh quotient [13]_ [15]_ . * 'VAMP2' Sum of squared singular values of the symmetrized transition matrix [14]_ . If the MSM is reversible, this is equal to the kinetic variance [16]_ . score_k : int or None The maximum number of eigenvalues or singular values used in the score. If set to None, all available eigenvalues will be used. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. Returns ------- msm : :class:`MaximumLikelihoodMSM <pyemma.msm.MaximumLikelihoodMSM>` Estimator object containing the MSM and estimation information. See also -------- MaximumLikelihoodMSM An MSM object that has been estimated from data .. autoclass:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :attributes: References ---------- The mathematical theory of Markov (state) model estimation was introduced in [1]_ . Further theoretical developments were made in [2]_ . The term Markov state model was coined in [3]_ . Continuous-time Markov models (Master equation models) were suggested in [4]_. Reversible Markov model estimation was introduced in [5]_ , and further developed in [6]_ [7]_ [9]_ . It was shown in [8]_ that the quality of Markov state models does in fact not depend on memory loss, but rather on where the discretization is suitable to approximate the eigenfunctions of the Markov operator (the 'reaction coordinates'). With a suitable choice of discretization and lag time, MSMs can thus become very accurate. [9]_ introduced a number of methodological improvements and gives a good overview of the methodological basics of Markov state modeling today. [10]_ is a more extensive review book of theory, methods and applications. .. [1] Schuette, C. , A. Fischer, W. Huisinga and P. Deuflhard: A Direct Approach to Conformational Dynamics based on Hybrid Monte Carlo. J. Comput. Phys., 151, 146-168 (1999) .. [2] Swope, W. C., J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory J. Phys. Chem. B 108, 6571-6581 (2004) .. [3] Singhal, N., C. D. Snow, V. S. Pande: Using path sampling to build better Markovian state models: Predicting the folding rate and mechanism of a tryptophan zipper beta hairpin. J. Chem. Phys. 121, 415 (2004). .. [4] Sriraman, S., I. G. Kevrekidis and G. Hummer, G. J. Phys. Chem. B 109, 6479-6484 (2005) .. [5] Noe, F.: Probability Distributions of Molecular Observables computed from Markov Models. J. Chem. Phys. 128, 244103 (2008) .. [6] Buchete, N.-V. and Hummer, G.: Coarse master equations for peptide folding dynamics. J. Phys. Chem. B 112, 6057--6069 (2008) .. [7] Bowman, G. R., K. A. Beauchamp, G. Boxer and V. S. Pande: Progress and challenges in the automated construction of Markov state models for full protein systems. J. Chem. Phys. 131, 124101 (2009) .. [8] Sarich, M., F. Noe and C. Schuette: On the approximation quality of Markov state models. SIAM Multiscale Model. Simul. 8, 1154-1177 (2010) .. [9] Prinz, J.-H., H. Wu, M. Sarich, B. Keller, M. Senne, M. Held, J. D. Chodera, C. Schuette and F. Noe: Markov models of molecular kinetics: Generation and Validation J. Chem. Phys. 134, 174105 (2011) .. [10] Bowman, G. R., V. S. Pande and F. Noe: An Introduction to Markov State Models and Their Application to Long Timescale Molecular Simulation. Advances in Experimental Medicine and Biology 797, Springer, Heidelberg (2014) .. [11] Nueske, F., Wu, H., Prinz, J.-H., Wehmeyer, C., Clementi, C. and Noe, F.: Markov State Models from short non-Equilibrium Simulations - Analysis and Correction of Estimation Bias J. Chem. Phys. (submitted) (2017) .. [12] H. Wu and F. Noe: Variational approach for learning Markov processes from time series data (in preparation) .. [13] Noe, F. and F. Nueske: A variational approach to modeling slow processes in stochastic dynamical systems. SIAM Multiscale Model. Simul. 11, 635-655 (2013). .. [14] Wu, H and F. Noe: Variational approach for learning Markov processes from time series data (in preparation) .. [15] McGibbon, R and V. S. Pande: Variational cross-validation of slow dynamical modes in molecular kinetics, J. Chem. Phys. 142, 124105 (2015) .. [16] Noe, F. and C. Clementi: Kinetic distance and kinetic maps from molecular dynamics simulation. J. Chem. Theory Comput. 11, 5002-5011 (2015) Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.estimate_markov_model(dtrajs, 2) Which is the active set of states we are working on? >>> print(mm.active_set) [0 1 2] Show the count matrix >>> print(mm.count_matrix_active) [[ 7. 2. 1.] [ 2. 0. 4.] [ 2. 3. 9.]] Show the estimated transition matrix >>> print(mm.transition_matrix) [[ 0.7 0.167 0.133] [ 0.388 0. 0.612] [ 0.119 0.238 0.643]] Is this model reversible (i.e. does it fulfill detailed balance)? >>> print(mm.is_reversible) True What is the equilibrium distribution of states? >>> print(mm.stationary_distribution) [ 0.393 0.17 0.437] Relaxation timescales? >>> print(mm.timescales()) [ 3.415 1.297] Mean first passage time from state 0 to 2: >>> print(mm.mfpt(0, 2)) # doctest: +ELLIPSIS 9.929... """ # Catch invalid inputs for weights: if isinstance(weights, str): if weights not in ['empirical', 'oom']: raise ValueError("Weights must be either \'empirical\' or \'oom\'") else: raise ValueError("Weights must be either \'empirical\' or \'oom\'") # transition matrix estimator if weights == 'empirical': mlmsm = _ML_MSM(lag=lag, reversible=reversible, statdist_constraint=statdist, count_mode=count_mode, sparse=sparse, connectivity=connectivity, dt_traj=dt_traj, maxiter=maxiter, maxerr=maxerr, score_method=score_method, score_k=score_k, mincount_connectivity=mincount_connectivity) # estimate and return return mlmsm.estimate(dtrajs) elif weights == 'oom': if (statdist is not None) or (maxiter != 1000000) or (maxerr != 1e-8): import warnings warnings.warn("Values for statdist, maxiter or maxerr are ignored if OOM-correction is used.") oom_msm = _OOM_MSM(lag=lag, reversible=reversible, count_mode=count_mode, sparse=sparse, connectivity=connectivity, dt_traj=dt_traj, score_method=score_method, score_k=score_k, mincount_connectivity=mincount_connectivity) # estimate and return return oom_msm.estimate(dtrajs)
python
def estimate_markov_model(dtrajs, lag, reversible=True, statdist=None, count_mode='sliding', weights='empirical', sparse=False, connectivity='largest', dt_traj='1 step', maxiter=1000000, maxerr=1e-8, score_method='VAMP2', score_k=10, mincount_connectivity='1/n'): r""" Estimates a Markov model from discrete trajectories Returns a :class:`MaximumLikelihoodMSM` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lag time at which transitions are counted and the transition matrix is estimated. reversible : bool, optional If true compute reversible MSM, else non-reversible MSM statdist : (M,) ndarray, optional Stationary vector on the full state-space. Transition matrix will be estimated such that statdist is its equilibrium distribution. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/\tau)-1) \tau \rightarrow T) weights : str, optional can be used to re-weight non-equilibrium data to equilibrium. Must be one of the following: * 'empirical': Each trajectory frame counts as one. (default) * 'oom': Each transition is re-weighted using OOM theory, see [11]_. sparse : bool, optional If true compute count matrix, transition matrix and all derived quantities using sparse matrix algebra. In this case python sparse matrices will be returned by the corresponding functions instead of numpy arrays. This behavior is suggested for very large numbers of states (e.g. > 4000) because it is likely to be much more efficient. connectivity : str, optional Connectivity mode. Three methods are intended (currently only 'largest' is implemented) * 'largest' : The active set is the largest reversibly connected set. All estimation will be done on this subset and all quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than the full set of states * 'all' : The active set is the full set of states. Estimation will be conducted on each reversibly connected set separately. That means the transition matrix will decompose into disconnected submatrices, the stationary vector is only defined within subsets, etc. Currently not implemented. * 'none' : The active set is the full set of states. Estimation will be conducted on the full set of states without ensuring connectivity. This only permits nonreversible estimation. Currently not implemented. dt_traj : str, optional Description of the physical time corresponding to the lag. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): * 'fs', 'femtosecond*' * 'ps', 'picosecond*' * 'ns', 'nanosecond*' * 'us', 'microsecond*' * 'ms', 'millisecond*' * 's', 'second*' maxiter : int, optional Optional parameter with reversible = True. maximum number of iterations before the transition matrix estimation method exits maxerr : float, optional Optional parameter with reversible = True. convergence tolerance for transition matrix estimation. This specifies the maximum change of the Euclidean norm of relative stationary probabilities (:math:`x_i = \sum_k x_{ik}`). The relative stationary probability changes :math:`e_i = (x_i^{(1)} - x_i^{(2)})/(x_i^{(1)} + x_i^{(2)})` are used in order to track changes in small probabilities. The Euclidean norm of the change vector, :math:`|e_i|_2`, is compared to maxerr. score_method : str, optional, default='VAMP2' Score to be used with MSM score function. Available scores are based on the variational approach for Markov processes [13]_ [14]_: * 'VAMP1' Sum of singular values of the symmetrized transition matrix [14]_ . If the MSM is reversible, this is equal to the sum of transition matrix eigenvalues, also called Rayleigh quotient [13]_ [15]_ . * 'VAMP2' Sum of squared singular values of the symmetrized transition matrix [14]_ . If the MSM is reversible, this is equal to the kinetic variance [16]_ . score_k : int or None The maximum number of eigenvalues or singular values used in the score. If set to None, all available eigenvalues will be used. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. Returns ------- msm : :class:`MaximumLikelihoodMSM <pyemma.msm.MaximumLikelihoodMSM>` Estimator object containing the MSM and estimation information. See also -------- MaximumLikelihoodMSM An MSM object that has been estimated from data .. autoclass:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :attributes: References ---------- The mathematical theory of Markov (state) model estimation was introduced in [1]_ . Further theoretical developments were made in [2]_ . The term Markov state model was coined in [3]_ . Continuous-time Markov models (Master equation models) were suggested in [4]_. Reversible Markov model estimation was introduced in [5]_ , and further developed in [6]_ [7]_ [9]_ . It was shown in [8]_ that the quality of Markov state models does in fact not depend on memory loss, but rather on where the discretization is suitable to approximate the eigenfunctions of the Markov operator (the 'reaction coordinates'). With a suitable choice of discretization and lag time, MSMs can thus become very accurate. [9]_ introduced a number of methodological improvements and gives a good overview of the methodological basics of Markov state modeling today. [10]_ is a more extensive review book of theory, methods and applications. .. [1] Schuette, C. , A. Fischer, W. Huisinga and P. Deuflhard: A Direct Approach to Conformational Dynamics based on Hybrid Monte Carlo. J. Comput. Phys., 151, 146-168 (1999) .. [2] Swope, W. C., J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory J. Phys. Chem. B 108, 6571-6581 (2004) .. [3] Singhal, N., C. D. Snow, V. S. Pande: Using path sampling to build better Markovian state models: Predicting the folding rate and mechanism of a tryptophan zipper beta hairpin. J. Chem. Phys. 121, 415 (2004). .. [4] Sriraman, S., I. G. Kevrekidis and G. Hummer, G. J. Phys. Chem. B 109, 6479-6484 (2005) .. [5] Noe, F.: Probability Distributions of Molecular Observables computed from Markov Models. J. Chem. Phys. 128, 244103 (2008) .. [6] Buchete, N.-V. and Hummer, G.: Coarse master equations for peptide folding dynamics. J. Phys. Chem. B 112, 6057--6069 (2008) .. [7] Bowman, G. R., K. A. Beauchamp, G. Boxer and V. S. Pande: Progress and challenges in the automated construction of Markov state models for full protein systems. J. Chem. Phys. 131, 124101 (2009) .. [8] Sarich, M., F. Noe and C. Schuette: On the approximation quality of Markov state models. SIAM Multiscale Model. Simul. 8, 1154-1177 (2010) .. [9] Prinz, J.-H., H. Wu, M. Sarich, B. Keller, M. Senne, M. Held, J. D. Chodera, C. Schuette and F. Noe: Markov models of molecular kinetics: Generation and Validation J. Chem. Phys. 134, 174105 (2011) .. [10] Bowman, G. R., V. S. Pande and F. Noe: An Introduction to Markov State Models and Their Application to Long Timescale Molecular Simulation. Advances in Experimental Medicine and Biology 797, Springer, Heidelberg (2014) .. [11] Nueske, F., Wu, H., Prinz, J.-H., Wehmeyer, C., Clementi, C. and Noe, F.: Markov State Models from short non-Equilibrium Simulations - Analysis and Correction of Estimation Bias J. Chem. Phys. (submitted) (2017) .. [12] H. Wu and F. Noe: Variational approach for learning Markov processes from time series data (in preparation) .. [13] Noe, F. and F. Nueske: A variational approach to modeling slow processes in stochastic dynamical systems. SIAM Multiscale Model. Simul. 11, 635-655 (2013). .. [14] Wu, H and F. Noe: Variational approach for learning Markov processes from time series data (in preparation) .. [15] McGibbon, R and V. S. Pande: Variational cross-validation of slow dynamical modes in molecular kinetics, J. Chem. Phys. 142, 124105 (2015) .. [16] Noe, F. and C. Clementi: Kinetic distance and kinetic maps from molecular dynamics simulation. J. Chem. Theory Comput. 11, 5002-5011 (2015) Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.estimate_markov_model(dtrajs, 2) Which is the active set of states we are working on? >>> print(mm.active_set) [0 1 2] Show the count matrix >>> print(mm.count_matrix_active) [[ 7. 2. 1.] [ 2. 0. 4.] [ 2. 3. 9.]] Show the estimated transition matrix >>> print(mm.transition_matrix) [[ 0.7 0.167 0.133] [ 0.388 0. 0.612] [ 0.119 0.238 0.643]] Is this model reversible (i.e. does it fulfill detailed balance)? >>> print(mm.is_reversible) True What is the equilibrium distribution of states? >>> print(mm.stationary_distribution) [ 0.393 0.17 0.437] Relaxation timescales? >>> print(mm.timescales()) [ 3.415 1.297] Mean first passage time from state 0 to 2: >>> print(mm.mfpt(0, 2)) # doctest: +ELLIPSIS 9.929... """ # Catch invalid inputs for weights: if isinstance(weights, str): if weights not in ['empirical', 'oom']: raise ValueError("Weights must be either \'empirical\' or \'oom\'") else: raise ValueError("Weights must be either \'empirical\' or \'oom\'") # transition matrix estimator if weights == 'empirical': mlmsm = _ML_MSM(lag=lag, reversible=reversible, statdist_constraint=statdist, count_mode=count_mode, sparse=sparse, connectivity=connectivity, dt_traj=dt_traj, maxiter=maxiter, maxerr=maxerr, score_method=score_method, score_k=score_k, mincount_connectivity=mincount_connectivity) # estimate and return return mlmsm.estimate(dtrajs) elif weights == 'oom': if (statdist is not None) or (maxiter != 1000000) or (maxerr != 1e-8): import warnings warnings.warn("Values for statdist, maxiter or maxerr are ignored if OOM-correction is used.") oom_msm = _OOM_MSM(lag=lag, reversible=reversible, count_mode=count_mode, sparse=sparse, connectivity=connectivity, dt_traj=dt_traj, score_method=score_method, score_k=score_k, mincount_connectivity=mincount_connectivity) # estimate and return return oom_msm.estimate(dtrajs)
[ "def", "estimate_markov_model", "(", "dtrajs", ",", "lag", ",", "reversible", "=", "True", ",", "statdist", "=", "None", ",", "count_mode", "=", "'sliding'", ",", "weights", "=", "'empirical'", ",", "sparse", "=", "False", ",", "connectivity", "=", "'largest...
r""" Estimates a Markov model from discrete trajectories Returns a :class:`MaximumLikelihoodMSM` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lag time at which transitions are counted and the transition matrix is estimated. reversible : bool, optional If true compute reversible MSM, else non-reversible MSM statdist : (M,) ndarray, optional Stationary vector on the full state-space. Transition matrix will be estimated such that statdist is its equilibrium distribution. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/\tau)-1) \tau \rightarrow T) weights : str, optional can be used to re-weight non-equilibrium data to equilibrium. Must be one of the following: * 'empirical': Each trajectory frame counts as one. (default) * 'oom': Each transition is re-weighted using OOM theory, see [11]_. sparse : bool, optional If true compute count matrix, transition matrix and all derived quantities using sparse matrix algebra. In this case python sparse matrices will be returned by the corresponding functions instead of numpy arrays. This behavior is suggested for very large numbers of states (e.g. > 4000) because it is likely to be much more efficient. connectivity : str, optional Connectivity mode. Three methods are intended (currently only 'largest' is implemented) * 'largest' : The active set is the largest reversibly connected set. All estimation will be done on this subset and all quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than the full set of states * 'all' : The active set is the full set of states. Estimation will be conducted on each reversibly connected set separately. That means the transition matrix will decompose into disconnected submatrices, the stationary vector is only defined within subsets, etc. Currently not implemented. * 'none' : The active set is the full set of states. Estimation will be conducted on the full set of states without ensuring connectivity. This only permits nonreversible estimation. Currently not implemented. dt_traj : str, optional Description of the physical time corresponding to the lag. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): * 'fs', 'femtosecond*' * 'ps', 'picosecond*' * 'ns', 'nanosecond*' * 'us', 'microsecond*' * 'ms', 'millisecond*' * 's', 'second*' maxiter : int, optional Optional parameter with reversible = True. maximum number of iterations before the transition matrix estimation method exits maxerr : float, optional Optional parameter with reversible = True. convergence tolerance for transition matrix estimation. This specifies the maximum change of the Euclidean norm of relative stationary probabilities (:math:`x_i = \sum_k x_{ik}`). The relative stationary probability changes :math:`e_i = (x_i^{(1)} - x_i^{(2)})/(x_i^{(1)} + x_i^{(2)})` are used in order to track changes in small probabilities. The Euclidean norm of the change vector, :math:`|e_i|_2`, is compared to maxerr. score_method : str, optional, default='VAMP2' Score to be used with MSM score function. Available scores are based on the variational approach for Markov processes [13]_ [14]_: * 'VAMP1' Sum of singular values of the symmetrized transition matrix [14]_ . If the MSM is reversible, this is equal to the sum of transition matrix eigenvalues, also called Rayleigh quotient [13]_ [15]_ . * 'VAMP2' Sum of squared singular values of the symmetrized transition matrix [14]_ . If the MSM is reversible, this is equal to the kinetic variance [16]_ . score_k : int or None The maximum number of eigenvalues or singular values used in the score. If set to None, all available eigenvalues will be used. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. Returns ------- msm : :class:`MaximumLikelihoodMSM <pyemma.msm.MaximumLikelihoodMSM>` Estimator object containing the MSM and estimation information. See also -------- MaximumLikelihoodMSM An MSM object that has been estimated from data .. autoclass:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.MaximumLikelihoodMSM :attributes: References ---------- The mathematical theory of Markov (state) model estimation was introduced in [1]_ . Further theoretical developments were made in [2]_ . The term Markov state model was coined in [3]_ . Continuous-time Markov models (Master equation models) were suggested in [4]_. Reversible Markov model estimation was introduced in [5]_ , and further developed in [6]_ [7]_ [9]_ . It was shown in [8]_ that the quality of Markov state models does in fact not depend on memory loss, but rather on where the discretization is suitable to approximate the eigenfunctions of the Markov operator (the 'reaction coordinates'). With a suitable choice of discretization and lag time, MSMs can thus become very accurate. [9]_ introduced a number of methodological improvements and gives a good overview of the methodological basics of Markov state modeling today. [10]_ is a more extensive review book of theory, methods and applications. .. [1] Schuette, C. , A. Fischer, W. Huisinga and P. Deuflhard: A Direct Approach to Conformational Dynamics based on Hybrid Monte Carlo. J. Comput. Phys., 151, 146-168 (1999) .. [2] Swope, W. C., J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory J. Phys. Chem. B 108, 6571-6581 (2004) .. [3] Singhal, N., C. D. Snow, V. S. Pande: Using path sampling to build better Markovian state models: Predicting the folding rate and mechanism of a tryptophan zipper beta hairpin. J. Chem. Phys. 121, 415 (2004). .. [4] Sriraman, S., I. G. Kevrekidis and G. Hummer, G. J. Phys. Chem. B 109, 6479-6484 (2005) .. [5] Noe, F.: Probability Distributions of Molecular Observables computed from Markov Models. J. Chem. Phys. 128, 244103 (2008) .. [6] Buchete, N.-V. and Hummer, G.: Coarse master equations for peptide folding dynamics. J. Phys. Chem. B 112, 6057--6069 (2008) .. [7] Bowman, G. R., K. A. Beauchamp, G. Boxer and V. S. Pande: Progress and challenges in the automated construction of Markov state models for full protein systems. J. Chem. Phys. 131, 124101 (2009) .. [8] Sarich, M., F. Noe and C. Schuette: On the approximation quality of Markov state models. SIAM Multiscale Model. Simul. 8, 1154-1177 (2010) .. [9] Prinz, J.-H., H. Wu, M. Sarich, B. Keller, M. Senne, M. Held, J. D. Chodera, C. Schuette and F. Noe: Markov models of molecular kinetics: Generation and Validation J. Chem. Phys. 134, 174105 (2011) .. [10] Bowman, G. R., V. S. Pande and F. Noe: An Introduction to Markov State Models and Their Application to Long Timescale Molecular Simulation. Advances in Experimental Medicine and Biology 797, Springer, Heidelberg (2014) .. [11] Nueske, F., Wu, H., Prinz, J.-H., Wehmeyer, C., Clementi, C. and Noe, F.: Markov State Models from short non-Equilibrium Simulations - Analysis and Correction of Estimation Bias J. Chem. Phys. (submitted) (2017) .. [12] H. Wu and F. Noe: Variational approach for learning Markov processes from time series data (in preparation) .. [13] Noe, F. and F. Nueske: A variational approach to modeling slow processes in stochastic dynamical systems. SIAM Multiscale Model. Simul. 11, 635-655 (2013). .. [14] Wu, H and F. Noe: Variational approach for learning Markov processes from time series data (in preparation) .. [15] McGibbon, R and V. S. Pande: Variational cross-validation of slow dynamical modes in molecular kinetics, J. Chem. Phys. 142, 124105 (2015) .. [16] Noe, F. and C. Clementi: Kinetic distance and kinetic maps from molecular dynamics simulation. J. Chem. Theory Comput. 11, 5002-5011 (2015) Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.estimate_markov_model(dtrajs, 2) Which is the active set of states we are working on? >>> print(mm.active_set) [0 1 2] Show the count matrix >>> print(mm.count_matrix_active) [[ 7. 2. 1.] [ 2. 0. 4.] [ 2. 3. 9.]] Show the estimated transition matrix >>> print(mm.transition_matrix) [[ 0.7 0.167 0.133] [ 0.388 0. 0.612] [ 0.119 0.238 0.643]] Is this model reversible (i.e. does it fulfill detailed balance)? >>> print(mm.is_reversible) True What is the equilibrium distribution of states? >>> print(mm.stationary_distribution) [ 0.393 0.17 0.437] Relaxation timescales? >>> print(mm.timescales()) [ 3.415 1.297] Mean first passage time from state 0 to 2: >>> print(mm.mfpt(0, 2)) # doctest: +ELLIPSIS 9.929...
[ "r", "Estimates", "a", "Markov", "model", "from", "discrete", "trajectories" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/api.py#L322-L625
train
204,191
markovmodel/PyEMMA
pyemma/msm/api.py
bayesian_markov_model
def bayesian_markov_model(dtrajs, lag, reversible=True, statdist=None, sparse=False, connectivity='largest', count_mode='effective', nsamples=100, conf=0.95, dt_traj='1 step', show_progress=True, mincount_connectivity='1/n'): r""" Bayesian Markov model estimate using Gibbs sampling of the posterior Returns a :class:`BayesianMSM` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models as well as their statistical uncertainties. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lagtime for the MSM estimation in multiples of trajectory steps reversible : bool, optional, default = True If true compute reversible MSM, else non-reversible MSM sparse : bool, optional, default = False If true compute count matrix, transition matrix and all derived quantities using sparse matrix algebra. In this case python sparse matrices will be returned by the corresponding functions instead of numpy arrays. This behavior is suggested for very large numbers of states (e.g. > 4000) because it is likely to be much more efficient. statdist : (M,) ndarray, optional Stationary vector on the full state-space. Transition matrix will be estimated such that statdist is its equilibrium distribution. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/tau)-1) \tau \rightarrow T) connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. nsample : int, optional, default=100 number of transition matrix samples to compute and store conf : float, optional, default=0.95 size of confidence intervals dt_traj : str, optional, default='1 step' Description of the physical time corresponding to the trajectory time step. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): | 'fs', 'femtosecond*' | 'ps', 'picosecond*' | 'ns', 'nanosecond*' | 'us', 'microsecond*' | 'ms', 'millisecond*' | 's', 'second*' show_progress : bool, default=True Show progressbars for calculation mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. Returns ------- An :class:`BayesianMSM` object containing the Bayesian MSM estimator and the model. Example ------- Note that the following example is only qualitatively and not quantitatively reproducible because it involves random numbers. We build a Bayesian Markov model for the following two trajectories at lag time 2: >>> from pyemma import msm >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] >>> mm = msm.bayesian_markov_model(dtrajs, 2, show_progress=False) The resulting Model is an MSM just like you get with estimate_markov_model Its transition matrix does also come from a maximum likelihood estimation, but it's slightly different from the estimate_markov_mode result because bayesian_markov_model uses an effective count matrix with statistically uncorrelated counts: >>> print(mm.transition_matrix) # doctest: +SKIP [[ 0.70000001 0.16463699 0.135363 ] [ 0.38169055 0. 0.61830945] [ 0.12023989 0.23690297 0.64285714]] However bayesian_markov_model returns a SampledMSM object which is able to compute the probability distribution and statistical models of all methods that are offered by the MSM object. This works as follows. You can ask for the sample mean and specify the method you wanna evaluate as a string: >>> print(mm.sample_mean('transition_matrix')) # doctest: +SKIP [[ 0.71108663 0.15947371 0.12943966] [ 0.41076105 0. 0.58923895] [ 0.13079372 0.23005443 0.63915185]] Likewise, the standard deviation by element: >>> print(mm.sample_std('transition_matrix')) # doctest: +SKIP [[ 0.13707029 0.09479627 0.09200214] [ 0.15247454 0. 0.15247454] [ 0.07701315 0.09385258 0.1119089 ]] And this is the 95% (2 sigma) confidence interval. You can control the percentile using the conf argument in this function: >>> L, R = mm.sample_conf('transition_matrix') >>> print(L) # doctest: +SKIP >>> print(R) # doctest: +SKIP [[ 0.44083423 0.03926518 0.0242113 ] [ 0.14102544 0. 0.30729828] [ 0.02440188 0.07629456 0.43682481]] [[ 0.93571706 0.37522581 0.40180041] [ 0.69307665 0. 0.8649215 ] [ 0.31029752 0.44035732 0.85994006]] If you wanna compute expectations of functions that require arguments, just pass these arguments as well: >>> print(mm.sample_std('mfpt', 0, 2)) # doctest: +SKIP 12.9049811296 And if you want to histogram the distribution or compute more complex statistical moment such as the covariance between different quantities, just get the full sample of your quantity of interest and evaluate it at will: >>> samples = mm.sample_f('mfpt', 0, 2) >>> print(samples[:4]) # doctest: +SKIP [7.9763615793248155, 8.6540958274695701, 26.295326015231058, 17.909895469938899] Internally, the SampledMSM object has 100 transition matrices (the number can be controlled by nsamples), that were computed by the transition matrix sampling method. All of the above sample functions iterate over these 100 transition matrices and evaluate the requested function with the given parameters on each of them. .. autoclass:: pyemma.msm.estimators.bayesian_msm.BayesianMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.bayesian_msm.BayesianMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.bayesian_msm.BayesianMSM :attributes: References ---------- .. [1] Trendelkamp-Schroer, B, H. Wu, F. Paul and F. Noe: Estimation and uncertainty of reversible Markov models. http://arxiv.org/abs/1507.05990 """ # TODO: store_data=True bmsm_estimator = _Bayes_MSM(lag=lag, reversible=reversible, statdist_constraint=statdist, count_mode=count_mode, sparse=sparse, connectivity=connectivity, dt_traj=dt_traj, nsamples=nsamples, conf=conf, show_progress=show_progress, mincount_connectivity=mincount_connectivity) return bmsm_estimator.estimate(dtrajs)
python
def bayesian_markov_model(dtrajs, lag, reversible=True, statdist=None, sparse=False, connectivity='largest', count_mode='effective', nsamples=100, conf=0.95, dt_traj='1 step', show_progress=True, mincount_connectivity='1/n'): r""" Bayesian Markov model estimate using Gibbs sampling of the posterior Returns a :class:`BayesianMSM` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models as well as their statistical uncertainties. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lagtime for the MSM estimation in multiples of trajectory steps reversible : bool, optional, default = True If true compute reversible MSM, else non-reversible MSM sparse : bool, optional, default = False If true compute count matrix, transition matrix and all derived quantities using sparse matrix algebra. In this case python sparse matrices will be returned by the corresponding functions instead of numpy arrays. This behavior is suggested for very large numbers of states (e.g. > 4000) because it is likely to be much more efficient. statdist : (M,) ndarray, optional Stationary vector on the full state-space. Transition matrix will be estimated such that statdist is its equilibrium distribution. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/tau)-1) \tau \rightarrow T) connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. nsample : int, optional, default=100 number of transition matrix samples to compute and store conf : float, optional, default=0.95 size of confidence intervals dt_traj : str, optional, default='1 step' Description of the physical time corresponding to the trajectory time step. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): | 'fs', 'femtosecond*' | 'ps', 'picosecond*' | 'ns', 'nanosecond*' | 'us', 'microsecond*' | 'ms', 'millisecond*' | 's', 'second*' show_progress : bool, default=True Show progressbars for calculation mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. Returns ------- An :class:`BayesianMSM` object containing the Bayesian MSM estimator and the model. Example ------- Note that the following example is only qualitatively and not quantitatively reproducible because it involves random numbers. We build a Bayesian Markov model for the following two trajectories at lag time 2: >>> from pyemma import msm >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] >>> mm = msm.bayesian_markov_model(dtrajs, 2, show_progress=False) The resulting Model is an MSM just like you get with estimate_markov_model Its transition matrix does also come from a maximum likelihood estimation, but it's slightly different from the estimate_markov_mode result because bayesian_markov_model uses an effective count matrix with statistically uncorrelated counts: >>> print(mm.transition_matrix) # doctest: +SKIP [[ 0.70000001 0.16463699 0.135363 ] [ 0.38169055 0. 0.61830945] [ 0.12023989 0.23690297 0.64285714]] However bayesian_markov_model returns a SampledMSM object which is able to compute the probability distribution and statistical models of all methods that are offered by the MSM object. This works as follows. You can ask for the sample mean and specify the method you wanna evaluate as a string: >>> print(mm.sample_mean('transition_matrix')) # doctest: +SKIP [[ 0.71108663 0.15947371 0.12943966] [ 0.41076105 0. 0.58923895] [ 0.13079372 0.23005443 0.63915185]] Likewise, the standard deviation by element: >>> print(mm.sample_std('transition_matrix')) # doctest: +SKIP [[ 0.13707029 0.09479627 0.09200214] [ 0.15247454 0. 0.15247454] [ 0.07701315 0.09385258 0.1119089 ]] And this is the 95% (2 sigma) confidence interval. You can control the percentile using the conf argument in this function: >>> L, R = mm.sample_conf('transition_matrix') >>> print(L) # doctest: +SKIP >>> print(R) # doctest: +SKIP [[ 0.44083423 0.03926518 0.0242113 ] [ 0.14102544 0. 0.30729828] [ 0.02440188 0.07629456 0.43682481]] [[ 0.93571706 0.37522581 0.40180041] [ 0.69307665 0. 0.8649215 ] [ 0.31029752 0.44035732 0.85994006]] If you wanna compute expectations of functions that require arguments, just pass these arguments as well: >>> print(mm.sample_std('mfpt', 0, 2)) # doctest: +SKIP 12.9049811296 And if you want to histogram the distribution or compute more complex statistical moment such as the covariance between different quantities, just get the full sample of your quantity of interest and evaluate it at will: >>> samples = mm.sample_f('mfpt', 0, 2) >>> print(samples[:4]) # doctest: +SKIP [7.9763615793248155, 8.6540958274695701, 26.295326015231058, 17.909895469938899] Internally, the SampledMSM object has 100 transition matrices (the number can be controlled by nsamples), that were computed by the transition matrix sampling method. All of the above sample functions iterate over these 100 transition matrices and evaluate the requested function with the given parameters on each of them. .. autoclass:: pyemma.msm.estimators.bayesian_msm.BayesianMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.bayesian_msm.BayesianMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.bayesian_msm.BayesianMSM :attributes: References ---------- .. [1] Trendelkamp-Schroer, B, H. Wu, F. Paul and F. Noe: Estimation and uncertainty of reversible Markov models. http://arxiv.org/abs/1507.05990 """ # TODO: store_data=True bmsm_estimator = _Bayes_MSM(lag=lag, reversible=reversible, statdist_constraint=statdist, count_mode=count_mode, sparse=sparse, connectivity=connectivity, dt_traj=dt_traj, nsamples=nsamples, conf=conf, show_progress=show_progress, mincount_connectivity=mincount_connectivity) return bmsm_estimator.estimate(dtrajs)
[ "def", "bayesian_markov_model", "(", "dtrajs", ",", "lag", ",", "reversible", "=", "True", ",", "statdist", "=", "None", ",", "sparse", "=", "False", ",", "connectivity", "=", "'largest'", ",", "count_mode", "=", "'effective'", ",", "nsamples", "=", "100", ...
r""" Bayesian Markov model estimate using Gibbs sampling of the posterior Returns a :class:`BayesianMSM` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models as well as their statistical uncertainties. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lagtime for the MSM estimation in multiples of trajectory steps reversible : bool, optional, default = True If true compute reversible MSM, else non-reversible MSM sparse : bool, optional, default = False If true compute count matrix, transition matrix and all derived quantities using sparse matrix algebra. In this case python sparse matrices will be returned by the corresponding functions instead of numpy arrays. This behavior is suggested for very large numbers of states (e.g. > 4000) because it is likely to be much more efficient. statdist : (M,) ndarray, optional Stationary vector on the full state-space. Transition matrix will be estimated such that statdist is its equilibrium distribution. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/tau)-1) \tau \rightarrow T) connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. nsample : int, optional, default=100 number of transition matrix samples to compute and store conf : float, optional, default=0.95 size of confidence intervals dt_traj : str, optional, default='1 step' Description of the physical time corresponding to the trajectory time step. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): | 'fs', 'femtosecond*' | 'ps', 'picosecond*' | 'ns', 'nanosecond*' | 'us', 'microsecond*' | 'ms', 'millisecond*' | 's', 'second*' show_progress : bool, default=True Show progressbars for calculation mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. Returns ------- An :class:`BayesianMSM` object containing the Bayesian MSM estimator and the model. Example ------- Note that the following example is only qualitatively and not quantitatively reproducible because it involves random numbers. We build a Bayesian Markov model for the following two trajectories at lag time 2: >>> from pyemma import msm >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] >>> mm = msm.bayesian_markov_model(dtrajs, 2, show_progress=False) The resulting Model is an MSM just like you get with estimate_markov_model Its transition matrix does also come from a maximum likelihood estimation, but it's slightly different from the estimate_markov_mode result because bayesian_markov_model uses an effective count matrix with statistically uncorrelated counts: >>> print(mm.transition_matrix) # doctest: +SKIP [[ 0.70000001 0.16463699 0.135363 ] [ 0.38169055 0. 0.61830945] [ 0.12023989 0.23690297 0.64285714]] However bayesian_markov_model returns a SampledMSM object which is able to compute the probability distribution and statistical models of all methods that are offered by the MSM object. This works as follows. You can ask for the sample mean and specify the method you wanna evaluate as a string: >>> print(mm.sample_mean('transition_matrix')) # doctest: +SKIP [[ 0.71108663 0.15947371 0.12943966] [ 0.41076105 0. 0.58923895] [ 0.13079372 0.23005443 0.63915185]] Likewise, the standard deviation by element: >>> print(mm.sample_std('transition_matrix')) # doctest: +SKIP [[ 0.13707029 0.09479627 0.09200214] [ 0.15247454 0. 0.15247454] [ 0.07701315 0.09385258 0.1119089 ]] And this is the 95% (2 sigma) confidence interval. You can control the percentile using the conf argument in this function: >>> L, R = mm.sample_conf('transition_matrix') >>> print(L) # doctest: +SKIP >>> print(R) # doctest: +SKIP [[ 0.44083423 0.03926518 0.0242113 ] [ 0.14102544 0. 0.30729828] [ 0.02440188 0.07629456 0.43682481]] [[ 0.93571706 0.37522581 0.40180041] [ 0.69307665 0. 0.8649215 ] [ 0.31029752 0.44035732 0.85994006]] If you wanna compute expectations of functions that require arguments, just pass these arguments as well: >>> print(mm.sample_std('mfpt', 0, 2)) # doctest: +SKIP 12.9049811296 And if you want to histogram the distribution or compute more complex statistical moment such as the covariance between different quantities, just get the full sample of your quantity of interest and evaluate it at will: >>> samples = mm.sample_f('mfpt', 0, 2) >>> print(samples[:4]) # doctest: +SKIP [7.9763615793248155, 8.6540958274695701, 26.295326015231058, 17.909895469938899] Internally, the SampledMSM object has 100 transition matrices (the number can be controlled by nsamples), that were computed by the transition matrix sampling method. All of the above sample functions iterate over these 100 transition matrices and evaluate the requested function with the given parameters on each of them. .. autoclass:: pyemma.msm.estimators.bayesian_msm.BayesianMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.bayesian_msm.BayesianMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.bayesian_msm.BayesianMSM :attributes: References ---------- .. [1] Trendelkamp-Schroer, B, H. Wu, F. Paul and F. Noe: Estimation and uncertainty of reversible Markov models. http://arxiv.org/abs/1507.05990
[ "r", "Bayesian", "Markov", "model", "estimate", "using", "Gibbs", "sampling", "of", "the", "posterior" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/api.py#L628-L825
train
204,192
markovmodel/PyEMMA
pyemma/msm/api.py
timescales_hmsm
def timescales_hmsm(dtrajs, nstates, lags=None, nits=None, reversible=True, stationary=False, connectivity=None, mincount_connectivity='1/n', separate=None, errors=None, nsamples=100, stride=None, n_jobs=None, show_progress=True): r""" Calculate implied timescales from Hidden Markov state models estimated at a series of lag times. Warning: this can be slow! Parameters ---------- dtrajs : array-like or list of array-likes discrete trajectories nstates : int number of hidden states lags : int, array-like with integers or None, optional integer lag times at which the implied timescales will be calculated. If set to None (default) as list of lag times will be automatically generated. For a single int, generate a set of lag times starting from 1 to lags, using a multiplier of 1.5 between successive lags. nits : int (optional) number of implied timescales to be computed. Will compute less if the number of states are smaller. None means the number of timescales will be determined automatically. connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. reversible : boolean (optional) Estimate transition matrix reversibly (True) or nonreversibly (False) stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. errors : None | 'bayes' Specifies whether to compute statistical uncertainties (by default not), an which algorithm to use if yes. The only option is currently 'bayes'. This algorithm is much faster than MSM-based error calculation because the involved matrices are much smaller. nsamples : int Number of approximately independent HMSM samples generated for each lag time for uncertainty quantification. Only used if errors is not None. n_jobs : int how many subprocesses to start to estimate the models for each lag time. show_progress : bool, default=True Show progressbars for calculation? Returns ------- itsobj : :class:`ImpliedTimescales <pyemma.msm.ImpliedTimescales>` object See also -------- ImpliedTimescales The object returned by this function. pyemma.plots.plot_implied_timescales Plotting function for the :class:`ImpliedTimescales <pyemma.msm.ImpliedTimescales>` object Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtraj = [0,1,1,0,0,0,1,1,0,0,0,1,2,2,2,2,2,2,2,2,2,1,1,0,0,0,1,1,0,1,0] # mini-trajectory >>> ts = msm.timescales_hmsm(dtraj, 2, [1,2,3,4], show_progress=False) >>> print(ts.timescales) # doctest: +ELLIPSIS [[ 5.786] [ 5.143] [ 4.44 ] [ 3.677]] .. autoclass:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :attributes: References ---------- Implied timescales as a lagtime-selection and MSM-validation approach were suggested in [1]_. Hidden Markov state model estimation is done here as described in [2]_. For uncertainty quantification we employ the Bayesian sampling algorithm described in [3]_. .. [1] Swope, W. C. and J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory. J. Phys. Chem. B 108: 6571-6581 (2004) .. [2] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) .. [3] J. D. Chodera et al: Bayesian hidden Markov model analysis of single-molecule force spectroscopy: Characterizing kinetics under measurement uncertainty arXiv:1108.1430 (2011) """ # format data dtrajs = _types.ensure_dtraj_list(dtrajs) # MLE or error estimation? if errors is None: if stride is None: stride = 1 estimator = _ML_HMSM(nstates=nstates, reversible=reversible, stationary=stationary, connectivity=connectivity, stride=stride, mincount_connectivity=mincount_connectivity, separate=separate) elif errors == 'bayes': if stride is None: stride = 'effective' estimator = _Bayes_HMSM(nstates=nstates, reversible=reversible, stationary=stationary, connectivity=connectivity, mincount_connectivity=mincount_connectivity, stride=stride, separate=separate, show_progress=show_progress, nsamples=nsamples) else: raise NotImplementedError('Error estimation method'+str(errors)+'currently not implemented') # go itsobj = _ImpliedTimescales(estimator, lags=lags, nits=nits, n_jobs=n_jobs, show_progress=show_progress) itsobj.estimate(dtrajs) return itsobj
python
def timescales_hmsm(dtrajs, nstates, lags=None, nits=None, reversible=True, stationary=False, connectivity=None, mincount_connectivity='1/n', separate=None, errors=None, nsamples=100, stride=None, n_jobs=None, show_progress=True): r""" Calculate implied timescales from Hidden Markov state models estimated at a series of lag times. Warning: this can be slow! Parameters ---------- dtrajs : array-like or list of array-likes discrete trajectories nstates : int number of hidden states lags : int, array-like with integers or None, optional integer lag times at which the implied timescales will be calculated. If set to None (default) as list of lag times will be automatically generated. For a single int, generate a set of lag times starting from 1 to lags, using a multiplier of 1.5 between successive lags. nits : int (optional) number of implied timescales to be computed. Will compute less if the number of states are smaller. None means the number of timescales will be determined automatically. connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. reversible : boolean (optional) Estimate transition matrix reversibly (True) or nonreversibly (False) stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. errors : None | 'bayes' Specifies whether to compute statistical uncertainties (by default not), an which algorithm to use if yes. The only option is currently 'bayes'. This algorithm is much faster than MSM-based error calculation because the involved matrices are much smaller. nsamples : int Number of approximately independent HMSM samples generated for each lag time for uncertainty quantification. Only used if errors is not None. n_jobs : int how many subprocesses to start to estimate the models for each lag time. show_progress : bool, default=True Show progressbars for calculation? Returns ------- itsobj : :class:`ImpliedTimescales <pyemma.msm.ImpliedTimescales>` object See also -------- ImpliedTimescales The object returned by this function. pyemma.plots.plot_implied_timescales Plotting function for the :class:`ImpliedTimescales <pyemma.msm.ImpliedTimescales>` object Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtraj = [0,1,1,0,0,0,1,1,0,0,0,1,2,2,2,2,2,2,2,2,2,1,1,0,0,0,1,1,0,1,0] # mini-trajectory >>> ts = msm.timescales_hmsm(dtraj, 2, [1,2,3,4], show_progress=False) >>> print(ts.timescales) # doctest: +ELLIPSIS [[ 5.786] [ 5.143] [ 4.44 ] [ 3.677]] .. autoclass:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :attributes: References ---------- Implied timescales as a lagtime-selection and MSM-validation approach were suggested in [1]_. Hidden Markov state model estimation is done here as described in [2]_. For uncertainty quantification we employ the Bayesian sampling algorithm described in [3]_. .. [1] Swope, W. C. and J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory. J. Phys. Chem. B 108: 6571-6581 (2004) .. [2] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) .. [3] J. D. Chodera et al: Bayesian hidden Markov model analysis of single-molecule force spectroscopy: Characterizing kinetics under measurement uncertainty arXiv:1108.1430 (2011) """ # format data dtrajs = _types.ensure_dtraj_list(dtrajs) # MLE or error estimation? if errors is None: if stride is None: stride = 1 estimator = _ML_HMSM(nstates=nstates, reversible=reversible, stationary=stationary, connectivity=connectivity, stride=stride, mincount_connectivity=mincount_connectivity, separate=separate) elif errors == 'bayes': if stride is None: stride = 'effective' estimator = _Bayes_HMSM(nstates=nstates, reversible=reversible, stationary=stationary, connectivity=connectivity, mincount_connectivity=mincount_connectivity, stride=stride, separate=separate, show_progress=show_progress, nsamples=nsamples) else: raise NotImplementedError('Error estimation method'+str(errors)+'currently not implemented') # go itsobj = _ImpliedTimescales(estimator, lags=lags, nits=nits, n_jobs=n_jobs, show_progress=show_progress) itsobj.estimate(dtrajs) return itsobj
[ "def", "timescales_hmsm", "(", "dtrajs", ",", "nstates", ",", "lags", "=", "None", ",", "nits", "=", "None", ",", "reversible", "=", "True", ",", "stationary", "=", "False", ",", "connectivity", "=", "None", ",", "mincount_connectivity", "=", "'1/n'", ",",...
r""" Calculate implied timescales from Hidden Markov state models estimated at a series of lag times. Warning: this can be slow! Parameters ---------- dtrajs : array-like or list of array-likes discrete trajectories nstates : int number of hidden states lags : int, array-like with integers or None, optional integer lag times at which the implied timescales will be calculated. If set to None (default) as list of lag times will be automatically generated. For a single int, generate a set of lag times starting from 1 to lags, using a multiplier of 1.5 between successive lags. nits : int (optional) number of implied timescales to be computed. Will compute less if the number of states are smaller. None means the number of timescales will be determined automatically. connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. reversible : boolean (optional) Estimate transition matrix reversibly (True) or nonreversibly (False) stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. errors : None | 'bayes' Specifies whether to compute statistical uncertainties (by default not), an which algorithm to use if yes. The only option is currently 'bayes'. This algorithm is much faster than MSM-based error calculation because the involved matrices are much smaller. nsamples : int Number of approximately independent HMSM samples generated for each lag time for uncertainty quantification. Only used if errors is not None. n_jobs : int how many subprocesses to start to estimate the models for each lag time. show_progress : bool, default=True Show progressbars for calculation? Returns ------- itsobj : :class:`ImpliedTimescales <pyemma.msm.ImpliedTimescales>` object See also -------- ImpliedTimescales The object returned by this function. pyemma.plots.plot_implied_timescales Plotting function for the :class:`ImpliedTimescales <pyemma.msm.ImpliedTimescales>` object Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtraj = [0,1,1,0,0,0,1,1,0,0,0,1,2,2,2,2,2,2,2,2,2,1,1,0,0,0,1,1,0,1,0] # mini-trajectory >>> ts = msm.timescales_hmsm(dtraj, 2, [1,2,3,4], show_progress=False) >>> print(ts.timescales) # doctest: +ELLIPSIS [[ 5.786] [ 5.143] [ 4.44 ] [ 3.677]] .. autoclass:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.implied_timescales.ImpliedTimescales :attributes: References ---------- Implied timescales as a lagtime-selection and MSM-validation approach were suggested in [1]_. Hidden Markov state model estimation is done here as described in [2]_. For uncertainty quantification we employ the Bayesian sampling algorithm described in [3]_. .. [1] Swope, W. C. and J. W. Pitera and F. Suits: Describing protein folding kinetics by molecular dynamics simulations: 1. Theory. J. Phys. Chem. B 108: 6571-6581 (2004) .. [2] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) .. [3] J. D. Chodera et al: Bayesian hidden Markov model analysis of single-molecule force spectroscopy: Characterizing kinetics under measurement uncertainty arXiv:1108.1430 (2011)
[ "r", "Calculate", "implied", "timescales", "from", "Hidden", "Markov", "state", "models", "estimated", "at", "a", "series", "of", "lag", "times", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/api.py#L833-L978
train
204,193
markovmodel/PyEMMA
pyemma/msm/api.py
estimate_hidden_markov_model
def estimate_hidden_markov_model(dtrajs, nstates, lag, reversible=True, stationary=False, connectivity=None, mincount_connectivity='1/n', separate=None, observe_nonempty=True, stride=1, dt_traj='1 step', accuracy=1e-3, maxit=1000): r""" Estimates a Hidden Markov state model from discrete trajectories Returns a :class:`MaximumLikelihoodHMSM` that contains a transition matrix between a few (hidden) metastable states. Each metastable state has a probability distribution of visiting the discrete 'microstates' contained in the input trajectories. The resulting object is a hidden Markov model that allows to compute a large number of quantities. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lagtime for the MSM estimation in multiples of trajectory steps nstates : int the number of metastable states in the resulting HMM reversible : bool, optional, default = True If true compute reversible MSM, else non-reversible MSM stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. observe_nonempty : bool If True, will restricted the observed states to the states that have at least one observation in the lagged input trajectories. dt_traj : str, optional, default='1 step' Description of the physical time corresponding to the trajectory time step. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): | 'fs', 'femtosecond*' | 'ps', 'picosecond*' | 'ns', 'nanosecond*' | 'us', 'microsecond*' | 'ms', 'millisecond*' | 's', 'second*' accuracy : float convergence threshold for EM iteration. When two the likelihood does not increase by more than accuracy, the iteration is stopped successfully. maxit : int stopping criterion for EM iteration. When so many iterations are performed without reaching the requested accuracy, the iteration is stopped without convergence (a warning is given) Returns ------- hmsm : :class:`MaximumLikelihoodHMSM <pyemma.msm.MaximumLikelihoodHMSM>` Estimator object containing the HMSM and estimation information. Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.estimate_hidden_markov_model(dtrajs, 2, 2) We have estimated a 2x2 hidden transition matrix between the metastable states: >>> print(mm.transition_matrix) [[ 0.684 0.316] [ 0.242 0.758]] With the equilibrium distribution: >>> print(mm.stationary_distribution) # doctest: +ELLIPSIS [ 0.43... 0.56...] The observed states are the three discrete clusters that we have in our discrete trajectory: >>> print(mm.observable_set) [0 1 2] The metastable distributions (mm.metastable_distributions), or equivalently the observation probabilities are the probability to be in a given cluster ('microstate') if we are in one of the hidden metastable states. So it's a 2 x 3 matrix: >>> print(mm.observation_probabilities) # doctest: +SKIP [[ 0.9620883 0.0379117 0. ] [ 0. 0.28014352 0.71985648]] The first metastable state ist mostly in cluster 0, and a little bit in the transition state cluster 1. The second metastable state is less well defined, but mostly in cluster 2 and less prominently in the transition state cluster 1. We can print the lifetimes of the metastable states: >>> print(mm.lifetimes) # doctest: +ELLIPSIS [ 5... 7...] And the timescale of the hidden transition matrix - now we only have one relaxation timescale: >>> print(mm.timescales()) # doctest: +ELLIPSIS [ 2.4...] The mean first passage times can also be computed between metastable states: >>> print(mm.mfpt(0, 1)) # doctest: +ELLIPSIS 6.3... .. autoclass:: pyemma.msm.estimators.maximum_likelihood_hmsm.MaximumLikelihoodHMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_hmsm.MaximumLikelihoodHMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_hmsm.MaximumLikelihoodHMSM :attributes: References ---------- [1]_ is an excellent review of estimation algorithms for discrete Hidden Markov Models. This function estimates a discrete HMM on the discrete input states using the Baum-Welch algorithm [2]_. We use a maximum-likelihood Markov state model to initialize the HMM estimation as described in [3]_. .. [1] L. R. Rabiner: A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition. Proc. IEEE 77, 257-286 (1989) .. [2] L. Baum, T. Petrie, G. Soules and N. Weiss N: A maximization technique occurring in the statistical analysis of probabilistic functions of Markov chains. Ann. Math. Statist. 41, 164-171 (1970) .. [3] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) """ # initialize HMSM estimator hmsm_estimator = _ML_HMSM(lag=lag, nstates=nstates, reversible=reversible, stationary=stationary, msm_init='largest-strong', connectivity=connectivity, mincount_connectivity=mincount_connectivity, separate=separate, observe_nonempty=observe_nonempty, stride=stride, dt_traj=dt_traj, accuracy=accuracy, maxit=maxit) # run estimation return hmsm_estimator.estimate(dtrajs)
python
def estimate_hidden_markov_model(dtrajs, nstates, lag, reversible=True, stationary=False, connectivity=None, mincount_connectivity='1/n', separate=None, observe_nonempty=True, stride=1, dt_traj='1 step', accuracy=1e-3, maxit=1000): r""" Estimates a Hidden Markov state model from discrete trajectories Returns a :class:`MaximumLikelihoodHMSM` that contains a transition matrix between a few (hidden) metastable states. Each metastable state has a probability distribution of visiting the discrete 'microstates' contained in the input trajectories. The resulting object is a hidden Markov model that allows to compute a large number of quantities. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lagtime for the MSM estimation in multiples of trajectory steps nstates : int the number of metastable states in the resulting HMM reversible : bool, optional, default = True If true compute reversible MSM, else non-reversible MSM stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. observe_nonempty : bool If True, will restricted the observed states to the states that have at least one observation in the lagged input trajectories. dt_traj : str, optional, default='1 step' Description of the physical time corresponding to the trajectory time step. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): | 'fs', 'femtosecond*' | 'ps', 'picosecond*' | 'ns', 'nanosecond*' | 'us', 'microsecond*' | 'ms', 'millisecond*' | 's', 'second*' accuracy : float convergence threshold for EM iteration. When two the likelihood does not increase by more than accuracy, the iteration is stopped successfully. maxit : int stopping criterion for EM iteration. When so many iterations are performed without reaching the requested accuracy, the iteration is stopped without convergence (a warning is given) Returns ------- hmsm : :class:`MaximumLikelihoodHMSM <pyemma.msm.MaximumLikelihoodHMSM>` Estimator object containing the HMSM and estimation information. Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.estimate_hidden_markov_model(dtrajs, 2, 2) We have estimated a 2x2 hidden transition matrix between the metastable states: >>> print(mm.transition_matrix) [[ 0.684 0.316] [ 0.242 0.758]] With the equilibrium distribution: >>> print(mm.stationary_distribution) # doctest: +ELLIPSIS [ 0.43... 0.56...] The observed states are the three discrete clusters that we have in our discrete trajectory: >>> print(mm.observable_set) [0 1 2] The metastable distributions (mm.metastable_distributions), or equivalently the observation probabilities are the probability to be in a given cluster ('microstate') if we are in one of the hidden metastable states. So it's a 2 x 3 matrix: >>> print(mm.observation_probabilities) # doctest: +SKIP [[ 0.9620883 0.0379117 0. ] [ 0. 0.28014352 0.71985648]] The first metastable state ist mostly in cluster 0, and a little bit in the transition state cluster 1. The second metastable state is less well defined, but mostly in cluster 2 and less prominently in the transition state cluster 1. We can print the lifetimes of the metastable states: >>> print(mm.lifetimes) # doctest: +ELLIPSIS [ 5... 7...] And the timescale of the hidden transition matrix - now we only have one relaxation timescale: >>> print(mm.timescales()) # doctest: +ELLIPSIS [ 2.4...] The mean first passage times can also be computed between metastable states: >>> print(mm.mfpt(0, 1)) # doctest: +ELLIPSIS 6.3... .. autoclass:: pyemma.msm.estimators.maximum_likelihood_hmsm.MaximumLikelihoodHMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_hmsm.MaximumLikelihoodHMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_hmsm.MaximumLikelihoodHMSM :attributes: References ---------- [1]_ is an excellent review of estimation algorithms for discrete Hidden Markov Models. This function estimates a discrete HMM on the discrete input states using the Baum-Welch algorithm [2]_. We use a maximum-likelihood Markov state model to initialize the HMM estimation as described in [3]_. .. [1] L. R. Rabiner: A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition. Proc. IEEE 77, 257-286 (1989) .. [2] L. Baum, T. Petrie, G. Soules and N. Weiss N: A maximization technique occurring in the statistical analysis of probabilistic functions of Markov chains. Ann. Math. Statist. 41, 164-171 (1970) .. [3] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) """ # initialize HMSM estimator hmsm_estimator = _ML_HMSM(lag=lag, nstates=nstates, reversible=reversible, stationary=stationary, msm_init='largest-strong', connectivity=connectivity, mincount_connectivity=mincount_connectivity, separate=separate, observe_nonempty=observe_nonempty, stride=stride, dt_traj=dt_traj, accuracy=accuracy, maxit=maxit) # run estimation return hmsm_estimator.estimate(dtrajs)
[ "def", "estimate_hidden_markov_model", "(", "dtrajs", ",", "nstates", ",", "lag", ",", "reversible", "=", "True", ",", "stationary", "=", "False", ",", "connectivity", "=", "None", ",", "mincount_connectivity", "=", "'1/n'", ",", "separate", "=", "None", ",", ...
r""" Estimates a Hidden Markov state model from discrete trajectories Returns a :class:`MaximumLikelihoodHMSM` that contains a transition matrix between a few (hidden) metastable states. Each metastable state has a probability distribution of visiting the discrete 'microstates' contained in the input trajectories. The resulting object is a hidden Markov model that allows to compute a large number of quantities. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lagtime for the MSM estimation in multiples of trajectory steps nstates : int the number of metastable states in the resulting HMM reversible : bool, optional, default = True If true compute reversible MSM, else non-reversible MSM stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. observe_nonempty : bool If True, will restricted the observed states to the states that have at least one observation in the lagged input trajectories. dt_traj : str, optional, default='1 step' Description of the physical time corresponding to the trajectory time step. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): | 'fs', 'femtosecond*' | 'ps', 'picosecond*' | 'ns', 'nanosecond*' | 'us', 'microsecond*' | 'ms', 'millisecond*' | 's', 'second*' accuracy : float convergence threshold for EM iteration. When two the likelihood does not increase by more than accuracy, the iteration is stopped successfully. maxit : int stopping criterion for EM iteration. When so many iterations are performed without reaching the requested accuracy, the iteration is stopped without convergence (a warning is given) Returns ------- hmsm : :class:`MaximumLikelihoodHMSM <pyemma.msm.MaximumLikelihoodHMSM>` Estimator object containing the HMSM and estimation information. Example ------- >>> from pyemma import msm >>> import numpy as np >>> np.set_printoptions(precision=3) >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.estimate_hidden_markov_model(dtrajs, 2, 2) We have estimated a 2x2 hidden transition matrix between the metastable states: >>> print(mm.transition_matrix) [[ 0.684 0.316] [ 0.242 0.758]] With the equilibrium distribution: >>> print(mm.stationary_distribution) # doctest: +ELLIPSIS [ 0.43... 0.56...] The observed states are the three discrete clusters that we have in our discrete trajectory: >>> print(mm.observable_set) [0 1 2] The metastable distributions (mm.metastable_distributions), or equivalently the observation probabilities are the probability to be in a given cluster ('microstate') if we are in one of the hidden metastable states. So it's a 2 x 3 matrix: >>> print(mm.observation_probabilities) # doctest: +SKIP [[ 0.9620883 0.0379117 0. ] [ 0. 0.28014352 0.71985648]] The first metastable state ist mostly in cluster 0, and a little bit in the transition state cluster 1. The second metastable state is less well defined, but mostly in cluster 2 and less prominently in the transition state cluster 1. We can print the lifetimes of the metastable states: >>> print(mm.lifetimes) # doctest: +ELLIPSIS [ 5... 7...] And the timescale of the hidden transition matrix - now we only have one relaxation timescale: >>> print(mm.timescales()) # doctest: +ELLIPSIS [ 2.4...] The mean first passage times can also be computed between metastable states: >>> print(mm.mfpt(0, 1)) # doctest: +ELLIPSIS 6.3... .. autoclass:: pyemma.msm.estimators.maximum_likelihood_hmsm.MaximumLikelihoodHMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_hmsm.MaximumLikelihoodHMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_hmsm.MaximumLikelihoodHMSM :attributes: References ---------- [1]_ is an excellent review of estimation algorithms for discrete Hidden Markov Models. This function estimates a discrete HMM on the discrete input states using the Baum-Welch algorithm [2]_. We use a maximum-likelihood Markov state model to initialize the HMM estimation as described in [3]_. .. [1] L. R. Rabiner: A Tutorial on Hidden Markov Models and Selected Applications in Speech Recognition. Proc. IEEE 77, 257-286 (1989) .. [2] L. Baum, T. Petrie, G. Soules and N. Weiss N: A maximization technique occurring in the statistical analysis of probabilistic functions of Markov chains. Ann. Math. Statist. 41, 164-171 (1970) .. [3] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013)
[ "r", "Estimates", "a", "Hidden", "Markov", "state", "model", "from", "discrete", "trajectories" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/api.py#L981-L1161
train
204,194
markovmodel/PyEMMA
pyemma/msm/api.py
bayesian_hidden_markov_model
def bayesian_hidden_markov_model(dtrajs, nstates, lag, nsamples=100, reversible=True, stationary=False, connectivity=None, mincount_connectivity='1/n', separate=None, observe_nonempty=True, stride='effective', conf=0.95, dt_traj='1 step', store_hidden=False, show_progress=True): r""" Bayesian Hidden Markov model estimate using Gibbs sampling of the posterior Returns a :class:`BayesianHMSM` that contains the estimated hidden Markov model [1]_ and a Bayesian estimate [2]_ that contains samples around this estimate to estimate uncertainties. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lagtime for the MSM estimation in multiples of trajectory steps nstates : int the number of metastable states in the resulting HMM reversible : bool, optional, default = True If true compute reversible MSM, else non-reversible MSM stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. observe_nonempty : bool If True, will restricted the observed states to the states that have at least one observation in the lagged input trajectories. nsamples : int, optional, default=100 number of transition matrix samples to compute and store stride : str or int, default='effective' stride between two lagged trajectories extracted from the input trajectories. Given trajectory s[t], stride and lag will result in trajectories s[0], s[tau], s[2 tau], ... s[stride], s[stride + tau], s[stride + 2 tau], ... Setting stride = 1 will result in using all data (useful for maximum likelihood estimator), while a Bayesian estimator requires a longer stride in order to have statistically uncorrelated trajectories. Setting stride = None 'effective' uses the largest neglected timescale as an estimate for the correlation time and sets the stride accordingly. conf : float, optional, default=0.95 size of confidence intervals dt_traj : str, optional, default='1 step' Description of the physical time corresponding to the trajectory time step. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): | 'fs', 'femtosecond*' | 'ps', 'picosecond*' | 'ns', 'nanosecond*' | 'us', 'microsecond*' | 'ms', 'millisecond*' | 's', 'second*' store_hidden : bool, optional, default=False store hidden trajectories in sampled HMMs show_progress : bool, default=True Show progressbars for calculation? Returns ------- An :class:`BayesianHMSM` object containing a transition matrix and various other HMM-related quantities and statistical uncertainties. Example ------- Note that the following example is only qualitative and not quantitatively reproducible because random numbers are involved >>> from pyemma import msm >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.bayesian_hidden_markov_model(dtrajs, 2, 2, show_progress=False) We compute the stationary distribution (here given by the maximum likelihood estimate), and the 1-sigma uncertainty interval. You can see that the uncertainties are quite large (we have seen only very few transitions between the metastable states: >>> pi = mm.stationary_distribution >>> piL,piR = mm.sample_conf('stationary_distribution') >>> for i in range(2): print(pi[i],' -',piL[i],'+',piR[i]) # doctest: +SKIP 0.459176653019 - 0.268314552886 + 0.715326151685 0.540823346981 - 0.284761476984 + 0.731730375713 Let's look at the lifetimes of metastable states. Now we have really huge uncertainties. In states where one state is more probable than the other, the mean first passage time from the more probable to the less probable state is much higher than the reverse: >>> l = mm.lifetimes >>> lL, lR = mm.sample_conf('lifetimes') >>> for i in range(2): print(l[i],' -',lL[i],'+',lR[i]) # doctest: +SKIP 7.18543434854 - 6.03617757784 + 80.1298222741 8.65699332061 - 5.35089540896 + 30.1719505772 In contrast the relaxation timescale is less uncertain. This is because for a two-state system the relaxation timescale is dominated by the faster passage, which is less uncertain than the slower passage time: >>> ts = mm.timescales() >>> tsL,tsR = mm.sample_conf('timescales') >>> print(ts[0],' -',tsL[0],'+',tsR[0]) # doctest: +SKIP 3.35310468086 - 2.24574587978 + 8.34383177258 .. autoclass:: pyemma.msm.estimators.bayesian_hmsm.BayesianHMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.bayesian_hmsm.BayesianHMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.bayesian_hmsm.BayesianHMSM :attributes: References ---------- .. [1] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) .. [2] J. D. Chodera Et Al: Bayesian hidden Markov model analysis of single-molecule force spectroscopy: Characterizing kinetics under measurement uncertainty. arXiv:1108.1430 (2011) """ bhmsm_estimator = _Bayes_HMSM(lag=lag, nstates=nstates, stride=stride, nsamples=nsamples, reversible=reversible, stationary=stationary, connectivity=connectivity, mincount_connectivity=mincount_connectivity, separate=separate, observe_nonempty=observe_nonempty, dt_traj=dt_traj, conf=conf, store_hidden=store_hidden, show_progress=show_progress) return bhmsm_estimator.estimate(dtrajs)
python
def bayesian_hidden_markov_model(dtrajs, nstates, lag, nsamples=100, reversible=True, stationary=False, connectivity=None, mincount_connectivity='1/n', separate=None, observe_nonempty=True, stride='effective', conf=0.95, dt_traj='1 step', store_hidden=False, show_progress=True): r""" Bayesian Hidden Markov model estimate using Gibbs sampling of the posterior Returns a :class:`BayesianHMSM` that contains the estimated hidden Markov model [1]_ and a Bayesian estimate [2]_ that contains samples around this estimate to estimate uncertainties. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lagtime for the MSM estimation in multiples of trajectory steps nstates : int the number of metastable states in the resulting HMM reversible : bool, optional, default = True If true compute reversible MSM, else non-reversible MSM stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. observe_nonempty : bool If True, will restricted the observed states to the states that have at least one observation in the lagged input trajectories. nsamples : int, optional, default=100 number of transition matrix samples to compute and store stride : str or int, default='effective' stride between two lagged trajectories extracted from the input trajectories. Given trajectory s[t], stride and lag will result in trajectories s[0], s[tau], s[2 tau], ... s[stride], s[stride + tau], s[stride + 2 tau], ... Setting stride = 1 will result in using all data (useful for maximum likelihood estimator), while a Bayesian estimator requires a longer stride in order to have statistically uncorrelated trajectories. Setting stride = None 'effective' uses the largest neglected timescale as an estimate for the correlation time and sets the stride accordingly. conf : float, optional, default=0.95 size of confidence intervals dt_traj : str, optional, default='1 step' Description of the physical time corresponding to the trajectory time step. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): | 'fs', 'femtosecond*' | 'ps', 'picosecond*' | 'ns', 'nanosecond*' | 'us', 'microsecond*' | 'ms', 'millisecond*' | 's', 'second*' store_hidden : bool, optional, default=False store hidden trajectories in sampled HMMs show_progress : bool, default=True Show progressbars for calculation? Returns ------- An :class:`BayesianHMSM` object containing a transition matrix and various other HMM-related quantities and statistical uncertainties. Example ------- Note that the following example is only qualitative and not quantitatively reproducible because random numbers are involved >>> from pyemma import msm >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.bayesian_hidden_markov_model(dtrajs, 2, 2, show_progress=False) We compute the stationary distribution (here given by the maximum likelihood estimate), and the 1-sigma uncertainty interval. You can see that the uncertainties are quite large (we have seen only very few transitions between the metastable states: >>> pi = mm.stationary_distribution >>> piL,piR = mm.sample_conf('stationary_distribution') >>> for i in range(2): print(pi[i],' -',piL[i],'+',piR[i]) # doctest: +SKIP 0.459176653019 - 0.268314552886 + 0.715326151685 0.540823346981 - 0.284761476984 + 0.731730375713 Let's look at the lifetimes of metastable states. Now we have really huge uncertainties. In states where one state is more probable than the other, the mean first passage time from the more probable to the less probable state is much higher than the reverse: >>> l = mm.lifetimes >>> lL, lR = mm.sample_conf('lifetimes') >>> for i in range(2): print(l[i],' -',lL[i],'+',lR[i]) # doctest: +SKIP 7.18543434854 - 6.03617757784 + 80.1298222741 8.65699332061 - 5.35089540896 + 30.1719505772 In contrast the relaxation timescale is less uncertain. This is because for a two-state system the relaxation timescale is dominated by the faster passage, which is less uncertain than the slower passage time: >>> ts = mm.timescales() >>> tsL,tsR = mm.sample_conf('timescales') >>> print(ts[0],' -',tsL[0],'+',tsR[0]) # doctest: +SKIP 3.35310468086 - 2.24574587978 + 8.34383177258 .. autoclass:: pyemma.msm.estimators.bayesian_hmsm.BayesianHMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.bayesian_hmsm.BayesianHMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.bayesian_hmsm.BayesianHMSM :attributes: References ---------- .. [1] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) .. [2] J. D. Chodera Et Al: Bayesian hidden Markov model analysis of single-molecule force spectroscopy: Characterizing kinetics under measurement uncertainty. arXiv:1108.1430 (2011) """ bhmsm_estimator = _Bayes_HMSM(lag=lag, nstates=nstates, stride=stride, nsamples=nsamples, reversible=reversible, stationary=stationary, connectivity=connectivity, mincount_connectivity=mincount_connectivity, separate=separate, observe_nonempty=observe_nonempty, dt_traj=dt_traj, conf=conf, store_hidden=store_hidden, show_progress=show_progress) return bhmsm_estimator.estimate(dtrajs)
[ "def", "bayesian_hidden_markov_model", "(", "dtrajs", ",", "nstates", ",", "lag", ",", "nsamples", "=", "100", ",", "reversible", "=", "True", ",", "stationary", "=", "False", ",", "connectivity", "=", "None", ",", "mincount_connectivity", "=", "'1/n'", ",", ...
r""" Bayesian Hidden Markov model estimate using Gibbs sampling of the posterior Returns a :class:`BayesianHMSM` that contains the estimated hidden Markov model [1]_ and a Bayesian estimate [2]_ that contains samples around this estimate to estimate uncertainties. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. lag : int lagtime for the MSM estimation in multiples of trajectory steps nstates : int the number of metastable states in the resulting HMM reversible : bool, optional, default = True If true compute reversible MSM, else non-reversible MSM stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. connectivity : str, optional, default = None Defines if the resulting HMM will be defined on all hidden states or on a connected subset. Connectivity is defined by counting only transitions with at least mincount_connectivity counts. If a subset of states is used, all estimated quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than nstates. Following modes are available: * None or 'all' : The active set is the full set of states. Estimation is done on all weakly connected subsets separately. The resulting transition matrix may be disconnected. * 'largest' : The active set is the largest reversibly connected set. * 'populous' : The active set is the reversibly connected set with most counts. mincount_connectivity : float or '1/n' minimum number of counts to consider a connection between two states. Counts lower than that will count zero in the connectivity check and may thus separate the resulting transition matrix. The default evaluates to 1/nstates. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. observe_nonempty : bool If True, will restricted the observed states to the states that have at least one observation in the lagged input trajectories. nsamples : int, optional, default=100 number of transition matrix samples to compute and store stride : str or int, default='effective' stride between two lagged trajectories extracted from the input trajectories. Given trajectory s[t], stride and lag will result in trajectories s[0], s[tau], s[2 tau], ... s[stride], s[stride + tau], s[stride + 2 tau], ... Setting stride = 1 will result in using all data (useful for maximum likelihood estimator), while a Bayesian estimator requires a longer stride in order to have statistically uncorrelated trajectories. Setting stride = None 'effective' uses the largest neglected timescale as an estimate for the correlation time and sets the stride accordingly. conf : float, optional, default=0.95 size of confidence intervals dt_traj : str, optional, default='1 step' Description of the physical time corresponding to the trajectory time step. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): | 'fs', 'femtosecond*' | 'ps', 'picosecond*' | 'ns', 'nanosecond*' | 'us', 'microsecond*' | 'ms', 'millisecond*' | 's', 'second*' store_hidden : bool, optional, default=False store hidden trajectories in sampled HMMs show_progress : bool, default=True Show progressbars for calculation? Returns ------- An :class:`BayesianHMSM` object containing a transition matrix and various other HMM-related quantities and statistical uncertainties. Example ------- Note that the following example is only qualitative and not quantitatively reproducible because random numbers are involved >>> from pyemma import msm >>> dtrajs = [[0,1,2,2,2,2,1,2,2,2,1,0,0,0,0,0,0,0], [0,0,0,0,1,1,2,2,2,2,2,2,2,1,0,0]] # two trajectories >>> mm = msm.bayesian_hidden_markov_model(dtrajs, 2, 2, show_progress=False) We compute the stationary distribution (here given by the maximum likelihood estimate), and the 1-sigma uncertainty interval. You can see that the uncertainties are quite large (we have seen only very few transitions between the metastable states: >>> pi = mm.stationary_distribution >>> piL,piR = mm.sample_conf('stationary_distribution') >>> for i in range(2): print(pi[i],' -',piL[i],'+',piR[i]) # doctest: +SKIP 0.459176653019 - 0.268314552886 + 0.715326151685 0.540823346981 - 0.284761476984 + 0.731730375713 Let's look at the lifetimes of metastable states. Now we have really huge uncertainties. In states where one state is more probable than the other, the mean first passage time from the more probable to the less probable state is much higher than the reverse: >>> l = mm.lifetimes >>> lL, lR = mm.sample_conf('lifetimes') >>> for i in range(2): print(l[i],' -',lL[i],'+',lR[i]) # doctest: +SKIP 7.18543434854 - 6.03617757784 + 80.1298222741 8.65699332061 - 5.35089540896 + 30.1719505772 In contrast the relaxation timescale is less uncertain. This is because for a two-state system the relaxation timescale is dominated by the faster passage, which is less uncertain than the slower passage time: >>> ts = mm.timescales() >>> tsL,tsR = mm.sample_conf('timescales') >>> print(ts[0],' -',tsL[0],'+',tsR[0]) # doctest: +SKIP 3.35310468086 - 2.24574587978 + 8.34383177258 .. autoclass:: pyemma.msm.estimators.bayesian_hmsm.BayesianHMSM :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.bayesian_hmsm.BayesianHMSM :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.bayesian_hmsm.BayesianHMSM :attributes: References ---------- .. [1] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) .. [2] J. D. Chodera Et Al: Bayesian hidden Markov model analysis of single-molecule force spectroscopy: Characterizing kinetics under measurement uncertainty. arXiv:1108.1430 (2011)
[ "r", "Bayesian", "Hidden", "Markov", "model", "estimate", "using", "Gibbs", "sampling", "of", "the", "posterior" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/api.py#L1164-L1325
train
204,195
markovmodel/PyEMMA
pyemma/msm/api.py
estimate_augmented_markov_model
def estimate_augmented_markov_model(dtrajs, ftrajs, lag, m, sigmas, count_mode='sliding', connectivity='largest', dt_traj='1 step', maxiter=1000000, eps=0.05, maxcache=3000): r""" Estimates an Augmented Markov model from discrete trajectories and experimental data Returns a :class:`AugmentedMarkovModel` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. ftrajs : list of trajectories of microscopic observables. Has to have the same shape (number of trajectories and timesteps) as dtrajs. Each timestep in each trajectory should match the shape of m and sigma, k. lag : int lag time at which transitions are counted and the transition matrix is estimated. m : ndarray(k) Experimental averages. sigmas : ndarray(k) Standard error for each experimental observable. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/\tau)-1) \tau \rightarrow T) connectivity : str, optional Connectivity mode. Three methods are intended (currently only 'largest' is implemented) * 'largest' : The active set is the largest reversibly connected set. All estimation will be done on this subset and all quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than the full set of states * 'all' : The active set is the full set of states. Estimation will be conducted on each reversibly connected set separately. That means the transition matrix will decompose into disconnected submatrices, the stationary vector is only defined within subsets, etc. Currently not implemented. * 'none' : The active set is the full set of states. Estimation will be conducted on the full set of states without ensuring connectivity. This only permits nonreversible estimation. Currently not implemented. dt_traj : str, optional Description of the physical time corresponding to the lag. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): * 'fs', 'femtosecond*' * 'ps', 'picosecond*' * 'ns', 'nanosecond*' * 'us', 'microsecond*' * 'ms', 'millisecond*' * 's', 'second*' maxiter : int, optional Optional parameter with specifies the maximum number of updates for Lagrange multiplier estimation. eps : float, optional Additional convergence criterion used when some experimental data are outside the support of the simulation. The value of the eps parameter is the threshold of the relative change in the predicted observables as a function of fixed-point iteration: $$ \mathrm{eps} > \frac{\mid o_{\mathrm{pred}}^{(i+1)}-o_{\mathrm{pred}}^{(i)}\mid }{\sigma}. $$ maxcache : int, optional Parameter which specifies the maximum size of cache used when performing estimation of AMM, in megabytes. Returns ------- amm : :class:`AugmentedMarkovModel <pyemma.msm.AugmentedMarkovModel>` Estimator object containing the AMM and estimation information. See also -------- AugmentedMarkovModel An AMM object that has been estimated from data .. autoclass:: pyemma.msm.estimators.maximum_likelihood_msm.AugmentedMarkovModel :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.AugmentedMarkovModel :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.AugmentedMarkovModel :attributes: References ---------- .. [1] Olsson S, Wu H, Paul F, Clementi C, Noe F "Combining experimental and simulation data of molecular processes via augmented Markov models" PNAS (2017), 114(31), pp. 8265-8270 doi: 10.1073/pnas.1704803114 """ # check input if _np.all(sigmas>0): _w = 1./(2*sigmas**2.) else: raise ValueError('Zero or negative standard errors supplied. Please revise input') if ftrajs[0].ndim < 2: raise ValueError("Supplied feature trajectories have inappropriate dimensions (%d) should be atleast 2."%ftrajs[0].ndim) if len(dtrajs) != len(ftrajs): raise ValueError("A different number of dtrajs and ftrajs were supplied as input. They must have exactly a one-to-one correspondence.") elif not _np.all([len(dt)==len(ft) for dt,ft in zip(dtrajs, ftrajs)]): raise ValueError("One or more supplied dtraj-ftraj pairs do not have the same length.") else: # MAKE E matrix dta = _np.concatenate(dtrajs) fta = _np.concatenate(ftrajs) all_markov_states = set(dta) _E = _np.zeros((len(all_markov_states), fta.shape[1])) for i, s in enumerate(all_markov_states): _E[i, :] = fta[_np.where(dta == s)].mean(axis = 0) # transition matrix estimator mlamm = _ML_AMM(lag=lag, count_mode=count_mode, connectivity=connectivity, dt_traj=dt_traj, maxiter=maxiter, max_cache=maxcache, E=_E, w=_w, m=m) # estimate and return return mlamm.estimate(dtrajs)
python
def estimate_augmented_markov_model(dtrajs, ftrajs, lag, m, sigmas, count_mode='sliding', connectivity='largest', dt_traj='1 step', maxiter=1000000, eps=0.05, maxcache=3000): r""" Estimates an Augmented Markov model from discrete trajectories and experimental data Returns a :class:`AugmentedMarkovModel` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. ftrajs : list of trajectories of microscopic observables. Has to have the same shape (number of trajectories and timesteps) as dtrajs. Each timestep in each trajectory should match the shape of m and sigma, k. lag : int lag time at which transitions are counted and the transition matrix is estimated. m : ndarray(k) Experimental averages. sigmas : ndarray(k) Standard error for each experimental observable. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/\tau)-1) \tau \rightarrow T) connectivity : str, optional Connectivity mode. Three methods are intended (currently only 'largest' is implemented) * 'largest' : The active set is the largest reversibly connected set. All estimation will be done on this subset and all quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than the full set of states * 'all' : The active set is the full set of states. Estimation will be conducted on each reversibly connected set separately. That means the transition matrix will decompose into disconnected submatrices, the stationary vector is only defined within subsets, etc. Currently not implemented. * 'none' : The active set is the full set of states. Estimation will be conducted on the full set of states without ensuring connectivity. This only permits nonreversible estimation. Currently not implemented. dt_traj : str, optional Description of the physical time corresponding to the lag. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): * 'fs', 'femtosecond*' * 'ps', 'picosecond*' * 'ns', 'nanosecond*' * 'us', 'microsecond*' * 'ms', 'millisecond*' * 's', 'second*' maxiter : int, optional Optional parameter with specifies the maximum number of updates for Lagrange multiplier estimation. eps : float, optional Additional convergence criterion used when some experimental data are outside the support of the simulation. The value of the eps parameter is the threshold of the relative change in the predicted observables as a function of fixed-point iteration: $$ \mathrm{eps} > \frac{\mid o_{\mathrm{pred}}^{(i+1)}-o_{\mathrm{pred}}^{(i)}\mid }{\sigma}. $$ maxcache : int, optional Parameter which specifies the maximum size of cache used when performing estimation of AMM, in megabytes. Returns ------- amm : :class:`AugmentedMarkovModel <pyemma.msm.AugmentedMarkovModel>` Estimator object containing the AMM and estimation information. See also -------- AugmentedMarkovModel An AMM object that has been estimated from data .. autoclass:: pyemma.msm.estimators.maximum_likelihood_msm.AugmentedMarkovModel :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.AugmentedMarkovModel :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.AugmentedMarkovModel :attributes: References ---------- .. [1] Olsson S, Wu H, Paul F, Clementi C, Noe F "Combining experimental and simulation data of molecular processes via augmented Markov models" PNAS (2017), 114(31), pp. 8265-8270 doi: 10.1073/pnas.1704803114 """ # check input if _np.all(sigmas>0): _w = 1./(2*sigmas**2.) else: raise ValueError('Zero or negative standard errors supplied. Please revise input') if ftrajs[0].ndim < 2: raise ValueError("Supplied feature trajectories have inappropriate dimensions (%d) should be atleast 2."%ftrajs[0].ndim) if len(dtrajs) != len(ftrajs): raise ValueError("A different number of dtrajs and ftrajs were supplied as input. They must have exactly a one-to-one correspondence.") elif not _np.all([len(dt)==len(ft) for dt,ft in zip(dtrajs, ftrajs)]): raise ValueError("One or more supplied dtraj-ftraj pairs do not have the same length.") else: # MAKE E matrix dta = _np.concatenate(dtrajs) fta = _np.concatenate(ftrajs) all_markov_states = set(dta) _E = _np.zeros((len(all_markov_states), fta.shape[1])) for i, s in enumerate(all_markov_states): _E[i, :] = fta[_np.where(dta == s)].mean(axis = 0) # transition matrix estimator mlamm = _ML_AMM(lag=lag, count_mode=count_mode, connectivity=connectivity, dt_traj=dt_traj, maxiter=maxiter, max_cache=maxcache, E=_E, w=_w, m=m) # estimate and return return mlamm.estimate(dtrajs)
[ "def", "estimate_augmented_markov_model", "(", "dtrajs", ",", "ftrajs", ",", "lag", ",", "m", ",", "sigmas", ",", "count_mode", "=", "'sliding'", ",", "connectivity", "=", "'largest'", ",", "dt_traj", "=", "'1 step'", ",", "maxiter", "=", "1000000", ",", "ep...
r""" Estimates an Augmented Markov model from discrete trajectories and experimental data Returns a :class:`AugmentedMarkovModel` that contains the estimated transition matrix and allows to compute a large number of quantities related to Markov models. Parameters ---------- dtrajs : list containing ndarrays(dtype=int) or ndarray(n, dtype=int) discrete trajectories, stored as integer ndarrays (arbitrary size) or a single ndarray for only one trajectory. ftrajs : list of trajectories of microscopic observables. Has to have the same shape (number of trajectories and timesteps) as dtrajs. Each timestep in each trajectory should match the shape of m and sigma, k. lag : int lag time at which transitions are counted and the transition matrix is estimated. m : ndarray(k) Experimental averages. sigmas : ndarray(k) Standard error for each experimental observable. count_mode : str, optional, default='sliding' mode to obtain count matrices from discrete trajectories. Should be one of: * 'sliding' : A trajectory of length T will have :math:`T-\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (1 \rightarrow \tau+1), ..., (T-\tau-1 \rightarrow T-1) * 'effective' : Uses an estimate of the transition counts that are statistically uncorrelated. Recommended when used with a Bayesian MSM. * 'sample' : A trajectory of length T will have :math:`T/\tau` counts at time indexes .. math:: (0 \rightarrow \tau), (\tau \rightarrow 2 \tau), ..., (((T/\tau)-1) \tau \rightarrow T) connectivity : str, optional Connectivity mode. Three methods are intended (currently only 'largest' is implemented) * 'largest' : The active set is the largest reversibly connected set. All estimation will be done on this subset and all quantities (transition matrix, stationary distribution, etc) are only defined on this subset and are correspondingly smaller than the full set of states * 'all' : The active set is the full set of states. Estimation will be conducted on each reversibly connected set separately. That means the transition matrix will decompose into disconnected submatrices, the stationary vector is only defined within subsets, etc. Currently not implemented. * 'none' : The active set is the full set of states. Estimation will be conducted on the full set of states without ensuring connectivity. This only permits nonreversible estimation. Currently not implemented. dt_traj : str, optional Description of the physical time corresponding to the lag. May be used by analysis algorithms such as plotting tools to pretty-print the axes. By default '1 step', i.e. there is no physical time unit. Specify by a number, whitespace and unit. Permitted units are (* is an arbitrary string): * 'fs', 'femtosecond*' * 'ps', 'picosecond*' * 'ns', 'nanosecond*' * 'us', 'microsecond*' * 'ms', 'millisecond*' * 's', 'second*' maxiter : int, optional Optional parameter with specifies the maximum number of updates for Lagrange multiplier estimation. eps : float, optional Additional convergence criterion used when some experimental data are outside the support of the simulation. The value of the eps parameter is the threshold of the relative change in the predicted observables as a function of fixed-point iteration: $$ \mathrm{eps} > \frac{\mid o_{\mathrm{pred}}^{(i+1)}-o_{\mathrm{pred}}^{(i)}\mid }{\sigma}. $$ maxcache : int, optional Parameter which specifies the maximum size of cache used when performing estimation of AMM, in megabytes. Returns ------- amm : :class:`AugmentedMarkovModel <pyemma.msm.AugmentedMarkovModel>` Estimator object containing the AMM and estimation information. See also -------- AugmentedMarkovModel An AMM object that has been estimated from data .. autoclass:: pyemma.msm.estimators.maximum_likelihood_msm.AugmentedMarkovModel :members: :undoc-members: .. rubric:: Methods .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.AugmentedMarkovModel :methods: .. rubric:: Attributes .. autoautosummary:: pyemma.msm.estimators.maximum_likelihood_msm.AugmentedMarkovModel :attributes: References ---------- .. [1] Olsson S, Wu H, Paul F, Clementi C, Noe F "Combining experimental and simulation data of molecular processes via augmented Markov models" PNAS (2017), 114(31), pp. 8265-8270 doi: 10.1073/pnas.1704803114
[ "r", "Estimates", "an", "Augmented", "Markov", "model", "from", "discrete", "trajectories", "and", "experimental", "data" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/msm/api.py#L1327-L1478
train
204,196
markovmodel/PyEMMA
pyemma/_ext/variational/estimators/moments.py
_is_zero
def _is_zero(x): """ Returns True if x is numerically 0 or an array with 0's. """ if x is None: return True if isinstance(x, numbers.Number): return x == 0.0 if isinstance(x, np.ndarray): return np.all(x == 0) return False
python
def _is_zero(x): """ Returns True if x is numerically 0 or an array with 0's. """ if x is None: return True if isinstance(x, numbers.Number): return x == 0.0 if isinstance(x, np.ndarray): return np.all(x == 0) return False
[ "def", "_is_zero", "(", "x", ")", ":", "if", "x", "is", "None", ":", "return", "True", "if", "isinstance", "(", "x", ",", "numbers", ".", "Number", ")", ":", "return", "x", "==", "0.0", "if", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")"...
Returns True if x is numerically 0 or an array with 0's.
[ "Returns", "True", "if", "x", "is", "numerically", "0", "or", "an", "array", "with", "0", "s", "." ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/variational/estimators/moments.py#L83-L91
train
204,197
markovmodel/PyEMMA
pyemma/_ext/variational/estimators/moments.py
_sparsify
def _sparsify(X, remove_mean=False, modify_data=False, sparse_mode='auto', sparse_tol=0.0): """ Determines the sparsity of X and returns a selected sub-matrix Only conducts sparsification if the number of constant columns is at least max(a N - b, min_const_col_number), Parameters ---------- X : ndarray data matrix remove_mean : bool True: remove column mean from the data, False: don't remove mean. modify_data : bool If remove_mean=True, the mean will be removed in the data matrix X, without creating an independent copy. This option is faster but might lead to surprises because your input array is changed. sparse_mode : str one of: * 'dense' : always use dense mode * 'sparse' : always use sparse mode if possible * 'auto' : automatic Returns ------- X0 : ndarray (view of X) Either X itself (if not sufficiently sparse), or a sliced view of X, containing only the variable columns mask : ndarray(N, dtype=bool) or None Bool selection array that indicates which columns of X were selected for X0, i.e. X0 = X[:, mask]. mask is None if no sparse selection was made. xconst : ndarray(N) Constant column values that are outside the sparse selection, i.e. X[i, ~mask] = xconst for any row i. xconst=0 if no sparse selection was made. """ if sparse_mode.lower() == 'sparse': min_const_col_number = 0 # enforce sparsity. A single constant column will lead to sparse treatment elif sparse_mode.lower() == 'dense': min_const_col_number = X.shape[1] + 1 # never use sparsity else: if remove_mean and not modify_data: # in this case we have to copy the data anyway, and can be permissive min_const_col_number = max(0.1 * X.shape[1], 50) else: # This is a rough heuristic to choose a minimum column number for which sparsity may pay off. # This heuristic is good for large number of samples, i.e. it may be inadequate for small matrices X. if X.shape[1] < 250: min_const_col_number = X.shape[1] - 0.25 * X.shape[1] elif X.shape[1] < 1000: min_const_col_number = X.shape[1] - (0.5 * X.shape[1] - 100) else: min_const_col_number = X.shape[1] - (0.8 * X.shape[1] - 400) # ensure we have an integer again. min_const_col_number = int(min_const_col_number) if X.shape[1] > min_const_col_number: mask = covartools.variable_cols(X, tol=sparse_tol, min_constant=min_const_col_number) # bool vector nconst = len(np.where(~mask)[0]) if nconst > min_const_col_number: xconst = X[0, ~mask] X = X[:, mask] # sparsify else: xconst = None mask = None else: xconst = None mask = None return X, mask, xconst
python
def _sparsify(X, remove_mean=False, modify_data=False, sparse_mode='auto', sparse_tol=0.0): """ Determines the sparsity of X and returns a selected sub-matrix Only conducts sparsification if the number of constant columns is at least max(a N - b, min_const_col_number), Parameters ---------- X : ndarray data matrix remove_mean : bool True: remove column mean from the data, False: don't remove mean. modify_data : bool If remove_mean=True, the mean will be removed in the data matrix X, without creating an independent copy. This option is faster but might lead to surprises because your input array is changed. sparse_mode : str one of: * 'dense' : always use dense mode * 'sparse' : always use sparse mode if possible * 'auto' : automatic Returns ------- X0 : ndarray (view of X) Either X itself (if not sufficiently sparse), or a sliced view of X, containing only the variable columns mask : ndarray(N, dtype=bool) or None Bool selection array that indicates which columns of X were selected for X0, i.e. X0 = X[:, mask]. mask is None if no sparse selection was made. xconst : ndarray(N) Constant column values that are outside the sparse selection, i.e. X[i, ~mask] = xconst for any row i. xconst=0 if no sparse selection was made. """ if sparse_mode.lower() == 'sparse': min_const_col_number = 0 # enforce sparsity. A single constant column will lead to sparse treatment elif sparse_mode.lower() == 'dense': min_const_col_number = X.shape[1] + 1 # never use sparsity else: if remove_mean and not modify_data: # in this case we have to copy the data anyway, and can be permissive min_const_col_number = max(0.1 * X.shape[1], 50) else: # This is a rough heuristic to choose a minimum column number for which sparsity may pay off. # This heuristic is good for large number of samples, i.e. it may be inadequate for small matrices X. if X.shape[1] < 250: min_const_col_number = X.shape[1] - 0.25 * X.shape[1] elif X.shape[1] < 1000: min_const_col_number = X.shape[1] - (0.5 * X.shape[1] - 100) else: min_const_col_number = X.shape[1] - (0.8 * X.shape[1] - 400) # ensure we have an integer again. min_const_col_number = int(min_const_col_number) if X.shape[1] > min_const_col_number: mask = covartools.variable_cols(X, tol=sparse_tol, min_constant=min_const_col_number) # bool vector nconst = len(np.where(~mask)[0]) if nconst > min_const_col_number: xconst = X[0, ~mask] X = X[:, mask] # sparsify else: xconst = None mask = None else: xconst = None mask = None return X, mask, xconst
[ "def", "_sparsify", "(", "X", ",", "remove_mean", "=", "False", ",", "modify_data", "=", "False", ",", "sparse_mode", "=", "'auto'", ",", "sparse_tol", "=", "0.0", ")", ":", "if", "sparse_mode", ".", "lower", "(", ")", "==", "'sparse'", ":", "min_const_c...
Determines the sparsity of X and returns a selected sub-matrix Only conducts sparsification if the number of constant columns is at least max(a N - b, min_const_col_number), Parameters ---------- X : ndarray data matrix remove_mean : bool True: remove column mean from the data, False: don't remove mean. modify_data : bool If remove_mean=True, the mean will be removed in the data matrix X, without creating an independent copy. This option is faster but might lead to surprises because your input array is changed. sparse_mode : str one of: * 'dense' : always use dense mode * 'sparse' : always use sparse mode if possible * 'auto' : automatic Returns ------- X0 : ndarray (view of X) Either X itself (if not sufficiently sparse), or a sliced view of X, containing only the variable columns mask : ndarray(N, dtype=bool) or None Bool selection array that indicates which columns of X were selected for X0, i.e. X0 = X[:, mask]. mask is None if no sparse selection was made. xconst : ndarray(N) Constant column values that are outside the sparse selection, i.e. X[i, ~mask] = xconst for any row i. xconst=0 if no sparse selection was made.
[ "Determines", "the", "sparsity", "of", "X", "and", "returns", "a", "selected", "sub", "-", "matrix" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/variational/estimators/moments.py#L94-L161
train
204,198
markovmodel/PyEMMA
pyemma/_ext/variational/estimators/moments.py
_copy_convert
def _copy_convert(X, const=None, remove_mean=False, copy=True): r""" Makes a copy or converts the data type if needed Copies the data and converts the data type if unsuitable for covariance calculation. The standard data type for covariance computations is float64, because the double precision (but not single precision) is usually sufficient to compute the long sums involved in covariance matrix computations. Integer types are avoided even if the data is integer, because the BLAS matrix multiplication is very fast with floats, but very slow with integers. If X is of boolean type (0/1), the standard data type is float32, because this will be sufficient to represent numbers up to 2^23 without rounding error, which is usually sufficient sufficient as the largest element in np.dot(X.T, X) can then be T, the number of data points. Parameters ---------- remove_mean : bool If True, will enforce float64 even if the input is boolean copy : bool If True, enforces a copy even if the data type doesn't require it. Return ------ X : ndarray copy or reference to X if no copy was needed. const : ndarray or None copy or reference to const if no copy was needed. """ # determine type dtype = np.float64 # default: convert to float64 in order to avoid cancellation errors if X.dtype.kind == 'b' and X.shape[0] < 2**23 and not remove_mean: dtype = np.float32 # convert to float32 if we can represent all numbers # copy/convert if needed if X.dtype not in (np.float64, dtype): # leave as float64 (conversion is expensive), otherwise convert to dtype X = X.astype(dtype, order='C') if const is not None: const = const.astype(dtype, order='C') elif copy: X = X.copy(order='C') if const is not None: const = const.copy(order='C') return X, const
python
def _copy_convert(X, const=None, remove_mean=False, copy=True): r""" Makes a copy or converts the data type if needed Copies the data and converts the data type if unsuitable for covariance calculation. The standard data type for covariance computations is float64, because the double precision (but not single precision) is usually sufficient to compute the long sums involved in covariance matrix computations. Integer types are avoided even if the data is integer, because the BLAS matrix multiplication is very fast with floats, but very slow with integers. If X is of boolean type (0/1), the standard data type is float32, because this will be sufficient to represent numbers up to 2^23 without rounding error, which is usually sufficient sufficient as the largest element in np.dot(X.T, X) can then be T, the number of data points. Parameters ---------- remove_mean : bool If True, will enforce float64 even if the input is boolean copy : bool If True, enforces a copy even if the data type doesn't require it. Return ------ X : ndarray copy or reference to X if no copy was needed. const : ndarray or None copy or reference to const if no copy was needed. """ # determine type dtype = np.float64 # default: convert to float64 in order to avoid cancellation errors if X.dtype.kind == 'b' and X.shape[0] < 2**23 and not remove_mean: dtype = np.float32 # convert to float32 if we can represent all numbers # copy/convert if needed if X.dtype not in (np.float64, dtype): # leave as float64 (conversion is expensive), otherwise convert to dtype X = X.astype(dtype, order='C') if const is not None: const = const.astype(dtype, order='C') elif copy: X = X.copy(order='C') if const is not None: const = const.copy(order='C') return X, const
[ "def", "_copy_convert", "(", "X", ",", "const", "=", "None", ",", "remove_mean", "=", "False", ",", "copy", "=", "True", ")", ":", "# determine type", "dtype", "=", "np", ".", "float64", "# default: convert to float64 in order to avoid cancellation errors", "if", ...
r""" Makes a copy or converts the data type if needed Copies the data and converts the data type if unsuitable for covariance calculation. The standard data type for covariance computations is float64, because the double precision (but not single precision) is usually sufficient to compute the long sums involved in covariance matrix computations. Integer types are avoided even if the data is integer, because the BLAS matrix multiplication is very fast with floats, but very slow with integers. If X is of boolean type (0/1), the standard data type is float32, because this will be sufficient to represent numbers up to 2^23 without rounding error, which is usually sufficient sufficient as the largest element in np.dot(X.T, X) can then be T, the number of data points. Parameters ---------- remove_mean : bool If True, will enforce float64 even if the input is boolean copy : bool If True, enforces a copy even if the data type doesn't require it. Return ------ X : ndarray copy or reference to X if no copy was needed. const : ndarray or None copy or reference to const if no copy was needed.
[ "r", "Makes", "a", "copy", "or", "converts", "the", "data", "type", "if", "needed" ]
5c3124398217de05ba5ce9c8fb01519222481ab8
https://github.com/markovmodel/PyEMMA/blob/5c3124398217de05ba5ce9c8fb01519222481ab8/pyemma/_ext/variational/estimators/moments.py#L181-L224
train
204,199