code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if self.verbose:
self.selftest()
self.count = 0
if self.verbose:
logging.info('initial value of the objective function is %f'
% self.function(self.initial))
theta0 = self.initial
theta, f, d = fmin_l_bfgs_b(self.function_a... | def run(self) | Run the minimization.
Returns
-------
K : (N,N) ndarray
the optimal rate matrix | 3.483378 | 3.323577 | 1.048081 |
ns = []
if os.path.exists(resolv):
for l in open(resolv):
if l.startswith("nameserver"):
address = l.strip().split(" ", 2)[1]
# forwarding to ourselves would be bad
if not address.startswith("127"):
ns.append(address)
... | def get_forwarders(resolv="resolv.conf") | Find the forwarders in /etc/resolv.conf, default to 8.8.8.8 and
8.8.4.4 | 3.048481 | 2.913017 | 1.046503 |
try:
return _format_code(source, preferred_quote)
except (tokenize.TokenError, IndentationError):
return source | def format_code(source, preferred_quote="'") | Return source code with quotes unified. | 3.629407 | 3.449563 | 1.052135 |
if not source:
return source
modified_tokens = []
sio = io.StringIO(source)
for (token_type,
token_string,
start,
end,
line) in tokenize.generate_tokens(sio.readline):
if token_type == tokenize.STRING:
token_string = unify_quotes(to... | def _format_code(source, preferred_quote) | Return source code with quotes unified. | 2.675829 | 2.42518 | 1.103353 |
bad_quote = {'"': "'",
"'": '"'}[preferred_quote]
allowed_starts = {
'': bad_quote,
'f': 'f' + bad_quote,
'b': 'b' + bad_quote
}
if not any(token_string.startswith(start)
for start in allowed_starts.values()):
return token_string
... | def unify_quotes(token_string, preferred_quote) | Return string with quotes changed to preferred_quote if possible. | 2.778804 | 2.733468 | 1.016586 |
return io.open(filename, mode=mode, encoding=encoding,
newline='') | def open_with_encoding(filename, encoding, mode='r') | Return opened file with a specific encoding. | 4.999156 | 4.459848 | 1.120925 |
try:
with open(filename, 'rb') as input_file:
from lib2to3.pgen2 import tokenize as lib2to3_tokenize
encoding = lib2to3_tokenize.detect_encoding(input_file.readline)[0]
# Check for correctness of encoding.
with open_with_encoding(filename, encoding) as i... | def detect_encoding(filename) | Return file encoding. | 3.017042 | 2.900027 | 1.040349 |
encoding = detect_encoding(filename)
with open_with_encoding(filename, encoding=encoding) as input_file:
source = input_file.read()
formatted_source = format_code(
source,
preferred_quote=args.quote)
if source != formatted_source:
if args.in_place:
... | def format_file(filename, args, standard_out) | Run format_code() on a file.
Returns `True` if any changes are needed and they are not being done
in-place. | 2.618653 | 2.532323 | 1.034091 |
import argparse
parser = argparse.ArgumentParser(description=__doc__, prog='unify')
parser.add_argument('-i', '--in-place', action='store_true',
help='make changes to files instead of printing diffs')
parser.add_argument('-c', '--check-only', action='store_true',
... | def _main(argv, standard_out, standard_error) | Run quotes unifying on files.
Returns `1` if any quoting changes are still needed, otherwise
`None`. | 2.491865 | 2.403811 | 1.036631 |
# Exit on broken pipe.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except AttributeError:
# SIGPIPE is not available on Windows.
pass
try:
return _main(sys.argv,
standard_out=sys.stdout,
standard_error=sys.stderr)
except Ke... | def main(): # pragma: no cover
try | Main entry point. | 3.696543 | 3.454618 | 1.07003 |
r
# convert dtraj input, if it contains out of nested python lists to
# a list of int ndarrays.
dtraj = _ensure_dtraj_list(dtraj)
return sparse.count_matrix.count_matrix_coo2_mult(dtraj, lag, sliding=sliding,
sparse=sparse_return, nstates=nstates... | def count_matrix(dtraj, lag, sliding=True, sparse_return=True, nstates=None) | r"""Generate a count matrix from given microstate trajectory.
Parameters
----------
dtraj : array_like or list of array_like
Discretized trajectory or list of discretized trajectories
lag : int
Lagtime in trajectory steps
sliding : bool, optional
If true the sliding window a... | 10.223322 | 15.916817 | 0.642297 |
r
dtrajs = _ensure_dtraj_list(dtrajs)
import os
# enforce one job on windows.
if os.name == 'nt':
n_jobs = 1
return sparse.effective_counts.effective_count_matrix(dtrajs, lag, average=average, mact=mact, n_jobs=n_jobs, callback=callback) | def effective_count_matrix(dtrajs, lag, average='row', mact=1.0, n_jobs=1, callback=None) | r""" Computes the statistically effective transition count matrix
Given a list of discrete trajectories, compute the effective number of statistically uncorrelated transition
counts at the given lag time. First computes the full sliding-window counts :math:`c_{ij}(tau)`. Then uses
:func:`statistical_ineffi... | 4.06014 | 5.556244 | 0.730735 |
r
dtrajs = _ensure_dtraj_list(dtrajs)
return dense.bootstrapping.bootstrap_counts(dtrajs, lagtime, corrlength=corrlength) | def bootstrap_counts(dtrajs, lagtime, corrlength=None) | r"""Generates a randomly resampled count matrix given the input coordinates.
Parameters
----------
dtrajs : array-like or array-like of array-like
single or multiple discrete trajectories. Every trajectory is assumed to be
a statistically independent realization. Note that this is often not... | 5.123061 | 8.773634 | 0.583916 |
r
if isdense(C):
return sparse.connectivity.connected_sets(csr_matrix(C), directed=directed)
else:
return sparse.connectivity.connected_sets(C, directed=directed) | def connected_sets(C, directed=True) | r"""Compute connected sets of microstates.
Connected components for a directed graph with edge-weights
given by the count matrix.
Parameters
----------
C : scipy.sparse matrix
Count matrix specifying edge weights.
directed : bool, optional
Whether to compute connected components... | 4.62782 | 6.947011 | 0.66616 |
r
if isdense(C):
return sparse.connectivity.largest_connected_set(csr_matrix(C), directed=directed)
else:
return sparse.connectivity.largest_connected_set(C, directed=directed) | def largest_connected_set(C, directed=True) | r"""Largest connected component for a directed graph with edge-weights
given by the count matrix.
Parameters
----------
C : scipy.sparse matrix
Count matrix specifying edge weights.
directed : bool, optional
Whether to compute connected components for a directed or
undirected... | 4.031981 | 6.066838 | 0.664593 |
r
if isdense(C):
return sparse.connectivity.largest_connected_submatrix(csr_matrix(C), directed=directed, lcc=lcc).toarray()
else:
return sparse.connectivity.largest_connected_submatrix(C, directed=directed, lcc=lcc) | def largest_connected_submatrix(C, directed=True, lcc=None) | r"""Compute the count matrix on the largest connected set.
Parameters
----------
C : scipy.sparse matrix
Count matrix specifying edge weights.
directed : bool, optional
Whether to compute connected components for a directed or
undirected graph. Default is True
lcc : (M,) ndarr... | 3.118714 | 4.835079 | 0.645018 |
if isdense(C):
return sparse.connectivity.is_connected(csr_matrix(C), directed=directed)
else:
return sparse.connectivity.is_connected(C, directed=directed) | def is_connected(C, directed=True) | Check connectivity of the given matrix.
Parameters
----------
C : scipy.sparse matrix
Count matrix specifying edge weights.
directed : bool, optional
Whether to compute connected components for a directed or
undirected graph. Default is True.
Returns
-------
is_connec... | 3.22232 | 5.583847 | 0.577079 |
r
if isdense(C):
B = sparse.prior.prior_neighbor(csr_matrix(C), alpha=alpha)
return B.toarray()
else:
return sparse.prior.prior_neighbor(C, alpha=alpha) | def prior_neighbor(C, alpha=0.001) | r"""Neighbor prior for the given count matrix.
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
alpha : float (optional)
Value of prior counts
Returns
-------
B : (M, M) ndarray or scipy.sparse matrix
Prior count matrix
Notes
---... | 4.882272 | 7.205428 | 0.677583 |
r
if isdense(C):
return sparse.prior.prior_const(C, alpha=alpha)
else:
warnings.warn("Prior will be a dense matrix for sparse input")
return sparse.prior.prior_const(C, alpha=alpha) | def prior_const(C, alpha=0.001) | r"""Constant prior for given count matrix.
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 matrix
Notes
-----
The prior is defined... | 5.220057 | 8.246716 | 0.632986 |
r
if isdense(C):
return sparse.prior.prior_rev(C, alpha=alpha)
else:
warnings.warn("Prior will be a dense matrix for sparse input")
return sparse.prior.prior_rev(C, alpha=alpha) | 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
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
alpha : float (optional)
Value of prior counts
Returns
---... | 5.075945 | 8.771065 | 0.578715 |
r
if issparse(C) and issparse(T):
return sparse.likelihood.log_likelihood(C, T)
else:
# use the dense likelihood calculator for all other cases
# if a mix of dense/sparse C/T matrices is used, then both
# will be converted to ndarrays.
if not isinstance(C, np.ndarray)... | def log_likelihood(C, T) | r"""Log-likelihood of the count matrix given a transition matrix.
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
T : (M, M) ndarray orscipy.sparse matrix
Transition matrix
Returns
-------
logL : float
Log-likelihood of the count matrix
... | 5.001983 | 6.094659 | 0.820716 |
r
if issparse(C):
warnings.warn("Covariance matrix will be dense for sparse input")
C = C.toarray()
return dense.covariance.tmatrix_cov(C, row=k) | def tmatrix_cov(C, k=None) | r"""Covariance tensor for non-reversible transition matrix posterior.
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
k : int (optional)
Return only covariance matrix for entires in the k-th row of
the transition matrix
Returns
-------
c... | 8.558445 | 13.472564 | 0.63525 |
r
if issparse(C):
warnings.warn("Error-perturbation will be dense for sparse input")
C = C.toarray()
return dense.covariance.error_perturbation(C, S) | def error_perturbation(C, S) | r"""Error perturbation for given sensitivity matrix.
Parameters
----------
C : (M, M) ndarray
Count matrix
S : (M, M) ndarray or (K, M, M) ndarray
Sensitivity matrix (for scalar observable) or sensitivity
tensor for vector observable
Returns
-------
X : float or (K,... | 7.551651 | 13.549514 | 0.557337 |
r
if issparse(C):
_showSparseConversionWarning()
C = C.toarray()
sampler = tmatrix_sampler(C, reversible=reversible, mu=mu, T0=T0, nsteps=nsteps)
return sampler.sample(nsamples=nsample, return_statdist=return_statdist) | def sample_tmatrix(C, nsample=1, nsteps=None, reversible=False, mu=None, T0=None, return_statdist=False) | r"""samples transition matrices from the posterior distribution
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
nsample : int
number of samples to be drawn
nstep : int, default=None
number of full Gibbs sampling sweeps internally done for each sa... | 4.096221 | 5.302299 | 0.772537 |
r
if issparse(C):
_showSparseConversionWarning()
C = C.toarray()
from .dense.tmatrix_sampler import TransitionMatrixSampler
sampler = TransitionMatrixSampler(C, reversible=reversible, mu=mu, P0=T0,
nsteps=nsteps, prior=prior)
return sampler | def tmatrix_sampler(C, reversible=False, mu=None, T0=None, nsteps=None, prior='sparse') | r"""Generate transition matrix sampler object.
Parameters
----------
C : (M, M) ndarray or scipy.sparse matrix
Count matrix
reversible : bool
If true sample from the ensemble of transition matrices
restricted to those obeying a detailed balance condition,
else draw from ... | 5.363599 | 6.686013 | 0.802212 |
if hasattr(target, "__len__"):
target = np.array(target)
else:
target = np.array([target])
# target size
n = np.shape(P)[0]
# nontarget
nontarget = np.array(list(set(range(n)) - set(target)), dtype=int)
# stable states
stable = np.where(np.isclose(np.diag(P), 1) == T... | def hitting_probability(P, target) | Computes the hitting probabilities for all states to the target states.
The hitting probability of state i to set A is defined as the minimal,
non-negative solution of:
.. math::
h_i^A &= 1 \:\:\:\: i\in A \\
h_i^A &= \sum_j p_{ij} h_i^A \:\:\:\: i \notin A
Retur... | 3.655587 | 3.614284 | 1.011428 |
r
A = A.tocoo()
data = A.data
row = A.row
col = A.col
pos = data > 0.0
datap = data[pos]
rowp = row[pos]
colp = col[pos]
Aplus = coo_matrix((datap, (rowp, colp)), shape=A.shape)
return Aplus | def remove_negative_entries(A) | r"""Remove all negative entries from sparse matrix.
Aplus=max(0, A)
Parameters
----------
A : (M, M) scipy.sparse matrix
Input matrix
Returns
-------
Aplus : (M, M) scipy.sparse matrix
Input matrix with negative entries set to zero. | 3.134978 | 3.559789 | 0.880664 |
r
D1 = diags((pi * qminus,), (0,))
D2 = diags((qplus,), (0,))
flux = D1.dot(T.dot(D2))
flux = flux - diags(flux.diagonal(), 0)
if netflux:
return to_netflux(flux)
else:
return flux | def flux_matrix(T, pi, qminus, qplus, netflux=True) | r"""Compute the flux.
Parameters
----------
T : (M, M) scipy.sparse matrix
Transition matrix
pi : (M,) ndarray
Stationary distribution corresponding to T
qminus : (M,) ndarray
Backward comittor
qplus : (M,) ndarray
Forward committor
netflux : boolean
... | 4.994699 | 6.452144 | 0.774115 |
r
netflux = flux - flux.T
netflux = remove_negative_entries(netflux)
return netflux | def to_netflux(flux) | r"""Compute the netflux.
f_ij^{+}=max{0, f_ij-f_ji}
for all pairs i,j
Parameters
----------
flux : (M, M) scipy.sparse matrix
Matrix of flux values between pairs of states.
Returns
-------
netflux : (M, M) scipy.sparse matrix
Matrix of netflux values between pairs of s... | 14.500424 | 16.268442 | 0.891322 |
r
nnew = len(sets)
Fin = F.tocsr()
Fc = csr_matrix((nnew, nnew))
for i in range(0, nnew - 1):
for j in range(i, nnew):
I = list(sets[i])
J = list(sets[j])
Fc[i, j] = (Fin[I, :][:, J]).sum()
Fc[j, i] = (Fin[J, :][:, I]).sum()
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.82244 | 3.030382 | 0.931381 |
r
X = set(np.arange(flux.shape[0])) # total state space
A = set(A)
notA = X.difference(A)
W = flux.tocsr()
W = W[list(A), :]
W = W.tocsc()
W = W[:, list(notA)]
F = W.sum()
return F | def total_flux(flux, A) | r"""Compute the total flux between reactant and product.
Parameters
----------
flux : (M, M) scipy.sparse matrix
Matrix of flux values between pairs of states.
A : array_like
List of integer state labels for set A (reactant)
Returns
-------
F : float
The total flux ... | 6.498934 | 6.456152 | 1.006627 |
n = len(T)
set_X = numpy.arange(n) # set(range(n))
set_A = numpy.unique(A) # set(A)
set_B = numpy.unique(B) # set(B)
set_AB = numpy.union1d(set_A, set_B) # set_A | set_B
notAB = numpy.setdiff1d(set_X, set_AB, True) # list(set_X - set_AB)
m = len(notAB)
K = T - numpy.diag(nump... | def forward_committor_sensitivity(T, A, B, index) | calculate the sensitivity matrix for index of the forward committor from A to B given transition matrix T.
Parameters
----------
T : numpy.ndarray shape = (n, n)
Transition matrix
A : array like
List of integer state labels for set A
B : array like
List of integer state label... | 3.444638 | 3.3596 | 1.025312 |
# This is really ugly to compute. The problem is, that changes in T induce changes in
# the stationary distribution and so we need to add this influence, too
# I implemented something which is correct, but don't ask me about the derivation
n = len(T)
trT = numpy.transpose(T)
one = numpy... | def backward_committor_sensitivity(T, A, B, index) | calculate the sensitivity matrix for index of the backward committor from A to B given transition matrix T.
Parameters
----------
T : numpy.ndarray shape = (n, n)
Transition matrix
A : array like
List of integer state labels for set A
B : array like
List of integer state labe... | 4.262679 | 4.314363 | 0.98802 |
eValues, rightEigenvectors = numpy.linalg.eig(T)
leftEigenvectors = numpy.linalg.inv(rightEigenvectors)
perm = numpy.argsort(eValues)[::-1]
rightEigenvectors = rightEigenvectors[:, perm]
leftEigenvectors = leftEigenvectors[perm]
sensitivity = numpy.outer(leftEigenvectors[k], rightEigenv... | def eigenvalue_sensitivity(T, k) | calculate the sensitivity matrix for eigenvalue k given transition matrix T.
Parameters
----------
T : numpy.ndarray shape = (n, n)
Transition matrix
k : int
eigenvalue index for eigenvalues order descending
Returns
-------
x : ndarray, shape=(n, n)
Sensitivity matri... | 2.618073 | 2.419662 | 1.082 |
eValues, rightEigenvectors = numpy.linalg.eig(T)
leftEigenvectors = numpy.linalg.inv(rightEigenvectors)
perm = numpy.argsort(eValues)[::-1]
eValues = eValues[perm]
rightEigenvectors = rightEigenvectors[:, perm]
leftEigenvectors = leftEigenvectors[perm]
eVal = eValues[k]
sensiti... | def timescale_sensitivity(T, k) | calculate the sensitivity matrix for timescale k given transition matrix T.
Parameters
----------
T : numpy.ndarray shape = (n, n)
Transition matrix
k : int
timescale index for timescales of descending order (k = 0 for the infinite one)
Returns
-------
x : ndarray, shape=(n,... | 2.615217 | 2.482345 | 1.053527 |
n = len(T)
if not right:
T = numpy.transpose(T)
eValues, rightEigenvectors = numpy.linalg.eig(T)
leftEigenvectors = numpy.linalg.inv(rightEigenvectors)
perm = numpy.argsort(eValues)[::-1]
eValues = eValues[perm]
rightEigenvectors = rightEigenvectors[:, perm]
leftEigenvec... | def eigenvector_sensitivity(T, k, j, right=True) | calculate the sensitivity matrix for entry j of left or right eigenvector k given transition matrix T.
Parameters
----------
T : numpy.ndarray shape = (n, n)
Transition matrix
k : int
eigenvector index ordered with descending eigenvalues
j : int
entry of eigenvector k for whi... | 3.103235 | 3.20686 | 0.967687 |
r
n = len(T)
lEV = numpy.ones(n)
rEV = stationary_distribution(T)
eVal = 1.0
T = numpy.transpose(T)
vecA = numpy.zeros(n)
vecA[j] = 1.0
matA = T - eVal * numpy.identity(n)
# normalize s.t. sum is one using rEV which is constant
matA = numpy.concatenate((matA, [lEV]))
... | def stationary_distribution_sensitivity(T, j) | r"""Calculate the sensitivity matrix for entry j the stationary
distribution vector given transition matrix T.
Parameters
----------
T : numpy.ndarray shape = (n, n)
Transition matrix
j : int
entry of stationary distribution for which the sensitivity is to be computed
Returns
... | 5.390395 | 5.495288 | 0.980912 |
n = len(T)
matA = T - numpy.diag(numpy.ones((n)))
matA[target] *= 0
matA[target, target] = 1.0
tVec = -1. * numpy.ones(n)
tVec[target] = 0
mfpt = numpy.linalg.solve(matA, tVec)
aVec = numpy.zeros(n)
aVec[j] = 1.0
phiVec = numpy.linalg.solve(numpy.transpose(matA), aVec)
... | def mfpt_sensitivity(T, target, j) | calculate the sensitivity matrix for entry j of the mean first passage time (MFPT) given transition matrix T.
Parameters
----------
T : numpy.ndarray shape = (n, n)
Transition matrix
target : int
target state to which the MFPT is computed
j : int
entry of the mfpt vector for ... | 3.636239 | 3.715409 | 0.978691 |
r
M = T.shape[0]
S = numpy.zeros((M, M))
for i in range(M):
S += a[i] * stationary_distribution_sensitivity(T, i)
return S | def expectation_sensitivity(T, a) | r"""Sensitivity of expectation value of observable A=(a_i).
Parameters
----------
T : (M, M) ndarray
Transition matrix
a : (M,) ndarray
Observable, a[i] is the value of the observable at state i.
Returns
-------
S : (M, M) ndarray
Sensitivity matrix of the expectati... | 4.767858 | 5.064287 | 0.941467 |
r
M = T.shape[0]
if n <= M:
return ec_matrix_vector(p0, T, n)
else:
return ec_geometric_series(p0, T, n) | def expected_counts(p0, T, n) | r"""Compute expected transition counts for Markov chain after n steps.
Expected counts are computed according to ..math::
E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^T T^{k})_{i} p_{ij}
For N<=M, the sum is computed via successive summation of the
following matrix vector products, p_1^t=p_0^t
T,...,p_n... | 6.51545 | 4.71644 | 1.381434 |
r
if n <= 0:
EC = np.zeros(T.shape)
return EC
else:
if mu is None:
mu = stationary_distribution(T)
EC = n * mu[:, np.newaxis] * T
return EC | def expected_counts_stationary(T, n, mu=None) | r"""Expected transition counts for Markov chain in equilibrium.
Since mu is stationary for T we have
.. math::
E(C^{(N)})=N diag(mu)*T.
Parameters
----------
T : (M, M) ndarray
Transition matrix.
n : int
Number of steps for chain.
mu : (M,) ndarray (optional)
... | 4.677057 | 4.258389 | 1.098316 |
q = np.asarray(q)
if n < 0:
raise ValueError('Finite geometric series is only defined for n>=0.')
else:
if q.ndim == 0:
if q == 1:
s = (n + 1) * 1.0
return s
else:
s = (1.0 - q ** (n + 1)) / (1.0 - q)
... | def geometric_series(q, n) | Compute finite geometric series.
\frac{1-q^{n+1}}{1-q} q \neq 1
\sum_{k=0}^{n} q^{k}=
n+1 q = 1
Parameters
----------
q : array-like
The common ratio of the geometric series.
n : int
The num... | 2.379567 | 2.274317 | 1.046278 |
r
if (n <= 0):
EC = np.zeros(T.shape)
return EC
else:
p_k = 1.0 * p0
p_sum = 1.0 * p_k
for k in range(n - 1):
p_k = np.dot(p_k, T)
p_sum += p_k
EC = p_sum[:, np.newaxis] * T
r... | def ec_matrix_vector(p0, T, n) | r"""Compute expected transition counts for Markov chain after n
steps.
Expected counts are computed according to ..math::
E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^t T^{k})_{i} p_{ij}
The sum is computed via successive summation of the following
matrix vector products, p_1^t=p_0^t T,...,p_n^t=P_{n-1}... | 3.896688 | 3.757227 | 1.037118 |
r
if (n <= 0):
EC = np.zeros(T.shape)
return EC
else:
R, D, L = rdl_decomposition(T)
w = np.diagonal(D)
L = np.transpose(L)
D_sum = np.diag(geometric_series(w, n - 1))
T_sum = np.dot(np.dot(R, D_sum), np.conjugate(np.transpose(L)))
p_sum = np.... | def ec_geometric_series(p0, T, n) | r"""Compute expected transition counts for Markov chain after n
steps.
Expected counts are computed according to ..math::
E[C_{ij}^{(n)}]=\sum_{k=0}^{n-1} (p_0^t T^{k})_{i} p_{ij}
The sum is computed using the eigenvalue decomposition of T and
applying the expression for a finite geometric series... | 4.795786 | 4.158849 | 1.153152 |
M = C.shape[0]
z0 = np.zeros(2*M)
z0[0:M] = 1.0
# G = np.zeros((M, 2*M))
# G[np.arange(M), np.arange(M)] = -1.0
G = -1.0*scipy.sparse.eye(M, n=2*M, k=0)
h = np.zeros(M)
A = np.zeros((1, 2*M))
A[0, M] = 1.0
b = np.array([0.0])
c0 = C.max()
C = ... | def solve_mle_rev(C, tol=1e-10, maxiter=100, show_progress=False, full_output=False,
return_statdist=True, **kwargs) | Number of states | 3.015287 | 3.005112 | 1.003386 |
if name[-1:] == ".":
name = name[:-1]
name = str(name).replace(".", "/")
return name | def blueprint_name_to_url(name) | remove the last . in the string it it ends with a .
for the url structure must follow the flask routing format
it should be /model/method instead of /model/method/ | 5.218118 | 4.428298 | 1.178358 |
"Simple homepage view."
context = {}
if request.user.is_authenticated():
try:
access = request.user.accountaccess_set.all()[0]
except IndexError:
access = None
else:
client = access.api_client
context['info'] = client.get_profile_info(r... | def home(request) | Simple homepage view. | 4.486346 | 3.980145 | 1.127182 |
"Write your forwards methods here."
# Note: Don't use "from appname.models import ModelName".
# Use orm.ModelName to refer to models in this application,
# and orm['appname.ModelName'] for models in other applications.
from account_keeping.models import Invoice
for invoi... | def forwards(self, orm) | Write your forwards methods here. | 4.979017 | 4.577026 | 1.087828 |
"Return the API client for the given provider."
cls = OAuth2Client
if provider.request_token_url:
cls = OAuthClient
return cls(provider, token) | def get_client(provider, token='') | Return the API client for the given provider. | 6.859323 | 6.241931 | 1.09891 |
"Fetch user profile information."
try:
response = self.request('get', self.provider.profile_url, token=raw_token, params=profile_info_params)
response.raise_for_status()
except RequestException as e:
logger.error('Unable to fetch user profile: {0}'.format(e))
... | def get_profile_info(self, raw_token, profile_info_params={}) | Fetch user profile information. | 3.53313 | 3.512053 | 1.006001 |
"Fetch access token from callback request."
raw_token = request.session.get(self.session_key, None)
verifier = request.GET.get('oauth_verifier', None)
if raw_token is not None and verifier is not None:
data = {'oauth_verifier': verifier}
callback = request.build_a... | def get_access_token(self, request, callback=None) | Fetch access token from callback request. | 2.874029 | 2.757647 | 1.042204 |
"Get request parameters for redirect url."
callback = force_text(request.build_absolute_uri(callback))
raw_token = self.get_request_token(request, callback)
token, secret = self.parse_raw_token(raw_token)
if token is not None and secret is not None:
request.session[se... | def get_redirect_args(self, request, callback) | Get request parameters for redirect url. | 3.587955 | 3.296012 | 1.088574 |
"Parse token and secret from raw token response."
if raw_token is None:
return (None, None)
qs = parse_qs(raw_token)
token = qs.get('oauth_token', [None])[0]
secret = qs.get('oauth_token_secret', [None])[0]
return (token, secret) | def parse_raw_token(self, raw_token) | Parse token and secret from raw token response. | 3.121554 | 2.286621 | 1.365138 |
"Build remote url request. Constructs necessary auth."
user_token = kwargs.pop('token', self.token)
token, secret = self.parse_raw_token(user_token)
callback = kwargs.pop('oauth_callback', None)
verifier = kwargs.get('data', {}).pop('oauth_verifier', None)
oauth = OAuth1(... | def request(self, method, url, **kwargs) | Build remote url request. Constructs necessary auth. | 3.490652 | 2.725072 | 1.280939 |
"Check optional state parameter."
stored = request.session.get(self.session_key, None)
returned = request.GET.get('state', None)
check = False
if stored is not None:
if returned is not None:
check = constant_time_compare(stored, returned)
e... | def check_application_state(self, request, callback) | Check optional state parameter. | 4.812575 | 4.120958 | 1.167829 |
"Get request parameters for redirect url."
callback = request.build_absolute_uri(callback)
args = {
'client_id': self.provider.consumer_key,
'redirect_uri': callback,
'response_type': 'code',
}
state = self.get_application_state(request, callba... | def get_redirect_args(self, request, callback) | Get request parameters for redirect url. | 3.042194 | 2.692074 | 1.130056 |
"Parse token and secret from raw token response."
if raw_token is None:
return (None, None)
# Load as json first then parse as query string
try:
token_data = json.loads(raw_token)
except ValueError:
qs = parse_qs(raw_token)
token = ... | def parse_raw_token(self, raw_token) | Parse token and secret from raw token response. | 3.634987 | 2.967492 | 1.224936 |
"Build remote url request. Constructs necessary auth."
user_token = kwargs.pop('token', self.token)
token, _ = self.parse_raw_token(user_token)
if token is not None:
params = kwargs.get('params', {})
params['access_token'] = token
kwargs['params'] = pa... | def request(self, method, url, **kwargs) | Build remote url request. Constructs necessary auth. | 4.574244 | 2.97402 | 1.538067 |
return tuple([
code.strip() for code in codes.split(',')
if code.strip()
]) | def _stripped_codes(codes) | Return a tuple of stripped codes split by ','. | 5.298919 | 3.441556 | 1.539687 |
if not self._compiled_regex:
self._compiled_regex = re.compile(self.raw)
return self._compiled_regex | def regex(self) | Return compiled regex. | 3.716479 | 2.635123 | 1.410363 |
if not self._marker:
assert markers, 'Package packaging is needed for environment markers'
self._marker = markers.Marker(self.raw)
return self._marker | def marker(self) | Return environment marker. | 15.489985 | 10.506953 | 1.47426 |
for selector in self.regex_selectors:
for match in selector.regex.finditer(line):
if codes and match.lastindex:
# Currently the group name must be 'codes'
try:
disabled_codes = match.group('codes')
... | def regex_match_any(self, line, codes=None) | Match any regex. | 4.86955 | 4.899152 | 0.993958 |
if self.regex_match_any(line, codes):
if self._vary_codes:
self.codes = tuple([codes[-1]])
return True | def match(self, filename, line, codes) | Match rule and set attribute codes. | 11.421528 | 9.359037 | 1.220374 |
if filename.startswith('.' + os.sep):
filename = filename[len(os.sep) + 1:]
if os.sep != '/':
filename = filename.replace(os.sep, '/')
for selector in self.file_selectors:
if (selector.pattern.endswith('/') and
filename.startswith... | def file_match_any(self, filename) | Match any filename. | 2.623485 | 2.595877 | 1.010635 |
for selector in self.code_selectors:
if selector.code in codes:
return True
return False | def codes_match_any(self, codes) | Match any code. | 5.118687 | 4.585987 | 1.116158 |
if ((not self.file_selectors or self.file_match_any(filename)) and
(not self.environment_marker_selector or
self.environment_marker_evaluate()) and
(not self.code_selectors or self.codes_match_any(codes))):
if self.regex_selectors:
... | def match(self, filename, line, codes) | Match rule. | 4.770406 | 4.503169 | 1.059344 |
"Fetch user for a given provider by id."
provider_q = Q(provider__name=provider)
if isinstance(provider, Provider):
provider_q = Q(provider=provider)
try:
access = AccountAccess.objects.filter(
provider_q, identifier=identifier
).select... | def authenticate(self, provider=None, identifier=None) | Fetch user for a given provider by id. | 4.55279 | 3.78296 | 1.203499 |
mod = loader.find_module(name).load_module(name)
if hasattr(mod, '__method__'):
module_router = ModuleRouter(mod,
ignore_names=self.__serialize_module_paths()
).register_route(... | def __extract_modules(self, loader, name, is_pkg) | if module found load module and save all attributes in the module found | 7.235154 | 7.104603 | 1.018376 |
"Get instance of the OAuth client for this provider."
if self.client_class is not None:
return self.client_class(provider)
return get_client(provider) | def get_client(self, provider) | Get instance of the OAuth client for this provider. | 6.124037 | 4.007315 | 1.528214 |
"Build redirect url for a given provider."
name = kwargs.get('provider', '')
try:
provider = Provider.objects.get(name=name)
except Provider.DoesNotExist:
raise Http404('Unknown OAuth provider.')
else:
if not provider.enabled():
... | def get_redirect_url(self, **kwargs) | Build redirect url for a given provider. | 3.147413 | 2.864967 | 1.098586 |
"Create a shell auth.User."
digest = hashlib.sha1(smart_bytes(access)).digest()
# Base 64 encode to get below 30 characters
# Removed padding characters
username = force_text(base64.urlsafe_b64encode(digest)).replace('=', '')
User = get_user_model()
kwargs = {
... | def get_or_create_user(self, provider, access, info) | Create a shell auth.User. | 6.504699 | 4.929649 | 1.319506 |
"Return unique identifier from the profile info."
id_key = self.provider_id or 'id'
result = info
try:
for key in id_key.split('.'):
result = result[key]
return result
except KeyError:
return None | def get_user_id(self, provider, info) | Return unique identifier from the profile info. | 6.469148 | 4.329681 | 1.49414 |
"Login user and redirect."
login(self.request, user)
return redirect(self.get_login_redirect(provider, user, access)) | def handle_existing_user(self, provider, user, access, info) | Login user and redirect. | 7.259803 | 4.230063 | 1.71624 |
"Create a shell auth.User and redirect."
user = self.get_or_create_user(provider, access, info)
access.user = user
AccountAccess.objects.filter(pk=access.pk).update(user=user)
user = authenticate(provider=access.provider, identifier=access.identifier)
login(self.request, ... | def handle_new_user(self, provider, access, info) | Create a shell auth.User and redirect. | 4.822491 | 3.184294 | 1.514462 |
async with websession.get(URL_NUPNP) as res:
return [Bridge(item['internalipaddress'], websession=websession)
for item in (await res.json())] | async def discover_nupnp(websession) | Discover bridges via NUPNP. | 5.031535 | 4.068703 | 1.236643 |
current_year = now().year
if year == current_year:
return now().month
if year > current_year:
return 1
if year < current_year:
return 12 | def get_months_of_year(year) | Returns the number of months that have already passed in the given year.
This is useful for calculating averages on the year view. For past years,
we should divide by 12, but for the current year, we should divide by
the current month. | 3.03652 | 3.219259 | 0.943236 |
try:
light_spec = self.controlcapabilities
gtup = tuple([XYPoint(*x) for x in light_spec['colorgamut']])
color_gamut = GamutType(*gtup)
except KeyError:
color_gamut = None
return color_gamut | def colorgamut(self) | The color gamut information of the light. | 10.044127 | 7.521092 | 1.335461 |
qs = Transaction.objects.filter(account=account, parent__isnull=True)
qs = qs.values('payee').annotate(models.Sum('value_gross'))
qs = qs.order_by('payee__name')
return qs | def get_totals_by_payee(self, account, start_date=None, end_date=None) | Returns transaction totals grouped by Payee. | 3.694846 | 3.29628 | 1.120914 |
qs = Transaction.objects.filter(
children__isnull=True, invoice__isnull=True)
return qs | def get_without_invoice(self) | Returns transactions that don't have an invoice.
We filter out transactions that have children, because those
transactions never have invoices - their children are the ones that
would each have one invoice. | 8.45399 | 4.57967 | 1.845982 |
providers = Provider.objects.all()
return [p for p in providers if p.enabled()] | def _get_enabled() | Wrapped function for filtering enabled providers. | 7.91739 | 5.738712 | 1.379646 |
"Adds the list of enabled providers to the context."
if APPENGINE:
# Note: AppEngine inequality queries are limited to one property.
# See https://developers.google.com/appengine/docs/python/datastore/queries#Python_Restrictions_on_queries
# Users have also noted that the exclusion queri... | def available_providers(request) | Adds the list of enabled providers to the context. | 9.926411 | 9.07765 | 1.0935 |
# Windows low-level subprocess API wants str for current working
# directory.
if sys.platform == 'win32':
_cwd = kw.get('cwd', None)
if _cwd is not None:
kw['cwd'] = _cwd.decode()
try:
# In Python 3, iterating over bytes yield integers, so we call
# `spli... | def run(command, **kw) | Run `command`, catch any exception, and return lines of output. | 5.486529 | 5.510652 | 0.995623 |
command = [b'locate', b'-0']
for dotdir in DOTDIRS:
# Escaping the slash (using '\/' rather than '/') is an
# important signal to locate(1) that these glob patterns are
# supposed to match the full path, so that things like
# '.hgignore' files do not show up in the result.
... | def find_repositories_with_locate(path) | Use locate to return a sequence of (directory, dotdir) pairs. | 4.89562 | 4.508116 | 1.085957 |
repos = []
for dirpath, dirnames, filenames in os.walk(path, followlinks=False):
for dotdir in set(dirnames) & DOTDIRS:
repos.append((dirpath, dotdir))
return repos | def find_repositories_by_walking_without_following_symlinks(path) | Walk a tree and return a sequence of (directory, dotdir) pairs. | 3.210726 | 2.528863 | 1.269632 |
repos = []
# This is for detecting symlink loops and escaping them. This is similar to
# http://stackoverflow.com/questions/36977259/avoiding-infinite-recursion-with-os-walk/36977656#36977656
def inode(path):
stats = os.stat(path)
return stats.st_dev, stats.st_ino
seen_inodes =... | def find_repositories_by_walking_and_following_symlinks(path) | Walk a tree and return a sequence of (directory, dotdir) pairs. | 3.180707 | 3.06202 | 1.038761 |
lines = run(['hg', '--config', 'extensions.color=!', 'st'], cwd=path)
subrepos = ()
return [b' ' + l for l in lines if not l.startswith(b'?')], subrepos | def status_mercurial(path, ignore_set, options) | Run hg status.
Returns a 2-element tuple:
* Text lines describing the status of the repository.
* Empty sequence of subrepos, since hg does not support them. | 10.892364 | 8.482016 | 1.284172 |
# Check whether current branch is dirty:
lines = [l for l in run(('git', 'status', '-s', '-b'), cwd=path)
if (options.untracked or not l.startswith(b'?'))
and not l.startswith(b'##')]
# Check all branches for unpushed commits:
lines += [l for l in run(('git', 'branch', '-... | def status_git(path, ignore_set, options) | Run git status.
Returns a 2-element tuple:
* Text lines describing the status of the repository.
* List of subrepository paths, relative to the repository itself. | 3.019637 | 3.025469 | 0.998072 |
subrepos = ()
if path in ignore_set:
return None, subrepos
keepers = []
for line in run(['svn', 'st', '-v'], cwd=path):
if not line.strip():
continue
if line.startswith(b'Performing') or line[0] in b'X?':
continue
status = line[:8]
ign... | def status_subversion(path, ignore_set, options) | Run svn status.
Returns a 2-element tuple:
* Text lines describing the status of the repository.
* Empty sequence of subrepos, since svn does not support them. | 4.145086 | 4.124301 | 1.00504 |
ignore_set = set()
repos = repos[::-1] # Create a queue we can push and pop from
while repos:
directory, dotdir = repos.pop()
ignore_this = any(pat in directory for pat in options.ignore_patterns)
if ignore_this:
if options.verbose:
output(b'Ignoring... | def scan(repos, options) | Given a repository list [(path, vcsname), ...], scan each of them. | 4.94018 | 4.644777 | 1.063599 |
# Stack
# 1. get_reporter_state (i.e. this function)
# 2. putty_ignore_code
# 3. QueueReport.error or pep8.StandardReport.error for flake8 -j 1
# 4. pep8.Checker.check_ast or check_physical or check_logical
# locals contains `tree` (ast) for check_ast
frame = sys._getframe(3)
rep... | def get_reporter_state() | Get pep8 reporter state from stack. | 7.549521 | 6.919604 | 1.091034 |
reporter, line_number, offset, text, check = get_reporter_state()
try:
line = reporter.lines[line_number - 1]
except IndexError:
line = ''
options.ignore = options._orig_ignore
options.select = options._orig_select
for rule in options.putty_ignore:
if rule.match(re... | def putty_ignore_code(options, code) | Implement pep8 'ignore_code' hook. | 3.488749 | 3.277269 | 1.064529 |
parser.add_option(
'--putty-select', metavar='errors', default='',
help='putty select list',
)
parser.add_option(
'--putty-ignore', metavar='errors', default='',
help='putty ignore list',
)
parser.add_option(
'-... | def add_options(cls, parser) | Add options for command line and config file. | 2.666712 | 2.626426 | 1.015339 |
if (not options.putty_select and not options.putty_ignore and
not options.putty_auto_ignore):
return
options._orig_select = options.select
options._orig_ignore = options.ignore
options.putty_select = Parser(options.putty_select)._rules
optio... | def parse_options(cls, options) | Parse options and activate `ignore_code` handler. | 4.373005 | 3.788919 | 1.154156 |
if isinstance(data, list):
data = data[0]
if isinstance(data, dict) and 'error' in data:
raise_error(data['error']) | def _raise_on_error(data) | Check response for error message. | 2.994533 | 2.547378 | 1.175536 |
result = await self.request('post', '', {
'devicetype': device_type
}, auth=False)
self.username = result[0]['success']['username']
return self.username | async def create_user(self, device_type) | Create a user.
https://developers.meethue.com/documentation/configuration-api#71_create_user | 5.743139 | 3.971256 | 1.446177 |
url = 'http://{}/api/'.format(self.host)
if auth:
url += '{}/'.format(self.username)
url += path
try:
async with self.websession.request(method, url, json=json) as res:
if res.content_type != 'application/json':
raise ... | async def request(self, method, path, json=None, auth=True) | Make a request to the API. | 2.55677 | 2.508776 | 1.01913 |
data = {
key: value for key, value in {
'on': on,
'long': long,
'lat': lat,
'sunriseoffset': sunriseoffset,
'sunsetoffset': sunsetoffset,
}.items() if value is not None
}
await self.... | async def set_config(self, on=None, long=None, lat=None,
sunriseoffset=None, sunsetoffset=None) | Change config of a Daylight sensor. | 2.138554 | 2.006568 | 1.065777 |
data = {
key: value for key, value in {
'on': on,
'tholddark': tholddark,
'tholdoffset': tholdoffset,
}.items() if value is not None
}
await self._request('put', 'sensors/{}/config'.format(self.id),
... | async def set_config(self, on=None, tholddark=None, tholdoffset=None) | Change config of a CLIP LightLevel sensor. | 2.408484 | 2.16837 | 1.110735 |
if not client: # pragma: nocover
return None
result = {}
try:
unpaid_invoices = client.fetch_json(
'invoices', query_params={'state': 'unpaid'})
except (ConnectionError, HTTPError): # pragma: nocover
result.update({'error': _('Wasn\'t able to connect to Freckle... | def get_unpaid_invoices_with_transactions(branch=None) | Returns all invoices that are unpaid on freckle but have transactions.
This means, that the invoice is either partially paid and can be left as
unpaid in freckle, or the invoice has been fully paid and should be set to
paid in freckle as well. | 3.181738 | 3.03837 | 1.047186 |
def load_cfg(self, src_dir):
# last files override previous ones
cfg_files = [os.path.expanduser(USER_CFG_FILE),
os.path.abspath(os.path.join(src_dir, '.dirsync'))]
cfg = ConfigParser()
cfg.read(cfg_files)
if not cfg.has_section('default... | Load defaults from configuration file:
- from the source/directory/.dirsync file (prioritary)
- and/or a %HOME%/.dirsync user config file | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.