code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
def set_siren_strobe_enabled(self, enabled):
values = {
"desired_state": {
"strobe_enabled": enabled
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param enabled: True or False
:return: nothing | null | null | null | |
def set_chime_strobe_enabled(self, enabled):
values = {
"desired_state": {
"chime_strobe_enabled": enabled
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param enabled: True or False
:return: nothing | null | null | null | |
def set_siren_sound(self, sound):
values = {
"desired_state": {
"siren_sound": sound
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param sound: a str, one of ["doorbell", "fur_elise", "doorbell_extended", "alert",
"william_tell", "rondo_alla_turca", "police_siren",
""evacuation", "beep_beep", "beep"]
:return: nothing | null | null | null | |
def set_chime(self, sound, cycles=None):
desired_state = {"activate_chime": sound}
if cycles is not None:
desired_state.update({"chime_cycles": cycles})
response = self.api_interface.set_device_state(self,
{"desire... | :param sound: a str, one of ["doorbell", "fur_elise", "doorbell_extended", "alert",
"william_tell", "rondo_alla_turca", "police_siren",
""evacuation", "beep_beep", "beep", "inactive"]
:param cycles: Undocumented seems to have no effect... | null | null | null | |
def set_auto_shutoff(self, timer):
values = {
"desired_state": {
"auto_shutoff": timer
}
}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param timer: an int, one of [None (never), -1, 30, 60, 120]
:return: nothing | null | null | null | |
def set_state(self, state):
values = {"desired_state": {"powered": state}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param state: a boolean of true (on) or false ('off')
:return: nothing | null | null | null | |
r
ind = np.diag_indices(T.shape[0])
flux = pi[:, np.newaxis] * qminus[:, np.newaxis] * T * qplus[np.newaxis, :]
flux[ind] = 0.0
if netflux:
return to_netflux(flux)
else:
return flux | def flux_matrix(T, pi, qminus, qplus, netflux=True) | r"""Compute the TPT flux network for the reaction A-->B.
Parameters
----------
T : (M, M) ndarray
transition matrix
pi : (M,) ndarray
Stationary distribution corresponding to T
qminus : (M,) ndarray
Backward comittor
qplus : (M,) ndarray
Forward committor
net... | 3.737907 | 5.186746 | 0.720665 |
r
netflux = flux - np.transpose(flux)
ind = (netflux < 0.0)
netflux[ind] = 0.0
return netflux | def to_netflux(flux) | r"""Compute the netflux from the gross flux.
f_ij^{+}=max{0, f_ij-f_ji}
for all pairs i,j
Parameters
----------
flux : (M, M) ndarray
Matrix of flux values between pairs of states.
Returns
-------
netflux : (M, M) ndarray
Matrix of netflux values between pairs ... | 5.61273 | 6.756031 | 0.830773 |
r
influxes = np.array(np.sum(F, axis=0)).flatten() # all that flows in
outfluxes = np.array(np.sum(F, axis=1)).flatten() # all that flows out
prod = outfluxes - influxes # net flux into nodes
return prod | def flux_production(F) | r"""Returns the net flux production for all states
Parameters
----------
F : (n, n) ndarray
Matrix of flux values between pairs of states.
Returns
-------
prod : (n) ndarray
array with flux production (positive) or consumption (negative) at each state | 5.563051 | 5.263796 | 1.056852 |
r
n = F.shape[0]
influxes = np.array(np.sum(F, axis=0)).flatten() # all that flows in
outfluxes = np.array(np.sum(F, axis=1)).flatten() # all that flows out
# net out flux absolute
prod_abs = np.maximum(outfluxes - influxes, np.zeros(n))
# net out flux relative
prod_rel = prod_abs / (n... | def flux_producers(F, rtol=1e-05, atol=1e-12) | r"""Return indexes of states that are net flux producers.
Parameters
----------
F : (n, n) ndarray
Matrix of flux values between pairs of states.
rtol : float
relative tolerance. fulfilled if max(outflux-influx, 0) / max(outflux,influx) < rtol
atol : float
absolute tolerance... | 4.579448 | 3.734702 | 1.226189 |
r
# can be used with sparse or dense
n = np.shape(F)[0]
influxes = np.array(np.sum(F, axis=0)).flatten() # all that flows in
outfluxes = np.array(np.sum(F, axis=1)).flatten() # all that flows out
# net in flux absolute
con_abs = np.maximum(influxes - outfluxes, np.zeros(n))
# net in fl... | def flux_consumers(F, rtol=1e-05, atol=1e-12) | r"""Return indexes of states that are net flux producers.
Parameters
----------
F : (n, n) ndarray
Matrix of flux values between pairs of states.
rtol : float
relative tolerance. fulfilled if max(outflux-influx, 0) / max(outflux,influx) < rtol
atol : float
absolute tolerance... | 4.941715 | 4.333477 | 1.140358 |
r
nnew = len(sets)
Fc = np.zeros((nnew, nnew))
for i in range(0, nnew - 1):
for j in range(i + 1, nnew):
I = list(sets[i])
J = list(sets[j])
Fc[i, j] = np.sum(F[I, :][:, J])
Fc[j, i] = np.sum(F[J, :][:, I])
return Fc | def coarsegrain(F, sets) | r"""Coarse-grains the flux to the given sets
$fc_{i,j} = \sum_{i \in I,j \in J} f_{i,j}$
Note that if you coarse-grain a net flux, it does not necessarily have a net
flux property anymore. If want to make sure you get a netflux,
use to_netflux(coarsegrain(F,sets)).
Parameters
----------
F ... | 2.150784 | 2.279007 | 0.943737 |
r
if A is None:
prod = flux_production(F)
zeros = np.zeros(len(prod))
outflux = np.sum(np.maximum(prod, zeros))
return outflux
else:
X = set(np.arange(F.shape[0])) # total state space
A = set(A)
notA = X.difference(A)
outflux = (F[list(A), :])... | def total_flux(F, A=None) | r"""Compute the total flux, or turnover flux, that is produced by the
flux sources and consumed by the flux sinks
Parameters
----------
F : (n, n) ndarray
Matrix of flux values between pairs of states.
A : array_like (optional)
List of integer state labels for set A (reactant)
... | 5.141552 | 4.646317 | 1.106587 |
r
kAB = totflux / (pi * qminus).sum()
return kAB | def rate(totflux, pi, qminus) | r"""Transition rate for reaction A to B.
Parameters
----------
totflux : float
The total flux between reactant and product
pi : (M,) ndarray
Stationary distribution
qminus : (M,) ndarray
Backward comittor
Returns
-------
kAB : float
The reaction rate (pe... | 19.174501 | 10.588047 | 1.810957 |
nowstamp = datetime.now().strftime("%d-%b-%Y %H:%M:%S.%f")[:-3]
self._add_entry(templates.INIT
.format(time_stamp=nowstamp))
if permissive:
self._add_entry(templates.INIT_DEBUG) | def _init_journal(self, permissive=True) | Add the initialization lines to the journal.
By default adds JrnObj variable and timestamp to the journal contents.
Args:
permissive (bool): if True most errors in journal will not
cause Revit to stop journal execution.
Some sti... | 5.899694 | 7.222394 | 0.816861 |
self._add_entry(base_template)
self._add_entry(templates.NEW_FROM_RFT
.format(rft_file_path=rft_file,
rft_file_name=op.basename(rft_file))) | def _new_from_rft(self, base_template, rft_file) | Append a new file from .rft entry to the journal.
This instructs Revit to create a new model based on
the provided .rft template.
Args:
base_template (str): new file journal template from rmj.templates
rft_file (str): full path to .rft template to be used | 4.454852 | 4.559466 | 0.977056 |
self._add_entry(templates.NEW_MODEL
.format(template_name=template_name)) | def new_model(self, template_name='<None>') | Append a new model from .rft entry to the journal.
This instructs Revit to create a new model based on the
provided .rft template.
Args:
template_name (str): optional full path to .rft template
to be used. default value is <None> | 11.439481 | 11.441063 | 0.999862 |
self._add_entry(templates.NEW_MODEL_TEMPLATE
.format(template_name=template_name)) | def new_template(self, template_name='<None>') | Append a new template from .rft entry to the journal.
This instructs Revit to create a new template model based on the
provided .rft template.
Args:
template_name (str): optional full path to .rft template
to be used. default value is <None> | 13.216263 | 12.470083 | 1.059838 |
if detached:
if audit:
if keep_worksets:
self._add_entry(
templates.CENTRAL_OPEN_DETACH_AUDIT
.format(model_path=model_path,
workset_config=show_workset_conf... | def open_workshared_model(self, model_path, central=False,
detached=False, keep_worksets=True, audit=False,
show_workset_config=1) | Append a open workshared model entry to the journal.
This instructs Revit to open a workshared model.
Args:
model_path (str): full path to workshared model
central (bool): if True opens central model and not local
detached (bool): if True opens a detached model
... | 1.430451 | 1.452737 | 0.984659 |
if audit:
self._add_entry(templates.FILE_OPEN_AUDIT
.format(model_path=model_path))
else:
self._add_entry(templates.FILE_OPEN
.format(model_path=model_path)) | def open_model(self, model_path, audit=False) | Append a open non-workshared model entry to the journal.
This instructs Revit to open a non-workshared model.
Args:
model_path (str): full path to non-workshared model
audit (bool): if True audits the model when opening | 3.777316 | 4.087725 | 0.924063 |
# make sure command_data is not empty
command_data = {} if command_data is None else command_data
# make the canonical name for the command
cmdclassname = '{}.{}'.format(command_module, command_class)
self._add_entry(templates.EXTERNAL_COMMAND
... | def execute_command(self, tab_name, panel_name,
command_module, command_class, command_data=None) | Append an execute external command entry to the journal.
This instructs Revit to execute the provided command from the
provided module, tab, and panel.
Args:
tab_name (str): name of ribbon tab that contains the command
panel_name (str): name of ribbon panel that contain... | 3.379219 | 3.366688 | 1.003722 |
self._add_entry(templates.DYNAMO_COMMAND
.format(dynamo_def_path=definition_path,
dyn_show_ui=show_ui,
dyn_automation=automation,
dyn_path_exec=pat... | def execute_dynamo_definition(self, definition_path,
show_ui=False, shutdown=True,
automation=False, path_exec=True) | Execute a dynamo definition.
Args:
definition_path (str): full path to dynamo definition file
show_ui (bool): show dynamo UI at execution
shutdown (bool): shutdown model after execution
automation (bool): activate dynamo automation
path_exec (bool): a... | 4.94543 | 5.234317 | 0.944809 |
self._add_entry(templates.IMPORT_FAMILY
.format(family_file=rfa_file)) | def import_family(self, rfa_file) | Append a import family entry to the journal.
This instructs Revit to import a family into the opened model.
Args:
rfa_file (str): full path of the family file | 13.06591 | 12.345138 | 1.058385 |
warn_filepath = op.dirname(export_file)
warn_filename = op.splitext(op.basename(export_file))[0]
self._add_entry(templates.EXPORT_WARNINGS
.format(warnings_export_path=warn_filepath,
warnings_export_file=warn_file... | def export_warnings(self, export_file) | Append an export warnings entry to the journal.
This instructs Revit to export warnings from the opened model.
Currently Revit will stop journal execution if the model does not
have any warnings and the export warnings UI button is disabled.
Args:
export_file (str): full pa... | 5.024599 | 5.695649 | 0.882182 |
for purge_count in range(0, pass_count):
self._add_entry(templates.PROJECT_PURGE) | def purge_unused(self, pass_count=3) | Append an purge model entry to the journal.
This instructs Revit to purge the open model.
Args:
pass_count (int): number of times to execute the purge.
default is 3 | 14.01365 | 12.096889 | 1.158451 |
self._add_entry(templates.FILE_SYNC_START)
if compact_central:
self._add_entry(templates.FILE_SYNC_COMPACT)
if release_borrowed:
self._add_entry(templates.FILE_SYNC_RELEASE_BORROWED)
if release_workset:
self._add_entry(templates.FILE_SYNC_REL... | def sync_model(self, comment='', compact_central=False,
release_borrowed=True, release_workset=True,
save_local=False) | Append a sync model entry to the journal.
This instructs Revit to sync the currently open workshared model.
Args:
comment (str): comment to be provided for the sync step
compact_central (bool): if True compacts the central file
release_borrowed (bool): if True relea... | 2.758577 | 2.610988 | 1.056526 |
# TODO: assert the extension is txt and not other
with open(journal_file_path, "w") as jrn_file:
jrn_file.write(self._journal_contents) | def write_journal(self, journal_file_path) | Write the constructed journal in to the provided file.
Args:
journal_file_path (str): full path to output journal file | 5.951227 | 6.886664 | 0.864167 |
for entry in reversed(list(open(self._jrnl_file, 'r'))[-5:]):
if search_str in entry:
return True
return False | def endswith(self, search_str) | Check whether the provided string exists in Journal file.
Only checks the last 5 lines of the journal file. This method is
usually used when tracking a journal from an active Revit session.
Args:
search_str (str): string to search for
Returns:
bool: if True the... | 7.807122 | 5.22616 | 1.493854 |
r
X = set(range(T.shape[0]))
A = set(A)
B = set(B)
AB = A.intersection(B)
notAB = X.difference(A).difference(B)
if len(AB) > 0:
raise ValueError("Sets A and B have to be disjoint")
L = T - np.eye(T.shape[0]) # Generator matrix
W = 1.0 * L
W[list(A), :] = ... | def forward_committor(T, A, B) | r"""Forward committor between given sets.
The forward committor u(x) between sets A and B is the probability
for the chain starting in x to reach B before reaching A.
Parameters
----------
T : (M, M) ndarray
Transition matrix
A : array_like
List of integer state labels for set ... | 3.443702 | 3.449283 | 0.998382 |
r
X = set(range(T.shape[0]))
A = set(A)
B = set(B)
AB = A.intersection(B)
notAB = X.difference(A).difference(B)
if len(AB) > 0:
raise ValueError("Sets A and B have to be disjoint")
if mu is None:
mu = stationary_distribution(T)
K = np.transpose(mu[:, np.newaxis] * (T ... | def backward_committor(T, A, B, mu=None) | r"""Backward committor between given sets.
The backward committor u(x) between sets A and B is the
probability for the chain starting in x to have come from A last
rather than from B.
Parameters
----------
T : (M, M) ndarray
Transition matrix
A : array_like
List of integer ... | 3.299197 | 3.477641 | 0.948688 |
r
C_sym = C + C.transpose()
C_sym = C_sym.tocoo()
data = C_sym.data
row = C_sym.row
col = C_sym.col
data_B = alpha * np.ones_like(data)
B = coo_matrix((data_B, (row, col)))
return B | def prior_neighbor(C, alpha=0.001) | r"""Neighbor prior of strength alpha for the given count matrix.
Prior is defined by
b_ij = alpha if Z_ij+Z_ji > 0
b_ij = 0 else
Parameters
----------
C : (M, M) scipy.sparse matrix
Count matrix
alpha : float (optional)
Value of prior counts
Returns
-... | 3.491187 | 3.847813 | 0.907317 |
B = alpha * np.ones(C.shape)
return B | def prior_const(C, alpha=0.001) | Constant prior of strength alpha.
Prior is defined via
b_ij=alpha for all i,j
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
alpha : float (optional)
Value of prior counts
Returns
-------
B : (M, M) ndarray
Prior count mat... | 6.088762 | 12.366336 | 0.492366 |
r
ind = np.triu_indices(C.shape[0])
B = np.zeros(C.shape)
B[ind] = alpha
return B | def prior_rev(C, alpha=-1.0) | r"""Prior counts for sampling of reversible transition
matrices.
Prior is defined as
b_ij= alpha if i<=j
b_ij=0 else
The reversible prior adds -1 to the upper triagular part of
the given count matrix. This prior respects the fact that
for a reversible transition matrix the degrees... | 4.805548 | 4.767982 | 1.007879 |
# check input
dtrajs = _ensure_dtraj_list(dtrajs)
# select subset unless given
n = number_of_states(dtrajs)
if subset is None:
subset = list(range(n))
else:
if np.max(subset) >= n:
raise ValueError('Selected subset is not a subset of the states in dtrajs.')
#... | def index_states(dtrajs, subset = None) | Generates a trajectory/time indexes for the given list of states
Parameters
----------
dtraj : array_like or list of array_like
Discretized trajectory or list of discretized trajectories
subset : ndarray((n)), optional, default = None
array of states to be indexed. By default all states... | 3.244435 | 3.234074 | 1.003204 |
# how many states in total?
n = len(indexes)
# define set of states to work on
if subset is None:
subset = list(range(n))
# list of states
res = np.ndarray((len(subset)), dtype=object)
for i in range(len(subset)):
# sample the following state
s = subset[i]
... | def sample_indexes_by_state(indexes, nsample, subset=None, replace=True) | Samples trajectory/time indexes according to the given sequence of states
Parameters
----------
indexes : list of ndarray( (N_i, 2) )
For each state, all trajectory and time indexes where this state occurs.
Each matrix has a number of rows equal to the number of occurrences of the correspon... | 3.185447 | 3.29817 | 0.965822 |
# how many states in total?
n = len(indexes)
for dist in distributions:
if len(dist) != n:
raise ValueError('Size error: Distributions must all be of length n (number of states).')
# list of states
res = np.ndarray((len(distributions)), dtype=object)
for i in range(len(... | def sample_indexes_by_distribution(indexes, distributions, nsample) | Samples trajectory/time indexes according to the given probability distributions
Parameters
----------
indexes : list of ndarray( (N_i, 2) )
For each state, all trajectory and time indexes where this state occurs.
Each matrix has a number of rows equal to the number of occurrences of the co... | 4.121412 | 4.106478 | 1.003637 |
if T.ndim != 2:
return False
if T.shape[0] != T.shape[1]:
return False
dim = T.shape[0]
X = np.abs(T) - T
x = np.sum(T, axis=1)
return np.abs(x - np.ones(dim)).max() < dim * tol and X.max() < 2.0 * tol | def is_transition_matrix(T, tol=1e-10) | Tests whether T is a transition matrix
Parameters
----------
T : ndarray shape=(n, n)
matrix to test
tol : float
tolerance to check with
Returns
-------
Truth value : bool
True, if all elements are in interval [0, 1]
and each row of T sums up to 1.
... | 3.32118 | 3.789859 | 0.876333 |
R = K - K.diagonal()
off_diagonal_positive = np.allclose(R, abs(R), 0.0, atol=tol)
row_sum = K.sum(axis=1)
row_sum_eq_0 = np.allclose(row_sum, 0.0, atol=tol)
return off_diagonal_positive and row_sum_eq_0 | def is_rate_matrix(K, tol=1e-10) | True if K is a rate matrix
Parameters
----------
K : numpy.ndarray matrix
Matrix to check
tol : float
tolerance to check with
Returns
-------
Truth value : bool
True, if K negated diagonal is positive and row sums up to zero.
False, otherwise | 3.221431 | 3.430368 | 0.939092 |
r
if is_transition_matrix(T, tol):
if mu is None:
mu = stationary_distribution(T)
X = mu[:, np.newaxis] * T
return np.allclose(X, np.transpose(X), atol=tol)
else:
raise ValueError("given matrix is not a valid transition matrix.") | def is_reversible(T, mu=None, tol=1e-10) | r"""
checks whether T is reversible in terms of given stationary distribution.
If no distribution is given, it will be calculated out of T.
It performs following check:
:math:`\pi_i P_{ij} = \pi_j P_{ji}`
Parameters
----------
T : numpy.ndarray matrix
Transition matrix
mu : num... | 4.46764 | 4.63983 | 0.962889 |
r
# Determine number of states
if nstates is None:
from msmtools.dtraj import number_of_states
nstates = number_of_states(dtrajs)
rows = []
cols = []
# collect transition index pairs
for dtraj in dtrajs:
if dtraj.size > lag:
if (sliding):
r... | def count_matrix_coo2_mult(dtrajs, lag, sliding=True, sparse=True, nstates=None) | r"""Generate a count matrix from a given list discrete trajectories.
The generated count matrix is a sparse matrix in compressed
sparse row (CSR) or numpy ndarray format.
Parameters
----------
dtraj : list of ndarrays
discrete trajectories
lag : int
Lagtime in trajectory steps
... | 3.235902 | 3.276832 | 0.987509 |
T = T.tocsr() # compressed sparse row for fast row slicing
values = T.data # non-zero entries of T
is_positive = np.allclose(values, np.abs(values), rtol=tol)
is_normed = np.allclose(T.sum(axis=1), 1.0, rtol=tol)
return is_positive and is_normed | def is_transition_matrix(T, tol) | True if T is a transition matrix
Parameters
----------
T : scipy.sparse matrix
Matrix to check
tol : float
tolerance to check with
Returns
-------
Truth value: bool
True, if T is positive and normed
False, otherwise | 4.664536 | 4.787979 | 0.974218 |
K = K.tocsr()
# check rows sum up to zero.
row_sum = K.sum(axis=1)
sum_eq_zero = np.allclose(row_sum, np.zeros(shape=row_sum.shape), atol=tol)
# store copy of original diagonal
org_diag = K.diagonal()
# substract diagonal
K = K - diags(org_diag, 0)
# check off diagonals are ... | def is_rate_matrix(K, tol) | True if K is a rate matrix
Parameters
----------
K : scipy.sparse matrix
Matrix to check
tol : float
tolerance to check with
Returns
-------
Truth value : bool
True, if K negated diagonal is positive and row sums up to zero.
False, otherwise | 3.530581 | 3.687974 | 0.957323 |
r
if not is_transition_matrix(T, tol):
raise ValueError("given matrix is not a valid transition matrix.")
T = T.tocsr()
if mu is None:
from .decomposition import stationary_distribution
mu = stationary_distribution(T)
Mu = diags(mu, 0)
prod = Mu * T
return allclos... | def is_reversible(T, mu=None, tol=1e-15) | r"""
checks whether T is reversible in terms of given stationary distribution.
If no distribution is given, it will be calculated out of T.
performs follwing check:
:math:`\pi_i P_{ij} = \pi_j P_{ji}
Parameters
----------
T : scipy.sparse matrix
Transition matrix
mu : numpy.ndar... | 5.135998 | 5.41683 | 0.948156 |
r
nc = connected_components(T, directed=directed, connection='strong', \
return_labels=False)
return nc == 1 | def is_connected(T, directed=True) | r"""Check connectivity of the transition matrix.
Return true, if the input matrix is completely connected,
effectively checking if the number of connected components equals one.
Parameters
----------
T : scipy.sparse matrix
Transition matrix
directed : bool, optional
Whether to ... | 9.605305 | 10.584678 | 0.907473 |
if isdense(T):
T = T.tocsr()
if not is_transition_matrix(T, tol):
raise ValueError("given matrix is not a valid transition matrix.")
num_components = connected_components(T, directed=True, \
connection='strong', \
... | def is_ergodic(T, tol) | checks if T is 'ergodic'
Parameters
----------
T : scipy.sparse matrix
Transition matrix
tol : float
tolerance
Returns
-------
Truth value : bool
True, if # strongly connected components = 1
False, otherwise | 4.77468 | 4.601088 | 1.037729 |
if opts.config is not None:
os.environ["CALLSIGN_CONFIG_FILE"] = opts.config
sys.argv[1:] = [
"-noy", sibpath(__file__, "callsign.tac"),
"--pidfile", conf['pidfile'],
"--logfile", conf['logfile'],
]
twistd.run() | def spawn(opts, conf) | Acts like twistd | 7.539707 | 6.385431 | 1.180767 |
r
if F.nnz == 0:
raise PathwayError('no more pathways left: Flux matrix does not contain any positive entries')
F = F.tocoo()
n = F.shape[0]
val = F.data
row = F.row
col = F.col
ind = np.argsort(val)
val = val[ind]
row = row[ind]
col = col[ind]
b... | def find_bottleneck(F, A, B) | r"""Find dynamic bottleneck of flux network.
Parameters
----------
F : scipy.sparse matrix
The flux network
A : array_like
The set of starting states
B : array_like
The set of end states
Returns
-------
e : tuple of int
The edge corresponding to the dynamic ... | 3.474557 | 3.457688 | 1.004879 |
r
for istart in A:
nodes = csgraph.breadth_first_order(graph, istart, directed=True, return_predecessors=False)
if has_path(nodes, A, B):
return True
return False | def has_connection(graph, A, B) | r"""Check if the given graph contains a path connecting A and B.
Parameters
----------
graph : scipy.sparse matrix
Adjacency matrix of the graph
A : array_like
The set of starting states
B : array_like
The set of end states
Returns
-------
hc : bool
True ... | 5.846769 | 5.899852 | 0.991003 |
r
x1 = np.intersect1d(nodes, A).size > 0
x2 = np.intersect1d(nodes, B).size > 0
return x1 and x2 | def has_path(nodes, A, B) | r"""Test if nodes from a breadth_first_order search lead from A to
B.
Parameters
----------
nodes : array_like
Nodes from breadth_first_oder_seatch
A : array_like
The set of educt states
B : array_like
The set of product states
Returns
-------
has_path : boo... | 3.772762 | 4.695252 | 0.803527 |
r
if F.nnz == 0:
raise PathwayError('no more pathways left: Flux matrix does not contain any positive entries')
b1, b2, F = find_bottleneck(F, A, B)
if np.any(A == b1):
wL = [b1, ]
elif np.any(B == b1):
raise PathwayError(("Roles of vertices b1 and b2 are switched."
... | def pathway(F, A, B) | r"""Compute the dominant reaction-pathway.
Parameters
----------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
A : array_like
The set of starting states
B : array_like
The set of end states
Returns
-------
w : list
The domina... | 4.036398 | 3.726738 | 1.083091 |
r
F = F.todok()
L = len(path)
currents = np.zeros(L - 1)
for l in range(L - 1):
i = path[l]
j = path[l + 1]
currents[l] = F[i, j]
return currents.min() | def capacity(F, path) | r"""Compute capacity (min. current) of path.
Paramters
---------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
path : list
Reaction path
Returns
-------
c : float
Capacity (min. current of path) | 3.497467 | 3.183986 | 1.098455 |
r
c = capacity(F, path)
F = F.todok()
L = len(path)
for l in range(L - 1):
i = path[l]
j = path[l + 1]
F[i, j] -= c
return F | def remove_path(F, path) | r"""Remove capacity along a path from flux network.
Parameters
----------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
path : list
Reaction path
Returns
-------
F : (M, M) scipy.sparse matrix
The updated flux network | 4.836959 | 4.336917 | 1.115299 |
r
F, a, b = add_endstates(F, A, B)
A = [a, ]
B = [b, ]
TF = F.tocsr()[A, :].sum()
CF = 0.0
niter = 0
paths = []
capacities = []
while True:
try:
path = pathway(F, A, B)
except PathwayError:
break
... | def pathways(F, A, B, fraction=1.0, maxiter=1000, tol=1e-14) | r"""Decompose flux network into dominant reaction paths.
Parameters
----------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
A : array_like
The set of starting states
B : array_like
The set of end states
fraction : float, optional
Fra... | 4.601171 | 4.644146 | 0.990746 |
r
F = F.tocsr()
outA = (F[A, :].sum(axis=1)).getA()[:, 0]
F = F.tocsc()
inB = (F[:, B].sum(axis=0)).getA()[0, :]
F = F.tocoo()
M = F.shape[0]
data_old = F.data
row_old = F.row
col_old = F.col
row1 = np.zeros(outA.shape[0], dtype=np.int)
row1[:] = M
... | def add_endstates(F, A, B) | r"""Adds artifical end states replacing source and sink sets.
Parameters
----------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
A : array_like
The set of starting states
B : array_like
The set of end states
Returns
-------
F_new : ... | 2.445923 | 2.250388 | 1.086889 |
assert isinstance(txt, six.binary_type)
try:
_ = six.text_type(txt, 'utf-8')
except (TypeError, UnicodeEncodeError):
return False
else:
return True | def _is_utf_8(txt) | Check a string is utf-8 encoded
:param bytes txt: utf-8 string
:return: Whether the string\
is utf-8 encoded or not
:rtype: bool | 2.640316 | 3.259678 | 0.809993 |
for path in scripts_paths:
self.run_script(_read_file(path), identifier=path) | def load_libs(self, scripts_paths) | Load script files into the context.\
This can be thought as the HTML script tag.\
The files content must be utf-8 encoded.
This is a shortcut for reading the files\
and pass the content to :py:func:`run_script`
:param list scripts_paths: Script file paths.
:raises OSErr... | 8.11644 | 8.340145 | 0.973177 |
assert isinstance(script, six.text_type) or _is_utf_8(script)
assert isinstance(identifier, six.text_type) or _is_utf_8(identifier)
if isinstance(script, six.text_type):
script = script.encode('utf-8')
if isinstance(identifier, six.text_type):
identifie... | def run_script(self, script, identifier=_DEFAULT_SCRIPT_NAME) | Run a JS script within the context.\
All code is ran synchronously,\
there is no event loop. It's thread-safe
:param script: utf-8 encoded or unicode string
:type script: bytes or str
:param identifier: utf-8 encoded or unicode string.\
This is used as the name of the sc... | 2.74623 | 2.676774 | 1.025948 |
r
if reversible:
try:
evals = eigenvalues_rev(T, k=k, mu=mu)
except:
evals = eigvals(T).real # use fallback code but cast to real
else:
evals = eigvals(T) # nonreversible
ind = np.argsort(np.abs(evals))[::-1]
evals = evals[ind]
if isinstan... | def eigenvalues(T, k=None, reversible=False, mu=None) | r"""Compute eigenvalues of given transition matrix.
Parameters
----------
T : (d, d) ndarray
Transition matrix (stochastic matrix)
k : int or tuple of ints, optional
Compute the first k eigenvalues of T
reversible : bool, optional
Indicate that transition matrix is reversibl... | 4.201687 | 4.454886 | 0.943164 |
r
if mu is None:
mu = stationary_distribution(T)
if np.any(mu <= 0):
raise ValueError('Cannot symmetrize transition matrix')
smu = np.sqrt(mu)
S = smu[:,None] * T / smu
evals = eigvalsh(S)
return evals | def eigenvalues_rev(T, k=None, mu=None) | r"""Compute eigenvalues of reversible transition matrix.
Parameters
----------
T : (d, d) ndarray
Transition matrix (stochastic matrix)
k : int or tuple of ints, optional
Compute the first k eigenvalues of T
mu : (d,) ndarray, optional
Stationary distribution of T
Retur... | 6.343354 | 5.905787 | 1.074091 |
r
if reversible:
eigvec = eigenvectors_rev(T, right=right, mu=mu)
else:
eigvec = eigenvectors_nrev(T, right=right)
if k is None:
return eigvec
elif isinstance(k, numbers.Integral):
return eigvec[:, 0:k]
else:
ind = np.asarray(k)
return eigvec... | def eigenvectors(T, k=None, right=True, reversible=False, mu=None) | r"""Compute eigenvectors of transition matrix.
Parameters
----------
T : (d, d) ndarray
Transition matrix (stochastic matrix)
k : int or tuple of ints, optional
Compute the first k eigenvalues of T
right : bool, optional
If right=True compute right eigenvectors, left eigenve... | 3.095051 | 3.376554 | 0.91663 |
r
if right:
val, R = eig(T, left=False, right=True)
perm = np.argsort(np.abs(val))[::-1]
# eigval=val[perm]
eigvec = R[:, perm]
else:
val, L = eig(T, left=True, right=False)
perm = np.argsort(np.abs(val))[::-1]
# eigval=val[perm]
... | def eigenvectors_nrev(T, right=True) | r"""Compute eigenvectors of transition matrix.
Parameters
----------
T : (d, d) ndarray
Transition matrix (stochastic matrix)
k : int or tuple of ints, optional
Compute the first k eigenvalues of T
right : bool, optional
If right=True compute right eigenvectors, left eigenve... | 3.124914 | 3.162737 | 0.988041 |
r
if mu is None:
mu = stationary_distribution(T)
smu = np.sqrt(mu)
S = smu[:,None] * T / smu
val, eigvec = eigh(S)
perm = np.argsort(np.abs(val))[::-1]
eigvec = eigvec[:, perm]
if right:
return eigvec / smu[:, np.newaxis]
else:
return eigvec * smu[:,... | def eigenvectors_rev(T, right=True, mu=None) | r"""Compute eigenvectors of reversible transition matrix.
Parameters
----------
T : (d, d) ndarray
Transition matrix (stochastic matrix)
right : bool, optional
If right=True compute right eigenvectors, left eigenvectors
otherwise
mu : (d,) ndarray, optional
Stationar... | 3.890896 | 3.773581 | 1.031089 |
r
# auto-set norm
if norm == 'auto':
if is_reversible(T):
norm = 'reversible'
else:
norm = 'standard'
if reversible:
R, D, L = rdl_decomposition_rev(T, norm=norm, mu=mu)
else:
R, D, L = rdl_decomposition_nrev(T, norm=norm)
if k is None:
... | def rdl_decomposition(T, k=None, reversible=False, norm='standard', mu=None) | r"""Compute the decomposition into left and right eigenvectors.
Parameters
----------
T : (M, M) ndarray
Transition matrix
k : int (optional)
Number of eigenvector/eigenvalue pairs
norm: {'standard', 'reversible', 'auto'}
standard: (L'R) = Id, L[:,0] is a probability distrib... | 2.767731 | 2.545068 | 1.087488 |
r
d = T.shape[0]
w, R = eig(T)
ind = np.argsort(np.abs(w))[::-1]
w = w[ind]
R = R[:, ind]
D = np.diag(w)
# Standard norm: Euclidean norm is 1 for r and LR = I.
if norm == 'standard':
L = solve(np.transpose(R), np.eye(d))
R[:, 0] = R[:, 0] * np.s... | def rdl_decomposition_nrev(T, norm='standard') | r"""Decomposition into left and right eigenvectors.
Parameters
----------
T : (M, M) ndarray
Transition matrix
norm: {'standard', 'reversible'}
standard: (L'R) = Id, L[:,0] is a probability distribution,
the stationary distribution mu of T. Right eigenvectors
R h... | 3.415251 | 3.357799 | 1.01711 |
r
if mu is None:
mu = stationary_distribution(T)
smu = np.sqrt(mu)
S = smu[:,None] * T / smu
val, eigvec = eigh(S)
perm = np.argsort(np.abs(val))[::-1]
val = val[perm]
eigvec = eigvec[:, perm]
D = np.diag(val)
R = eigvec / smu[:, np.newaxis]
L = ... | def rdl_decomposition_rev(T, norm='reversible', mu=None) | r"""Decomposition into left and right eigenvectors for reversible
transition matrices.
Parameters
----------
T : (M, M) ndarray
Transition matrix
norm: {'standard', 'reversible'}
standard: (L'R) = Id, L[:,0] is a probability distribution,
the stationary distribution mu o... | 3.595069 | 3.148073 | 1.14199 |
r
values = eigenvalues(T, reversible=reversible, mu=mu)
ind = np.argsort(np.abs(values))[::-1]
values = values[ind]
if k is None:
values = values
else:
values = values[0:k]
return timescales_from_eigenvalues(values, tau) | def timescales(T, tau=1, k=None, reversible=False, mu=None) | r"""Compute implied time scales of given transition matrix
Parameters
----------
T : (M, M) ndarray
Transition matrix
tau : int, optional
lag time
k : int, optional
Number of time scales
reversible : bool, optional
Indicate that transition matirx is reversible
... | 4.474183 | 5.588401 | 0.800619 |
r
if not np.allclose(evals.imag, 0.0):
warnings.warn('Using eigenvalues with non-zero imaginary part', ImaginaryEigenValueWarning)
ind_abs_one = np.isclose(np.abs(evals), 1.0, rtol=0.0, atol=1e-14)
if sum(ind_abs_one) > 1:
warnings.warn('Multiple eigenvalues with magnitude o... | def timescales_from_eigenvalues(evals, tau=1) | r"""Compute implied time scales from given eigenvalues
Parameters
----------
evals : eigenvalues
tau : lag time
Returns
-------
ts : ndarray
The implied time scales to the given eigenvalues, in the same order. | 3.76981 | 3.569578 | 1.056094 |
dirname, basename = os.path.split(filename)
name, ext = os.path.splitext(basename)
matrix_name, matrix_ext = os.path.splitext(name)
if matrix_ext == '.coo':
return True
else:
return False | def is_sparse_file(filename) | Determine if the given filename indicates a dense or a sparse matrix
If pathname is xxx.coo.yyy return True otherwise False. | 2.507518 | 2.326226 | 1.077934 |
coo = np.loadtxt(filename, comments=comments, dtype=dtype)
if len(coo.shape) == 2 and coo.shape[1] == 3:
row = coo[:, 0]
col = coo[:, 1]
values = coo[:, 2]
if np.all(np.isreal(row)) and np.all(np.isreal(col)):
row = row.real
col = col.real
... | def read_matrix_sparse(filename, dtype=float, comments='#') | Check if coo is (M, 3) ndarray | 2.536642 | 2.397968 | 1.05783 |
coo = np.load(filename)
if len(coo.shape) == 2 and coo.shape[1] == 3:
row = coo[:, 0]
col = coo[:, 1]
values = coo[:, 2]
if np.all(np.isreal(row)) and np.all(np.isreal(col)):
row = row.real
col = col.real
if np.all... | def load_matrix_sparse(filename) | Check if coo is (M, 3) ndarray | 2.632171 | 2.446732 | 1.075791 |
r
T = A - mu * eye(A.shape[0], A.shape[0])
T = T.tocsc()
solve = factorized(T)
r0 = 1.0 / np.linalg.norm(x0)
y0 = x0 * r0
y = 1.0 * y0
r = 1.0 * r0
N = 0
for i in range(maxiter):
x = solve(y)
r = 1.0 / np.linalg.norm(x)
y = x * r
if ... | def backward_iteration(A, mu, x0, tol=1e-14, maxiter=100) | r"""Find eigenvector to approximate eigenvalue via backward iteration.
Parameters
----------
A : (N, N) scipy.sparse matrix
Matrix for which eigenvector is desired
mu : float
Approximate eigenvalue for desired eigenvector
x0 : (N, ) ndarray
Initial guess for eigenvector
... | 3.399256 | 3.801233 | 0.894251 |
r
A = P.transpose()
mu = 1.0 - eps
x0 = np.ones(P.shape[0])
y = backward_iteration(A, mu, x0)
pi = y / y.sum()
return pi | def stationary_distribution_from_backward_iteration(P, eps=1e-15) | r"""Fast computation of the stationary vector using backward
iteration.
Parameters
----------
P : (M, M) scipy.sparse matrix
Transition matrix
eps : float (optional)
Perturbation parameter for the true eigenvalue.
Returns
-------
pi : (M,) ndarray
Stationary vec... | 5.790984 | 6.828951 | 0.848005 |
r
vals, vecs = scipy.sparse.linalg.eigs(T.transpose(), k=1, which='LR', ncv=ncv)
nu = vecs[:, 0].real
mu = nu / np.sum(nu)
return mu | def stationary_distribution_from_eigenvector(T, ncv=None) | r"""Compute stationary distribution of stochastic matrix T.
The stationary distribution is the left eigenvector corresponding to the 1
non-degenerate eigenvalue :math: `\lambda=1`.
Input:
------
T : numpy array, shape(d,d)
Transition matrix (stochastic matrix).
ncv : int (optional)
... | 4.49971 | 5.141041 | 0.875253 |
r
fallback = False
try:
mu = stationary_distribution_from_backward_iteration(T)
if np.any(mu < 0): # numerical problem, fall back to more robust algorithm.
fallback=True
except RuntimeError:
fallback = True
if fallback:
mu = stationary_distribution_from_... | def stationary_distribution(T) | r"""Compute stationary distribution of stochastic matrix T.
Chooses the fastest applicable algorithm automatically
Input:
------
T : numpy array, shape(d,d)
Transition matrix (stochastic matrix).
Returns
-------
mu : numpy array, shape(d,)
Vector of stationary probabilitie... | 5.825189 | 6.072559 | 0.959264 |
r
if k is None:
raise ValueError("Number of eigenvalues required for decomposition of sparse matrix")
else:
if reversible:
try:
v = eigenvalues_rev(T, k, ncv=ncv, mu=mu)
except: # use fallback code, but cast to real
v = scipy.sparse.li... | def eigenvalues(T, k=None, ncv=None, reversible=False, mu=None) | r"""Compute the eigenvalues of a sparse transition matrix.
Parameters
----------
T : (M, M) scipy.sparse matrix
Transition matrix
k : int, optional
Number of eigenvalues to compute.
ncv : int, optional
The number of Lanczos vectors generated, `ncv` must be greater than k;
... | 3.042795 | 3.087786 | 0.985429 |
r
if mu is None:
mu = stationary_distribution(T)
if np.any(mu <= 0):
raise ValueError('Cannot symmetrize transition matrix')
smu = np.sqrt(mu)
D = diags(smu, 0)
Dinv = diags(1.0/smu, 0)
S = (D.dot(T)).dot(Dinv)
evals = scipy.sparse.linalg.eigsh(S, k=k, ncv... | def eigenvalues_rev(T, k, ncv=None, mu=None) | r"""Compute the eigenvalues of a reversible, sparse transition matrix.
Parameters
----------
T : (M, M) scipy.sparse matrix
Transition matrix
k : int
Number of eigenvalues to compute.
ncv : int, optional
The number of Lanczos vectors generated, `ncv` must be greater than k;
... | 3.43337 | 3.125205 | 1.098606 |
r
if k is None:
raise ValueError("Number of eigenvectors required for decomposition of sparse matrix")
else:
if reversible:
eigvec = eigenvectors_rev(T, k, right=right, ncv=ncv, mu=mu)
return eigvec
else:
eigvec = eigenvectors_nrev(T, k, right=righ... | def eigenvectors(T, k=None, right=True, ncv=None, reversible=False, mu=None) | r"""Compute eigenvectors of given transition matrix.
Parameters
----------
T : scipy.sparse matrix
Transition matrix (stochastic matrix).
k : int (optional) or array-like
For integer k compute the first k eigenvalues of T
else return those eigenvector sepcified by integer indice... | 3.093541 | 3.512069 | 0.880832 |
r
if right:
val, vecs = scipy.sparse.linalg.eigs(T, k=k, which='LM', ncv=ncv)
ind = np.argsort(np.abs(val))[::-1]
return vecs[:, ind]
else:
val, vecs = scipy.sparse.linalg.eigs(T.transpose(), k=k, which='LM', ncv=ncv)
ind = np.argsort(np.abs(val))[::-1]
return... | def eigenvectors_nrev(T, k, right=True, ncv=None) | r"""Compute eigenvectors of transition matrix.
Parameters
----------
T : (M, M) scipy.sparse matrix
Transition matrix (stochastic matrix)
k : int
Number of eigenvalues to compute
right : bool, optional
If True compute right eigenvectors, left eigenvectors otherwise
ncv :... | 2.000008 | 1.973079 | 1.013648 |
r
if mu is None:
mu = stationary_distribution(T)
smu = np.sqrt(mu)
D = diags(smu, 0)
Dinv = diags(1.0/smu, 0)
S = (D.dot(T)).dot(Dinv)
val, eigvec = scipy.sparse.linalg.eigsh(S, k=k, ncv=ncv, which='LM',
return_eigenvectors=True)
... | def eigenvectors_rev(T, k, right=True, ncv=None, mu=None) | r"""Compute eigenvectors of reversible transition matrix.
Parameters
----------
T : (M, M) scipy.sparse matrix
Transition matrix (stochastic matrix)
k : int
Number of eigenvalues to compute
right : bool, optional
If True compute right eigenvectors, left eigenvectors otherwis... | 2.854552 | 2.93002 | 0.974243 |
r
if k is None:
raise ValueError("Number of eigenvectors required for decomposition of sparse matrix")
# auto-set norm
if norm == 'auto':
if is_reversible(T):
norm = 'reversible'
else:
norm = 'standard'
if reversible:
return rdl_decomposition_r... | def rdl_decomposition(T, k=None, norm='auto', ncv=None, reversible=False, mu=None) | r"""Compute the decomposition into left and right eigenvectors.
Parameters
----------
T : sparse matrix
Transition matrix
k : int (optional)
Number of eigenvector/eigenvalue pairs
norm: {'standard', 'reversible', 'auto'}
standard: (L'R) = Id, L[:,0] is a probability distribu... | 3.441201 | 3.249349 | 1.059043 |
r
# Standard norm: Euclidean norm is 1 for r and LR = I.
if norm == 'standard':
v, R = scipy.sparse.linalg.eigs(T, k=k, which='LM', ncv=ncv)
r, L = scipy.sparse.linalg.eigs(T.transpose(), k=k, which='LM', ncv=ncv)
ind = np.argsort(np.abs(v))[::-1]
v = v[ind]
... | def rdl_decomposition_nrev(T, k, norm='standard', ncv=None) | r"""Compute the decomposition into left and right eigenvectors.
Parameters
----------
T : sparse matrix
Transition matrix
k : int
Number of eigenvector/eigenvalue pairs
norm: {'standard', 'reversible'}
standard: (L'R) = Id, L[:,0] is a probability distribution,
t... | 2.577797 | 2.462859 | 1.046668 |
r
if mu is None:
mu = stationary_distribution(T)
smu = np.sqrt(mu)
Dpi = diags(smu, 0)
Dinv = diags(1.0/smu, 0)
S = (Dpi.dot(T)).dot(Dinv)
val, eigvec = scipy.sparse.linalg.eigsh(S, k=k, ncv=ncv, which='LM',
return_eigenvectors=Tr... | def rdl_decomposition_rev(T, k, norm='reversible', ncv=None, mu=None) | r"""Compute the decomposition into left and right eigenvectors.
Parameters
----------
T : sparse matrix
Transition matrix
k : int
Number of eigenvector/eigenvalue pairs
norm: {'standard', 'reversible'}
standard: (L'R) = Id, L[:,0] is a probability distribution,
t... | 3.221138 | 2.926535 | 1.100666 |
r
if k is None:
raise ValueError("Number of time scales required for decomposition of sparse matrix")
values = eigenvalues(T, k=k, ncv=ncv, reversible=reversible)
if not np.allclose(values.imag, 0.0):
warnings.warn('Using eigenvalues with non-zero imaginary part '
... | def timescales(T, tau=1, k=None, ncv=None, reversible=False, mu=None) | r"""Compute implied time scales of given transition matrix
Parameters
----------
T : transition matrix
tau : lag time
k : int (optional)
Compute the first k implied time scales.
ncv : int (optional)
The number of Lanczos vectors generated, `ncv` must be greater than k;
i... | 4.595506 | 4.365428 | 1.052705 |
r
# determine number of states n
nmax = 0
for dtraj in dtrajs:
nmax = max(nmax, np.max(dtraj))
# return number of states
return nmax + 1 | def number_of_states(dtrajs) | r"""
Determine the number of states from a set of discrete trajectories
Parameters
----------
dtrajs : list of int-arrays
discrete trajectories | 4.365422 | 3.991948 | 1.093557 |
r
if (isinstance(dtrajs[0], (int))):
return len(dtrajs) * np.ones((1))
lengths = np.zeros((len(dtrajs)))
for i in range(len(dtrajs)):
lengths[i] = len(dtrajs[i])
return lengths | def determine_lengths(dtrajs) | r"""
Determines the lengths of all trajectories
Parameters
----------
dtrajs : list of int-arrays
discrete trajectories | 2.88384 | 3.026383 | 0.9529 |
from scipy.stats import rv_discrete
# if we have just one trajectory, put it into a one-element list:
if (isinstance(trajs[0], (int, int, float))):
trajs = [trajs]
ntraj = len(trajs)
# determine correlation length to be used
lengths = determine_lengths(trajs)
Ltot = np.sum(leng... | def bootstrap_trajectories(trajs, correlation_length) | Generates a randomly resampled count matrix given the input coordinates.
See API function for full documentation. | 3.250844 | 3.262484 | 0.996432 |
# check if length is sufficient
L = len(dtraj)
if (lagtime > L):
raise ValueError(
'Cannot sample counts with lagtime ' + str(lagtime) + ' from a trajectory with length ' + str(L))
# sample
I = np.random.randint(0, L - lagtime - 1, size=n)
J = I + lagtime
# return s... | def bootstrap_counts_singletraj(dtraj, lagtime, n) | Samples n counts at the given lagtime from the given trajectory | 3.740726 | 3.719793 | 1.005627 |
from scipy.stats import rv_discrete
# if we have just one trajectory, put it into a one-element list:
if (isinstance(dtrajs[0], six.integer_types)):
dtrajs = [dtrajs]
ntraj = len(dtrajs)
# can we do the estimate?
lengths = determine_lengths(dtrajs)
Lmax = np.max(lengths)
Lt... | def bootstrap_counts(dtrajs, lagtime, corrlength=None) | Generates a randomly resampled count matrix given the input coordinates.
See API function for full documentation. | 3.131323 | 3.115042 | 1.005226 |
r
M = C.shape[0]
nc, indices = csgraph.connected_components(C, directed=directed, connection='strong')
states = np.arange(M) # Discrete states
ind = np.argsort(indices)
indices = indices[ind]
states = states[ind]
count = np.bincount(indices)
csum =... | def connected_sets(C, directed=True) | r"""Compute connected components for a directed graph with weights
represented by the given count matrix.
Parameters
----------
C : scipy.sparse matrix or numpy ndarray
square matrix specifying edge weights.
directed : bool, optional
Whether to compute connected components for a dire... | 4.160257 | 3.93507 | 1.057226 |
r
if lcc is None:
lcc = largest_connected_set(C, directed=directed)
if scipy.sparse.issparse(C):
C_cc = C.tocsr()
else:
C_cc = C
C_cc = C_cc[lcc, :]
if scipy.sparse.issparse(C):
C_cc = C_cc.tocsc()
C_cc = C_cc[:, lcc]
if scipy.sparse.issparse(... | def largest_connected_submatrix(C, directed=True, lcc=None) | r"""Compute the count matrix of the largest connected set.
The input count matrix is used as a weight matrix for the
construction of a directed graph. The largest connected set of the
constructed graph is computed. Vertices belonging to the largest
connected component are used to generate a completely ... | 2.431534 | 2.493414 | 0.975182 |
r
nc = csgraph.connected_components(C, directed=directed, connection='strong', \
return_labels=False)
return nc == 1 | def is_connected(C, directed=True) | r"""Return true, if the input count matrix is completely connected.
Effectively checking if the number of connected components equals one.
Parameters
----------
C : scipy.sparse matrix or numpy ndarray
Count matrix specifying edge weights.
directed : bool, optional
Whether to compute... | 7.878612 | 9.277285 | 0.849237 |
r
import msmtools.analysis as msmana
if len(A) == 0 or len(B) == 0:
raise ValueError('set A or B is empty')
n = T.shape[0]
if len(A) > n or len(B) > n or max(A) > n or max(B) > n:
raise ValueError('set A or B defines more states, than given transition matrix.')
if (rate_matrix i... | def tpt(T, A, B, mu=None, qminus=None, qplus=None, rate_matrix=False) | r""" Computes the A->B reactive flux using transition path theory (TPT)
Parameters
----------
T : (M, M) ndarray or scipy.sparse matrix
Transition matrix (default) or Rate matrix (if rate_matrix=True)
A : array_like
List of integer state labels for set A
B : array_like
List ... | 4.129403 | 3.497952 | 1.18052 |
r
if issparse(T):
return sparse.tpt.flux_matrix(T, pi, qminus, qplus, netflux=netflux)
elif isdense(T):
return dense.tpt.flux_matrix(T, pi, qminus, qplus, netflux=netflux)
else:
raise _type_not_supported | def flux_matrix(T, pi, qminus, qplus, netflux=True) | r"""Compute the TPT flux network for the reaction A-->B.
Parameters
----------
T : (M, M) ndarray
transition matrix
pi : (M,) ndarray
Stationary distribution corresponding to T
qminus : (M,) ndarray
Backward comittor
qplus : (M,) ndarray
Forward committor
net... | 3.273589 | 3.937279 | 0.831434 |
r
if issparse(flux):
return sparse.tpt.to_netflux(flux)
elif isdense(flux):
return dense.tpt.to_netflux(flux)
else:
raise _type_not_supported | def to_netflux(flux) | r"""Compute the netflux from the gross flux.
Parameters
----------
flux : (M, M) ndarray
Matrix of flux values between pairs of states.
Returns
-------
netflux : (M, M) ndarray
Matrix of netflux values between pairs of states.
Notes
-----
The netflux or effective c... | 6.06361 | 9.593616 | 0.632046 |
r
if issparse(F):
return sparse.tpt.coarsegrain(F, sets)
elif isdense(F):
return dense.tpt.coarsegrain(F, sets)
else:
raise _type_not_supported | def coarsegrain(F, sets) | r"""Coarse-grains the flux to the given sets.
Parameters
----------
F : (n, n) ndarray or scipy.sparse matrix
Matrix of flux values between pairs of states.
sets : list of array-like of ints
The sets of states onto which the flux is coarse-grained.
Notes
-----
The coarse gr... | 5.010559 | 7.937899 | 0.63122 |
r
if issparse(F):
return sparse.tpt.total_flux(F, A=A)
elif isdense(F):
return dense.tpt.total_flux(F, A=A)
else:
raise _type_not_supported | def total_flux(F, A=None) | r"""Compute the total flux, or turnover flux, that is produced by
the flux sources and consumed by the flux sinks.
Parameters
----------
F : (M, M) ndarray
Matrix of flux values between pairs of states.
A : array_like (optional)
List of integer state labels for set A (reactant)
... | 4.96113 | 7.259656 | 0.683384 |
r
return dense.tpt.rate(totflux, pi, qminus) | def rate(totflux, pi, qminus) | r"""Transition rate for reaction A to B.
Parameters
----------
totflux : float
The total flux between reactant and product
pi : (M,) ndarray
Stationary distribution
qminus : (M,) ndarray
Backward comittor
Returns
-------
kAB : float
The reaction rate (pe... | 24.074406 | 37.820053 | 0.636551 |
r
return dense.tpt.mfpt(totflux, pi, qminus) | def mfpt(totflux, pi, qminus) | r"""Mean first passage time for reaction A to B.
Parameters
----------
totflux : float
The total flux between reactant and product
pi : (M,) ndarray
Stationary distribution
qminus : (M,) ndarray
Backward comittor
Returns
-------
tAB : float
The mean firs... | 20.443674 | 34.835407 | 0.586865 |
r
if issparse(F):
return sparse.pathways.pathways(F, A, B, fraction=fraction, maxiter=maxiter)
elif isdense(F):
return sparse.pathways.pathways(csr_matrix(F), A, B, fraction=fraction, maxiter=maxiter)
else:
raise _type_not_supported | def pathways(F, A, B, fraction=1.0, maxiter=1000) | r"""Decompose flux network into dominant reaction paths.
Parameters
----------
F : (M, M) scipy.sparse matrix
The flux network (matrix of netflux values)
A : array_like
The set of starting states
B : array_like
The set of end states
fraction : float, optional
Fra... | 3.0342 | 4.528042 | 0.670091 |
(n, m) = evec.shape
# do we have enough eigenvectors?
if n_clusters > m:
raise ValueError("Cannot cluster the (" + str(n) + " x " + str(m)
+ " eigenvector matrix to " + str(n_clusters) + " clusters.")
# check if the first, and only the first eigenvector is constan... | def _pcca_connected_isa(evec, n_clusters) | PCCA+ spectral clustering method using the inner simplex algorithm.
Clusters the first n_cluster eigenvectors of a transition matrix in order to cluster the states.
This function assumes that the state space is fully connected, i.e. the transition matrix whose
eigenvectors are used is supposed to have only... | 3.652354 | 3.473856 | 1.051383 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.