text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expectation(T, a, mu=None): r"""Equilibrium expectation value of a given observable. Parameters T : (M, M) ndarray or scipy.sparse matrix Transition matrix a...
# check if square matrix and remember size T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') n = T.shape[0] a = _types.ensure_ndarray(a, ndim=1, size=n, kind='numeric') mu = _types.ensure_ndarray_or_None(mu, ndim=1, size=n, kind='numeric') # go if not mu: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pcca_object(T, m): """ Constructs the pcca object from dense or sparse Parameters T : (n, n) ndarray or scipy.sparse matrix Transition matrix m : int Number...
if _issparse(T): _showSparseConversionWarning() T = T.toarray() T = _types.ensure_ndarray(T, ndim=2, uniform=True, kind='numeric') return dense.pcca.PCCA(T, m)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eigenvalue_sensitivity(T, k): r"""Sensitivity matrix of a specified eigenvalue. Parameters T : (M, M) ndarray Transition matrix k : int Compute sensitivity m...
T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): _showSparseConversionWarning() eigenvalue_sensitivity(T.todense(), k) else: return dense.sensitivity.eigenvalue_sensitivity(T, k)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eigenvector_sensitivity(T, k, j, right=True): r"""Sensitivity matrix of a selected eigenvector element. Parameters T : (M, M) ndarray Transition matrix (stoc...
T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): _showSparseConversionWarning() eigenvector_sensitivity(T.todense(), k, j, right=right) else: return dense.sensitivity.eigenvector_sensitivity(T, k, j, right=right)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stationary_distribution_sensitivity(T, j): r"""Sensitivity matrix of a stationary distribution element. Parameters T : (M, M) ndarray Transition matrix (stoc...
T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') if _issparse(T): _showSparseConversionWarning() stationary_distribution_sensitivity(T.todense(), j) else: return dense.sensitivity.stationary_distribution_sensitivity(T, j)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mfpt_sensitivity(T, target, i): r"""Sensitivity matrix of the mean first-passage time from specified state. Parameters T : (M, M) ndarray Transition matrix t...
# check input T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') target = _types.ensure_int_vector(target) # go if _issparse(T): _showSparseConversionWarning() mfpt_sensitivity(T.todense(), target, i) else: return dense.sensitivity.mfpt_sensitiv...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def committor_sensitivity(T, A, B, i, forward=True): r"""Sensitivity matrix of a specified committor entry. Parameters T : (M, M) ndarray Transition matrix A : a...
# check inputs T = _types.ensure_ndarray_or_sparse(T, ndim=2, uniform=True, kind='numeric') A = _types.ensure_int_vector(A) B = _types.ensure_int_vector(B) if _issparse(T): _showSparseConversionWarning() committor_sensitivity(T.todense(), A, B, i, forward) else: if forwa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tmatrix_cov(C, row=None): r"""Covariance tensor for the non-reversible transition matrix ensemble Normally the covariance tensor cov(p_ij, p_kl) would carry ...
if row is None: alpha = C + 1.0 # Dirichlet parameters alpha0 = alpha.sum(axis=1) # Sum of paramters (per row) norm = alpha0 ** 2 * (alpha0 + 1.0) """Non-normalized covariance tensor""" Z = -alpha[:, :, np.newaxis] * alpha[:, np.newaxis, :] """Correct-diagonal"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dirichlet_covariance(alpha): r"""Covariance matrix for Dirichlet distribution. Parameters alpha : (M, ) ndarray Parameters of Dirichlet distribution Returns ...
alpha0 = alpha.sum() norm = alpha0 ** 2 * (alpha0 + 1.0) """Non normalized covariance""" Z = -alpha[:, np.newaxis] * alpha[np.newaxis, :] """Correct diagonal""" ind = np.diag_indices(Z.shape[0]) Z[ind] += alpha0 * alpha """Covariance matrix""" cov = Z / norm return cov
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mfpt_between_sets(T, target, origin, mu=None): """Compute mean-first-passage time between subsets of state space. Parameters T : scipy.sparse matrix Transiti...
if mu is None: mu = stationary_distribution(T) """Stationary distribution restriced on starting set X""" nuX = mu[origin] muX = nuX / np.sum(nuX) """Mean first-passage time to Y (for all possible starting states)""" tY = mfpt(T, target) """Mean first-passage time from X to Y""" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mydot(A, B): r"""Dot-product that can handle dense and sparse arrays Parameters A : numpy ndarray or scipy sparse matrix The first factor B : numpy ndarray o...
if issparse(A) : return A.dot(B) elif issparse(B): return (B.T.dot(A.T)).T else: return np.dot(A, B)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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}...
if (N <= 0): EC = coo_matrix(T.shape, dtype=float) return EC else: """Probability vector after (k=0) propagations""" p_k = 1.0 * p0 """Sum of vectors after (k=0) propagations""" p_sum = 1.0 * p_k """Transpose T to use sparse dot product""" Tt = T....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fingerprint(P, obs1, obs2=None, p0=None, tau=1, k=None, ncv=None): r"""Dynamical fingerprint for equilibrium or relaxation experiment The dynamical fingerpri...
if obs2 is None: obs2 = obs1 R, D, L = rdl_decomposition(P, k=k, ncv=ncv) """Stationary vector""" mu = L[0, :] """Extract diagonal""" w = np.diagonal(D) """Compute time-scales""" timescales = timescales_from_eigenvalues(w, tau) if p0 is None: """Use stationary distri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correlation_matvec(P, obs1, obs2=None, times=[1]): r"""Time-correlation for equilibrium experiment - via matrix vector products. Parameters P : (M, M) ndarra...
if obs2 is None: obs2 = obs1 """Compute stationary vector""" mu = statdist(P) obs1mu = mu * obs1 times = np.asarray(times) """Sort in increasing order""" ind = np.argsort(times) times = times[ind] if times[0] < 0: raise ValueError("Times can not be negative") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def propagate(A, x, N): r"""Use matrix A to propagate vector x. Parameters A : (M, M) scipy.sparse matrix Matrix of propagator x : (M, ) ndarray or scipy.sparse ...
y = 1.0 * x for i in range(N): y = A.dot(y) return y
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_traj(P, N, start=None, stop=None, dt=1): """ Generates a realization of the Markov chain with transition matrix P. Parameters P : (n, n) ndarray tra...
sampler = MarkovChainSampler(P, dt=dt) return sampler.trajectory(N, start=start, stop=stop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_trajs(P, M, N, start=None, stop=None, dt=1): """ Generates multiple realizations of the Markov chain with transition matrix P. Parameters P : (n, n)...
sampler = MarkovChainSampler(P, dt=dt) return sampler.trajectories(M, N, start=start, stop=stop)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transition_matrix_metropolis_1d(E, d=1.0): r"""Transition matrix describing the Metropolis chain jumping between neighbors in a discrete 1D energy landscape....
# check input if (d <= 0 or d > 1): raise ValueError('Diffusivity must be in (0,1]. Trying to set the invalid value', str(d)) # init n = len(E) P = np.zeros((n, n)) # set offdiagonals P[0, 1] = 0.5 * d * min(1.0, math.exp(-(E[1] - E[0]))) for i in range(1, n - 1): P[i, i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trajectory(self, N, start=None, stop=None): """ Generates a trajectory realization of length N, starting from state s Parameters N : int trajectory length st...
# check input stop = types.ensure_int_vector_or_None(stop, require_order=False) if start is None: if self.mudist is None: # compute mu, the stationary distribution of P import msmtools.analysis as msmana from scipy.stats import rv_dis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trajectories(self, M, N, start=None, stop=None): """ Generates M trajectories, each of length N, starting from state s Parameters M : int number of trajector...
trajs = [self.trajectory(N, start=start, stop=stop) for _ in range(M)] return trajs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _split_sequences_singletraj(dtraj, nstates, lag): """ splits the discrete trajectory into conditional sequences by starting state Parameters dtraj : int-iter...
sall = [[] for _ in range(nstates)] res_states = [] res_seqs = [] for t in range(len(dtraj)-lag): sall[dtraj[t]].append(dtraj[t+lag]) for i in range(nstates): if len(sall[i]) > 0: res_states.append(i) res_seqs.append(np.array(sall[i])) return res_states...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _split_sequences_multitraj(dtrajs, lag): """ splits the discrete trajectories into conditional sequences by starting state Parameters dtrajs : list of int-it...
n = number_of_states(dtrajs) res = [] for i in range(n): res.append([]) for dtraj in dtrajs: states, seqs = _split_sequences_singletraj(dtraj, n, lag) for i in range(len(states)): res[states[i]].append(seqs[i]) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _indicator_multitraj(ss, i, j): """ Returns conditional sequence for transition i -> j given all conditional sequences """
iseqs = ss[i] res = [] for iseq in iseqs: x = np.zeros(len(iseq)) I = np.where(iseq == j) x[I] = 1.0 res.append(x) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def statistical_inefficiencies(dtrajs, lag, C=None, truncate_acf=True, mact=2.0, n_jobs=1, callback=None): r""" Computes statistical inefficiencies of sliding-wi...
# count matrix if C is None: C = count_matrix_coo2_mult(dtrajs, lag, sliding=True, sparse=True) if callback is not None: if not callable(callback): raise ValueError('Provided callback is not callable') # split sequences splitseq = _split_sequences_multitraj(dtrajs, lag) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transition_matrix_non_reversible(C): r""" Estimates a non-reversible transition matrix from count matrix C T_ij = c_ij / c_i where c_i = sum_j c_ij Parameter...
# multiply by 1.0 to make sure we're not doing integer division rowsums = 1.0 * np.sum(C, axis=1) if np.min(rowsums) <= 0: raise ValueError( "Transition matrix has row sum of " + str(np.min(rowsums)) + ". Must have strictly positive row sums.") return np.divide(C, rowsums[:, np.newa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_correlation_direct_by_mtx_vec_prod(P, mu, obs1, obs2=None, time=1, start_values=None, return_P_k_obs=False): r"""Compute time-correlation of obs1, or ti...
# input checks if not (type(time) == int): if not (type(time) == np.int64): raise TypeError("given time (%s) is not an integer, but has type: %s" % (str(time), type(time))) if obs1.shape[0] != P.shape[0]: raise ValueError("observable shape not compati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def time_correlations_direct(P, pi, obs1, obs2=None, times=[1]): r"""Compute time-correlations of obs1, or time-cross-correlation with obs2. The time-correlation...
n_t = len(times) times = np.sort(times) # sort it to use caching of previously computed correlations f = np.zeros(n_t) # maximum time > number of rows? if times[-1] > P.shape[0]: use_diagonalization = True R, D, L = rdl_decomposition(P) # discard imaginary part, if all ele...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def factor_aug(z, DPhival, G, A): r"""Set up augmented system and return. Parameters z : (N+P+M+M,) ndarray Current iterate, z = (x, nu, l, s) DPhival : LinearOp...
M, N = G.shape P, N = A.shape """Multiplier for inequality constraints""" l = z[N+P:N+P+M] """Slacks""" s = z[N+P+M:] """Sigma matrix""" SIG = diags(l/s, 0) # SIG = diags(l*s, 0) """Convert A""" if not issparse(A): A = csr_matrix(A) """Convert G""" if not...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def I(self): r"""Returns the set of intermediate states """
return list(set(range(self.nstates)) - set(self._A) - set(self._B))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _pathways_to_flux(self, paths, pathfluxes, n=None): r"""Sums up the flux from the pathways given Parameters paths : list of int-arrays list of pathways pathf...
if (n is None): n = 0 for p in paths: n = max(n, np.max(p)) n += 1 # initialize flux F = np.zeros((n, n)) for i in range(len(paths)): p = paths[i] for t in range(len(p) - 1): F[p[t], p[t + 1]] +...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def major_flux(self, fraction=0.9): r"""Returns the main pathway part of the net flux comprising at most the requested fraction of the full flux. """
(paths, pathfluxes) = self.pathways(fraction=fraction) return self._pathways_to_flux(paths, pathfluxes, n=self.nstates)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_coarse_sets(self, user_sets): r"""Computes the sets to coarse-grain the tpt flux to. Parameters (tpt_sets, A, B) with tpt_sets : list of int-iterabl...
# set-ify everything setA = set(self.A) setB = set(self.B) setI = set(self.I) raw_sets = [set(user_set) for user_set in user_sets] # anything missing? Compute all listed states set_all = set(range(self.nstates)) set_all_user = [] for user_set in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coarse_grain(self, user_sets): r"""Coarse-grains the flux onto user-defined sets. Parameters user_sets : list of int-iterables sets of states that shall be d...
# coarse-grain sets (tpt_sets, Aindexes, Bindexes) = self._compute_coarse_sets(user_sets) nnew = len(tpt_sets) # coarse-grain fluxHere we should branch between sparse and dense implementations, but currently there is only a F_coarse = tptapi.coarsegrain(self._gross_flux, tpt_se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def committor_forward(self, a, b): r"""Forward committor for birth-and-death-chain. The forward committor is the probability to hit state b before hitting state ...
u = np.zeros(self.dim) g = np.zeros(self.dim - 1) g[0] = 1.0 g[1:] = np.cumprod(self.q[1:-1] / self.p[1:-1]) """If a and b are equal the event T_b<T_a is impossible for any starting state x so that the committor is zero everywhere""" if a == b: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transition_matrix_non_reversible(C): """implementation of transition_matrix"""
if not scipy.sparse.issparse(C): C = scipy.sparse.csr_matrix(C) rowsum = C.tocsr().sum(axis=1) # catch div by zero if np.min(rowsum) == 0.0: raise ValueError("matrix C contains rows with sum zero.") rowsum = np.array(1. / rowsum).flatten() norm = scipy.sparse.diags(rowsum, 0) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correct_transition_matrix(T, reversible=None): r"""Normalize transition matrix Fixes a the row normalization of a transition matrix. To be used with the reve...
row_sums = T.sum(axis=1).A1 max_sum = np.max(row_sums) if max_sum == 0.0: max_sum = 1.0 return (T + scipy.sparse.diags(-row_sums+max_sum, 0)) / max_sum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expectation(P, obs): r"""Equilibrium expectation of given observable. Parameters P : (M, M) ndarray Transition matrix obs : (M,) ndarray Observable, represen...
pi = statdist(P) return np.dot(pi, obs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correlation_decomp(P, obs1, obs2=None, times=[1], k=None): r"""Time-correlation for equilibrium experiment - via decomposition. Parameters P : (M, M) ndarray...
if obs2 is None: obs2 = obs1 R, D, L = rdl_decomposition(P, k=k) """Stationary vector""" mu = L[0, :] """Extract eigenvalues""" ev = np.diagonal(D) """Amplitudes""" amplitudes = np.dot(mu * obs1, R) * np.dot(L, obs2) """Propgate eigenvalues""" times = np.asarray(times) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_likelihood(C, T): """ implementation of likelihood of C given T """
C = C.tocsr() T = T.tocsr() ind = scipy.nonzero(C) relT = np.array(T[ind])[0, :] relT = np.log(relT) relC = np.array(C[ind])[0, :] return relT.dot(relC)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_file(token, channel_name, file_name): """ upload file to a channel """
slack = Slacker(token) slack.files.upload(file_name, channels=channel_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Run the minimization. Returns ------- K : (N,N) ndarray the optimal rate matrix """
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_and_gradi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unify_quotes(token_string, preferred_quote): """Return string with quotes changed to preferred_quote if possible."""
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 if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_encoding(filename): """Return file encoding."""
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 input...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _main(argv, standard_out, standard_error): """Run quotes unifying on files. Returns `1` if any quoting changes are still needed, otherwise `None`. """
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', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_matrix(dtraj, lag, sliding=True, sparse_return=True, nstates=None): r"""Generate a count matrix from given microstate trajectory. Parameters dtraj : ar...
# 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bootstrap_counts(dtrajs, lagtime, corrlength=None): r"""Generates a randomly resampled count matrix given the input coordinates. Parameters dtrajs : array-li...
dtrajs = _ensure_dtraj_list(dtrajs) return dense.bootstrapping.bootstrap_counts(dtrajs, lagtime, corrlength=corrlength)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 m...
if isdense(C): return sparse.connectivity.connected_sets(csr_matrix(C), directed=directed) else: return sparse.connectivity.connected_sets(C, directed=directed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 : sci...
if isdense(C): return sparse.connectivity.largest_connected_set(csr_matrix(C), directed=directed) else: return sparse.connectivity.largest_connected_set(C, directed=directed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_connected(C, directed=True): """Check connectivity of the given matrix. Parameters C : scipy.sparse matrix Count matrix specifying edge weights. directed ...
if isdense(C): return sparse.connectivity.is_connected(csr_matrix(C), directed=directed) else: return sparse.connectivity.is_connected(C, directed=directed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 : floa...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 (opti...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transition_matrix(C, reversible=False, mu=None, method='auto', **kwargs): r"""Estimate the transition matrix from the given countmatrix. Parameters C : numpy...
if issparse(C): sparse_input_type = True elif isdense(C): sparse_input_type = False else: raise NotImplementedError('C has an unknown type.') if method == 'dense': sparse_computation = False elif method == 'sparse': sparse_computation = True elif method ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 :...
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): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 matr...
if issparse(C): warnings.warn("Covariance matrix will be dense for sparse input") C = C.toarray() return dense.covariance.tmatrix_cov(C, row=k)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sample_tmatrix(C, nsample=1, nsteps=None, reversible=False, mu=None, T0=None, return_statdist=False): r"""samples transition matrices from the posterior dist...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tmatrix_sampler(C, reversible=False, mu=None, T0=None, nsteps=None, prior='sparse'): r"""Generate transition matrix sampler object. Parameters C : (M, M) nda...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 Return...
A = A.tocoo() data = A.data row = A.row col = A.col """Positive entries""" pos = data > 0.0 datap = data[pos] rowp = row[pos] colp = col[pos] Aplus = coo_matrix((datap, (rowp, colp)), shape=A.shape) return Aplus
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 Stationa...
D1 = diags((pi * qminus,), (0,)) D2 = diags((qplus,), (0,)) flux = D1.dot(T.dot(D2)) """Remove self-fluxes""" flux = flux - diags(flux.diagonal(), 0) """Return net or gross flux""" if netflux: return to_netflux(flux) else: return flux
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 be...
netflux = flux - flux.T """Set negative entries to zero""" netflux = remove_negative_entries(netflux) return netflux
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 pair...
X = set(np.arange(flux.shape[0])) # total state space A = set(A) notA = X.difference(A) """Extract rows corresponding to A""" W = flux.tocsr() W = W[list(A), :] """Extract columns corresonding to X\A""" W = W.tocsc() W = W[:, list(notA)] F = W.sum() return F
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stationary_distribution_sensitivity(T, j): r"""Calculate the sensitivity matrix for entry j the stationary distribution vector given transition matrix T. Par...
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])) phi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 com...
q = np.asarray(q) if n < 0: raise ValueError('Finite geometric series is only defined for n>=0.') else: """q is scalar""" if q.ndim == 0: if q == 1: s = (n + 1) * 1.0 return s else: s = (1.0 - q ** (n + 1)) / (1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve_mle_rev(C, tol=1e-10, maxiter=100, show_progress=False, full_output=False, return_statdist=True, **kwargs): """Number of states"""
M = C.shape[0] """Initial guess for primal-point""" z0 = np.zeros(2*M) z0[0:M] = 1.0 """Inequality constraints""" # 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) """Equality constraints""" A = np.zer...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def home(request): "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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_client(provider, token=''): "Return the API client for the given provider." cls = OAuth2Client if provider.request_token_url: cls = OAuthClient return cls(provider, token)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def check_application_state(self, request, callback): "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 =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _stripped_codes(codes): """Return a tuple of stripped codes split by ','."""
return tuple([ code.strip() for code in codes.split(',') if code.strip() ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regex(self): """Return compiled regex."""
if not self._compiled_regex: self._compiled_regex = re.compile(self.raw) return self._compiled_regex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def marker(self): """Return environment marker."""
if not self._marker: assert markers, 'Package packaging is needed for environment markers' self._marker = markers.Marker(self.raw) return self._marker
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regex_match_any(self, line, codes=None): """Match any regex."""
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') e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(self, filename, line, codes): """Match rule and set attribute codes."""
if self.regex_match_any(line, codes): if self._vary_codes: self.codes = tuple([codes[-1]]) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_match_any(self, filename): """Match any filename."""
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(selecto...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def codes_match_any(self, codes): """Match any code."""
for selector in self.code_selectors: if selector.code in codes: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(self, filename, line, codes): """Match rule."""
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: re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def authenticate(self, provider=None, identifier=None): "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( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __extract_modules(self, loader, name, is_pkg): """ if module found load module and save all attributes in the module found """
mod = loader.find_module(name).load_module(name) """ find the attribute method on each module """ if hasattr(mod, '__method__'): """ register to the blueprint if method attribute found """ module_router = ModuleRouter(mod, ignor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_or_create_user(self, provider, access, info): "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('=', '') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_user_id(self, provider, info): "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: retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def handle_existing_user(self, provider, user, access, info): "Login user and redirect." login(self.request, user) return redirect(self.get_login_redirect(provider, user, access))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def handle_new_user(self, provider, access, info): "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, identif...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def discover_nupnp(websession): """Discover bridges via NUPNP."""
async with websession.get(URL_NUPNP) as res: return [Bridge(item['internalipaddress'], websession=websession) for item in (await res.json())]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 vi...
current_year = now().year if year == current_year: return now().month if year > current_year: return 1 if year < current_year: return 12
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colorgamut(self): """The color gamut information of the light."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_totals_by_payee(self, account, start_date=None, end_date=None): """ Returns transaction totals grouped by Payee. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_without_invoice(self): """ Returns transactions that don't have an invoice. We filter out transactions that have children, because those transactions nev...
qs = Transaction.objects.filter( children__isnull=True, invoice__isnull=True) return qs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_enabled(): """Wrapped function for filtering enabled providers."""
providers = Provider.objects.all() return [p for p in providers if p.enabled()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def available_providers(request): "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 a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(command, **kw): """Run `command`, catch any exception, and return lines of output."""
# 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 # `splitlin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status_mercurial(path, ignore_set, options): """Run hg status. Returns a 2-element tuple: * Text lines describing the status of the repository. * Empty seque...
lines = run(['hg', '--config', 'extensions.color=!', 'st'], cwd=path) subrepos = () return [b' ' + l for l in lines if not l.startswith(b'?')], subrepos
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 subrepos...
# 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', '-v'),...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status_subversion(path, ignore_set, options): """Run svn status. Returns a 2-element tuple: * Text lines describing the status of the repository. * Empty seq...
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] ignored...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_reporter_state(): """Get pep8 reporter state from stack."""
# 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) reporte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def putty_ignore_code(options, code): """Implement pep8 'ignore_code' hook."""
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(report...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_options(cls, parser): """Add options for command line and config file."""
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( '--putty-n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_options(cls, options): """Parse options and activate `ignore_code` handler."""
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 options.putty...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _raise_on_error(data): """Check response for error message."""
if isinstance(data, list): data = data[0] if isinstance(data, dict) and 'error' in data: raise_error(data['error'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def set_config(self, on=None, long=None, lat=None, sunriseoffset=None, sunsetoffset=None): """Change config of a Daylight sensor."""
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._request...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def set_config(self, on=None, tholddark=None, tholdoffset=None): """Change config of a CLIP LightLevel sensor."""
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), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_unpaid_invoices_with_transactions(branch=None): """ Returns all invoices that are unpaid on freckle but have transactions. This means, that the invoice i...
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.')}...