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 load(filename):
"""Load an object that has been saved with dump. We try to open it using the pickle protocol. As a fallback, we use joblib.load. Joblib was t... |
try:
with open(filename, 'rb') as f:
return pickle.load(f)
except Exception as e1:
try:
return jl_load(filename)
except Exception as e2:
raise IOError(
"Unable to load {} using the pickle or joblib protocol.\n"
"Pickle:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verbosedump(value, fn, compress=None):
"""Verbose wrapper around dump""" |
print('Saving "%s"... (%s)' % (fn, type(value)))
dump(value, fn, compress=compress) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def net_fluxes(sources, sinks, msm, for_committors=None):
""" Computes the transition path theory net flux matrix. Parameters sources : array_like, int The set o... |
flux_matrix = fluxes(sources, sinks, msm, for_committors=for_committors)
net_flux = flux_matrix - flux_matrix.T
net_flux[np.where(net_flux < 0)] = 0.0
return net_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 featurize_all(filenames, featurizer, topology, chunk=1000, stride=1):
"""Load and featurize many trajectory files. Parameters filenames : list of strings Lis... |
data = []
indices = []
fns = []
for file in filenames:
kwargs = {} if file.endswith('.h5') else {'top': topology}
count = 0
for t in md.iterload(file, chunk=chunk, stride=stride, **kwargs):
x = featurizer.partial_transform(t)
n_frames = len(x)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_features(self, traj):
"""Generic method for describing features. Parameters traj : mdtraj.Trajectory Trajectory to use Returns ------- feature_descs... |
n_f = self.partial_transform(traj).shape[1]
zippy=zip(itertools.repeat("N/A", n_f),
itertools.repeat("N/A", n_f),
itertools.repeat("N/A", n_f),
itertools.repeat(("N/A","N/A","N/A","N/A"), n_f))
return dict_maker(zippy) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_features(self, traj):
"""Return a list of dictionaries describing the LandmarkRMSD features. Parameters traj : mdtraj.Trajectory The trajectory to d... |
feature_descs = []
# fill in the atom indices using just the first frame
self.partial_transform(traj[0])
top = traj.topology
aind_tuples = [self.atom_indices for _ in range(self.sliced_reference_traj.n_frames)]
zippy = zippy_maker(aind_tuples, top)
zippy = iter... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via pairwise atom-atom distances Parameters traj : mdtraj.Trajectory A molec... |
d = md.geometry.compute_distances(traj, self.pair_indices,
periodic=self.periodic)
return d ** self.exponent |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_features(self, traj):
"""Return a list of dictionaries describing the atom pair features. Parameters traj : mdtraj.Trajectory The trajectory to desc... |
feature_descs = []
top = traj.topology
residue_indices = [[top.atom(i[0]).residue.index, top.atom(i[1]).residue.index] \
for i in self.atom_indices]
aind = []
resseqs = []
resnames = []
for ind,resid_ids in enumerate(residue_indices):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via calculation of soft-bins over dihdral angle space. Parameters traj : mdt... |
x = []
for a in self.types:
func = getattr(md, 'compute_%s' % a)
_, y = func(traj)
res = vm.pdf(y[..., np.newaxis],
loc=self.loc, kappa=self.kappa)
#we reshape the results using a Fortran-like index order,
#so that it... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_features(self, traj):
"""Return a list of dictionaries describing the SASA features. Parameters traj : mdtraj.Trajectory The trajectory to describe ... |
feature_descs = []
_, mapping = md.geometry.sasa.shrake_rupley(traj, mode=self.mode, get_mapping=True)
top = traj.topology
if self.mode == "residue":
resids = np.unique(mapping)
resseqs = [top.residue(ri).resSeq for ri in resids]
resnames = [top.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 partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space via calculation of solvent fingerprints Parameters traj : mdtraj.Trajectory ... |
# The result vector
fingerprints = np.zeros((traj.n_frames, self.n_features))
atom_pairs = np.zeros((len(self.solvent_indices), 2))
sigma = self.sigma
for i, solute_i in enumerate(self.solute_indices):
# For each solute atom, calculate distance to all solvent
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partial_transform(self, traj):
"""Featurize an MD trajectory into a vector space with the raw cartesian coordinates. Parameters traj : mdtraj.Trajectory A mo... |
# Optionally take only certain atoms
if self.atom_indices is not None:
p_traj = traj.atom_slice(self.atom_indices)
else:
p_traj = traj
# Optionally superpose to a reference trajectory.
if self.ref_traj is not None:
p_traj.superpose(self.ref_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 partial_transform(self, traj):
"""Slice a single input array along to select a subset of features. Parameters traj : np.ndarray, shape=(n_samples, n_features... |
if self.index is not None:
return traj[:, self.index]
else:
return traj[:, :self.first] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def param_sweep(model, sequences, param_grid, n_jobs=1, verbose=0):
"""Fit a series of models over a range of parameters. Parameters model : msmbuilder.BaseEstim... |
if isinstance(param_grid, dict):
param_grid = ParameterGrid(param_grid)
elif not isinstance(param_grid, ParameterGrid):
raise ValueError("param_grid must be a dict or ParamaterGrid instance")
# iterable with (model, sequence) as items
iter_args = ((clone(model).set_params(**params), s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dataset(path, mode='r', fmt=None, verbose=False, **kwargs):
"""Open a dataset object MSMBuilder supports several dataset 'formats' for storing lists of seque... |
if mode == 'r' and fmt is None:
fmt = _guess_format(path)
elif mode in 'wa' and fmt is None:
raise ValueError('mode="%s", but no fmt. fmt=%s' % (mode, fmt))
if fmt == 'dir-npy':
return NumpyDirDataset(path, mode=mode, verbose=verbose)
elif fmt == 'mdtraj':
return MDTra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_with(self, estimator, out_ds, fmt=None):
"""Call the partial_transform method of the estimator on this dataset Parameters estimator : object with `... |
if isinstance(out_ds, str):
out_ds = self.create_derived(out_ds, fmt=fmt)
elif isinstance(out_ds, _BaseDataset):
err = "Dataset must be opened in write mode."
assert out_ds.mode in ('w', 'a'), err
else:
err = "Please specify a dataset path or an 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 fit_transform_with(self, estimator, out_ds, fmt=None):
"""Create a new dataset with the given estimator. The estimator will be fit by this dataset, and then ... |
self.fit_with(estimator)
return self.transform_with(estimator, out_ds, fmt=fmt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mapped_populations(mdl1, mdl2):
""" Method to get the populations for states in mdl 1 from populations inferred in mdl 2. Resorts to 0 if population is not ... |
return_vect = np.zeros(mdl1.n_states_)
for i in range(mdl1.n_states_):
try:
#there has to be a better way to do this
mdl1_unmapped = mdl1.inverse_transform([i])[0][0]
mdl2_mapped = mdl2.mapping_[mdl1_unmapped]
return_vect[i] = mdl2.populations_[mdl2_mapp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def top_path(sources, sinks, net_flux):
""" Use the Dijkstra algorithm for finding the shortest path connecting a set of source states from a set of sink states.... |
sources = np.array(sources, dtype=np.int).reshape((-1,))
sinks = np.array(sinks, dtype=np.int).reshape((-1,))
n_states = net_flux.shape[0]
queue = list(sources)
# nodes to check (the "queue")
# going to use list.pop method so I can't keep it as an array
visited = np.zeros(n_states).astyp... |
<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_bottleneck(net_flux, path):
""" Internal function for modifying the net flux matrix by removing a particular edge, corresponding to the bottleneck of... |
net_flux = copy.copy(net_flux)
bottleneck_ind = net_flux[path[:-1], path[1:]].argmin()
net_flux[path[bottleneck_ind], path[bottleneck_ind + 1]] = 0.0
return net_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 _subtract_path_flux(net_flux, path):
""" Internal function for modifying the net flux matrix by subtracting a path's flux from every edge in the path. """ |
net_flux = copy.copy(net_flux)
net_flux[path[:-1], path[1:]] -= net_flux[path[:-1], path[1:]].min()
# The above *should* make the bottleneck have zero flux, but
# numerically that may not be the case, so just set it to zero
# to be sure.
bottleneck_ind = net_flux[path[:-1], path[1:]].argmin(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paths(sources, sinks, net_flux, remove_path='subtract', num_paths=np.inf, flux_cutoff=(1-1E-10)):
""" Get the top N paths by iteratively performing Dijkstra'... |
if not callable(remove_path):
if remove_path == 'subtract':
remove_path = _subtract_path_flux
elif remove_path == 'bottleneck':
remove_path = _remove_bottleneck
else:
raise ValueError("remove_path_func (%s) must be a callable or one of ['subtract', 'bott... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rao_blackwell_ledoit_wolf(S, n):
"""Rao-Blackwellized Ledoit-Wolf shrinkaged estimator of the covariance matrix. Parameters S : array, shape=(n, n) Sample co... |
p = len(S)
assert S.shape == (p, p)
alpha = (n-2)/(n*(n+2))
beta = ((p+1)*n - 2) / (n*(n+2))
trace_S2 = np.sum(S*S) # np.trace(S.dot(S))
U = ((p * trace_S2 / np.trace(S)**2) - 1)
rho = min(alpha + beta/U, 1)
F = (np.trace(S) / p) * np.eye(p)
return (1-rho)*S + rho*F, rho |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit(self, sequences, y=None):
"""Fit the model with a collection of sequences. This method is not online. Any state accumulated from previous calls to fit() ... |
self._initialized = False
check_iter_of_sequences(sequences, max_iter=3) # we might be lazy-loading
for X in sequences:
self._fit(X)
if self.n_sequences_ == 0:
raise ValueError('All sequences were shorter than '
'the lag time, %d' %... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, sequences):
"""Apply the dimensionality reduction on X. Parameters sequences: list of array-like, each of shape (n_samples_i, n_features) Tra... |
check_iter_of_sequences(sequences, max_iter=3) # we might be lazy-loading
sequences_new = []
for X in sequences:
X = array2d(X)
if self.means_ is not None:
X = X - self.means_
X_transformed = np.dot(X, self.components_.T)
if sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, X_all, y=None):
"""Subsample several time series. Parameters X_all : list(np.ndarray) List of feature time series Returns ------- features : ... |
if self._sliding_window:
return [X[k::self._lag_time] for k in range(self._lag_time) for X in X_all]
else:
return [X[::self._lag_time] for X in X_all] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterate_tracker(maxiter, max_nc, verbose=False):
"""Generator that breaks after maxiter, or after the same array has been sent in more max_nc times in a row.... |
last_hash = None
last_hash_count = 0
arr = yield
for i in xrange(maxiter):
arr = yield i
if arr is not None:
hsh = hashlib.sha1(arr.view(np.uint8)).hexdigest()
if last_hash == hsh:
last_hash_count += 1
else:
last_h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit(self, sequences, y=None):
"""Fit a PCCA lumping model using a sequence of cluster assignments. Parameters sequences : list(np.ndarray(dtype='int')) List ... |
super(PCCA, self).fit(sequences, y=y)
self._do_lumping()
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_lumping(self):
"""Do the PCCA lumping. Notes ------- 1. Iterate over the eigenvectors, starting with the slowest. 2. Calculate the spread of that eigenve... |
# Extract non-perron eigenvectors
right_eigenvectors = self.right_eigenvectors_[:, 1:]
assert self.n_states_ > 0
microstate_mapping = np.zeros(self.n_states_, dtype=int)
def spread(x):
return x.max() - x.min()
for i in range(self.n_macrostates - 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 metastability(alpha, T, right_eigenvectors, square_map, pi):
"""Return the metastability PCCA+ objective function. Parameters alpha : ndarray Parameters of o... |
num_micro, num_eigen = right_eigenvectors.shape
A, chi, mapping = calculate_fuzzy_chi(alpha, square_map,
right_eigenvectors)
# If current point is infeasible or leads to degenerate lumping.
if (len(np.unique(mapping)) != right_eigenvectors.shape[1] or
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crispness(alpha, T, right_eigenvectors, square_map, pi):
"""Return the crispness PCCA+ objective function. Parameters alpha : ndarray Parameters of objective... |
A, chi, mapping = calculate_fuzzy_chi(alpha, square_map,
right_eigenvectors)
# If current point is infeasible or leads to degenerate lumping.
if (len(np.unique(mapping)) != right_eigenvectors.shape[1] or
has_constraint_violation(A, right_eigenvectors)... |
<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_maps(A):
"""Get mappings from the square array A to the flat vector of parameters alpha. Helper function for PCCA+ optimization. Parameters A : ndarray T... |
N = A.shape[0]
flat_map = []
for i in range(1, N):
for j in range(1, N):
flat_map.append([i, j])
flat_map = np.array(flat_map)
square_map = np.zeros(A.shape, 'int')
for k in range((N - 1) ** 2):
i, j = flat_map[k]
square_map[i, j] = k
return flat_map... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_constraint_violation(A, right_eigenvectors, epsilon=1E-8):
"""Check for constraint violations in transformation matrix. Parameters A : ndarray The transf... |
lhs = 1 - A[0, 1:].sum()
rhs = dot(right_eigenvectors[:, 1:], A[1:, 0])
rhs = -1 * rhs.min()
if abs(lhs - rhs) > epsilon:
return True
else:
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 index_search(right_eigenvectors):
"""Find simplex structure in eigenvectors to begin PCCA+. Parameters right_eigenvectors : ndarray Right eigenvectors of tra... |
num_micro, num_eigen = right_eigenvectors.shape
index = np.zeros(num_eigen, 'int')
# first vertex: row with largest norm
index[0] = np.argmax(
[norm(right_eigenvectors[i]) for i in range(num_micro)])
ortho_sys = right_eigenvectors - np.outer(np.ones(num_micro),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fill_A(A, right_eigenvectors):
"""Construct feasible initial guess for transformation matrix A. Parameters A : ndarray Possibly non-feasible transformation m... |
num_micro, num_eigen = right_eigenvectors.shape
A = A.copy()
# compute 1st column of A by row sum condition
A[1:, 0] = -1 * A[1:, 1:].sum(1)
# compute 1st row of A by maximum condition
A[0] = -1 * dot(right_eigenvectors[:, 1:].real, A[1:]).min(0)
# rescale A to be in the feasible set
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_lumping(self):
"""Perform PCCA+ algorithm by optimizing transformation matrix A. Creates the following member variables: ------- A : ndarray The transfor... |
right_eigenvectors = self.right_eigenvectors_[:, :self.n_macrostates]
index = index_search(right_eigenvectors)
# compute transformation matrix A as initial guess for local
# optimization (maybe not feasible)
A = right_eigenvectors[index, :]
A = inv(A)
A = fill_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _optimize_A(self, A):
"""Find optimal transformation matrix A by minimization. Parameters A : ndarray The transformation matrix A. Returns ------- A : ndarra... |
right_eigenvectors = self.right_eigenvectors_[:, :self.n_macrostates]
flat_map, square_map = get_maps(A)
alpha = to_flat(1.0 * A, flat_map)
def obj(x):
return -1 * self._objective_function(
x, self.transmat_, right_eigenvectors, square_map,
... |
<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_msm_eigensystem(transmat, k):
"""Find the dominant eigenpairs of an MSM transition matrix Parameters transmat : np.ndarray, shape=(n_states, n_states)... |
u, lv, rv = scipy.linalg.eig(transmat, left=True, right=True)
order = np.argsort(-np.real(u))
u = np.real_if_close(u[order[:k]])
lv = np.real_if_close(lv[:, order[:k]])
rv = np.real_if_close(rv[:, order[:k]])
return _normalize_eigensystem(u, lv, rv) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _normalize_eigensystem(u, lv, rv):
"""Normalize the eigenvectors of a reversible Markov state model according to our preferred scheme. """ |
# first normalize the stationary distribution separately
lv[:, 0] = lv[:, 0] / np.sum(lv[:, 0])
for i in range(1, lv.shape[1]):
# the remaining left eigenvectors to satisfy
# <\phi_i, \phi_i>_{\mu^{-1}} = 1
lv[:, i] = lv[:, i] / np.sqrt(np.dot(lv[:, i], lv[:, i] / lv[:, 0]))
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 _strongly_connected_subgraph(counts, weight=1, verbose=True):
"""Trim a transition count matrix down to its maximal strongly ergodic subgraph. From the count... |
n_states_input = counts.shape[0]
n_components, component_assignments = csgraph.connected_components(
csr_matrix(counts >= weight), connection="strong")
populations = np.array(counts.sum(0)).flatten()
component_pops = np.array([populations[component_assignments == i].sum() for
... |
<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_counts(sequences, lag_time=1, sliding_window=True):
"""Count the number of directed transitions in a collection of sequences in a discrete space.... |
if (not sliding_window) and lag_time > 1:
return _transition_counts([X[::lag_time] for X in sequences],
lag_time=1)
classes = np.unique(np.concatenate(sequences))
contains_nan = (classes.dtype.kind == 'f') and np.any(np.isnan(classes))
contains_none = any(c is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partial_transform(self, sequence, mode='clip'):
"""Transform a sequence to internal indexing Recall that `sequence` can be arbitrary labels, whereas ``transm... |
if mode not in ['clip', 'fill']:
raise ValueError('mode must be one of ["clip", "fill"]: %s' % mode)
sequence = np.asarray(sequence)
if sequence.ndim != 1:
raise ValueError("Each sequence must be 1D")
f = np.vectorize(lambda k: self.mapping_.get(k, np.nan),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, sequences, mode='clip'):
"""Transform a list of sequences to internal indexing Recall that `sequences` can be arbitrary labels, whereas ``tra... |
if mode not in ['clip', 'fill']:
raise ValueError('mode must be one of ["clip", "fill"]: %s' % mode)
sequences = list_of_1d(sequences)
result = []
for y in sequences:
if mode == 'fill':
result.append(self.partial_transform(y, mode))
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 _parse_ergodic_cutoff(self):
"""Get a numeric value from the ergodic_cutoff input, which can be 'on' or 'off'. """ |
ec_is_str = isinstance(self.ergodic_cutoff, str)
if ec_is_str and self.ergodic_cutoff.lower() == 'on':
if self.sliding_window:
return 1.0 / self.lag_time
else:
return 1.0
elif ec_is_str and self.ergodic_cutoff.lower() == 'off':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inverse_transform(self, sequences):
"""Transform a list of sequences from internal indexing into labels Parameters sequences : list List of sequences, each o... |
sequences = list_of_1d(sequences)
inverse_mapping = {v: k for k, v in self.mapping_.items()}
f = np.vectorize(inverse_mapping.get)
result = []
for y in sequences:
uq = np.unique(y)
if not np.all(np.logical_and(0 <= uq, uq < self.n_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 sample_discrete(self, state=None, n_steps=100, random_state=None):
r"""Generate a random sequence of states by propagating the model using discrete time step... |
random = check_random_state(random_state)
r = random.rand(1 + n_steps)
if state is None:
initial = np.sum(np.cumsum(self.populations_) < r[0])
elif hasattr(state, '__len__') and len(state) == self.n_states_:
initial = np.sum(np.cumsum(state) < r[0])
else... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_samples(self, sequences, n_samples, random_state=None):
"""Sample conformations for a sequences of states. Parameters sequences : list or list of lists ... |
if not any([isinstance(seq, collections.Iterable)
for seq in sequences]):
sequences = [sequences]
random = check_random_state(random_state)
selected_pairs_by_state = []
for state in range(self.n_states_):
all_frames = [np.where(a == state)[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 _do_lumping(self):
"""Do the MVCA lumping. """ |
model = LandmarkAgglomerative(linkage='ward',
n_clusters=self.n_macrostates,
metric=self.metric,
n_landmarks=self.n_landmarks,
landmark_strategy=self.landmark_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _truncate(self, x, k):
''' given a vector x, leave its top-k absolute-value entries alone, and set the rest to 0 '''
not_F = np.argsort(np.abs(x))[:-k]
x[not_F] = 0
return x |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _truncated_power_method(self, A, x0, k, max_iter=10000, thresh=1e-8):
'''
given a matrix A, an initial guess x0, and a maximum cardinality k,
find the best k-sparse approximation to its dominant eigenvector
References
----------
[1] Yuan, X-T. and Zhang, T. "Truncate... |
<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):
"""Do the APM lumping. """ |
# print("Doing APM Clustering...")
# Start looping for maxIter times
n_macrostates = 1 # initialized as 1 because no macrostate exist in loop 0
metaQ = -1.0
prevQ = -1.0
global_maxQ = -1.0
local_maxQ = -1.0
for iter in range(self.max_iter):
s... |
<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_atompair_indices(reference_traj, keep_atoms=None, exclude_atoms=None, reject_bonded=True):
"""Get a list of acceptable atom pairs. Parameters reference_t... |
if keep_atoms is None:
keep_atoms = ATOM_NAMES
top, bonds = reference_traj.top.to_dataframe()
if keep_atoms is not None:
atom_indices = top[top.name.isin(keep_atoms) == True].index.values
if exclude_atoms is not None:
atom_indices = top[top.name.isin(exclude_atoms) == 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 sample_dimension(trajs, dimension, n_frames, scheme="linear"):
"""Sample a dimension of the data. This method uses one of 3 schemes. All other dimensions are... |
fixed_indices = list(trajs.keys())
trajs = [trajs[k][:, [dimension]] for k in fixed_indices]
txx = np.concatenate([traj[:,0] for traj in trajs])
if scheme == "linear":
spaced_points = np.linspace(np.min(txx), np.max(txx), n_frames)
spaced_points = spaced_points[:, np.newaxis]
elif ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit(self, X, y=None):
"""Fit the grid Parameters X : array-like, shape = [n_samples, n_features] Data points Returns ------- self """ |
X = array2d(X)
self.n_features = X.shape[1]
self.n_bins = self.n_bins_per_feature ** self.n_features
if self.min is None:
min = np.min(X, axis=0)
elif isinstance(self.min, numbers.Number):
min = self.min * np.ones(self.n_features)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict(self, X):
"""Get the index of the grid cell containing each sample in X Parameters X : array-like, shape = [n_samples, n_features] New data Returns -... |
if np.any(X < self.grid[:, 0]) or np.any(X > self.grid[:, -1]):
raise ValueError('data out of min/max bounds')
binassign = np.zeros((self.n_features, len(X)), dtype=int)
for i in range(self.n_features):
binassign[i] = np.digitize(X[:, i], self.grid[i]) - 1
labe... |
<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_same_length(self, trajs_tuple):
"""Check that the datasets are the same length""" |
lens = [len(trajs) for trajs in trajs_tuple]
if len(set(lens)) > 1:
err = "Each dataset must be the same length. You gave: {}"
err = err.format(lens)
raise ValueError(err) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, trajs_tuple, y=None):
"""Featurize a several trajectories. Parameters traj_list : list(mdtraj.Trajectory) Trajectories to be featurized. Retu... |
return [self.partial_transform(traj_zip)
for traj_zip in zip(*trajs_tuple)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def backup(fn):
"""If ``fn`` exists, rename it and issue a warning This function will rename an existing filename {fn}.bak.{i} where i is the smallest integer th... |
if not os.path.exists(fn):
return
backnum = 1
backfmt = "{fn}.bak.{backnum}"
trial_fn = backfmt.format(fn=fn, backnum=backnum)
while os.path.exists(trial_fn):
backnum += 1
trial_fn = backfmt.format(fn=fn, backnum=backnum)
warnings.warn("{fn} exists. Moving it to {newfn... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_key_to_path(key, dfmt="{}", ffmt="{}.npy"):
"""Turn an arbitrary python object into a filename This uses string formatting, so make sure your keys ma... |
if isinstance(key, tuple):
paths = [dfmt.format(k) for k in key[:-1]]
paths += [ffmt.format(key[-1])]
return os.path.join(*paths)
else:
return ffmt.format(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preload_tops(meta):
"""Load all topology files into memory. This might save some performance compared to re-parsing the topology file for each trajectory you... |
top_fns = set(meta['top_fn'])
tops = {}
for tfn in top_fns:
tops[tfn] = md.load_topology(tfn)
return tops |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preload_top(meta):
"""Load one topology file into memory. This function checks to make sure there's only one topology file in play. When sampling frames, you... |
top_fns = set(meta['top_fn'])
if len(top_fns) != 1:
raise ValueError("More than one topology is used in this project!")
return md.load_topology(top_fns.pop()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def itertrajs(meta, stride=1):
"""Load one mdtraj trajectory at a time and yield it. MDTraj does striding badly. It reads in the whole trajectory and then perfor... |
tops = preload_tops(meta)
for i, row in meta.iterrows():
yield i, md.join(md.iterload(row['traj_fn'],
top=tops[row['top_fn']],
stride=stride),
discard_overlapping_frames=False,
c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_meta(meta, fn="meta.pandas.html", title="Project Metadata - MSMBuilder", pandas_kwargs=None):
"""Render a metadata dataframe as an html webpage for in... |
if pandas_kwargs is None:
pandas_kwargs = {}
kwargs_with_defaults = {
'classes': ('table', 'table-condensed', 'table-hover'),
}
kwargs_with_defaults.update(**pandas_kwargs)
env = Environment(loader=PackageLoader('msmbuilder', 'io_templates'))
templ = env.get_template("twitter-... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_generic(obj, fn):
"""Save Python objects, including msmbuilder Estimators. This is a convenience wrapper around Python's ``pickle`` serialization scheme... |
backup(fn)
with open(fn, 'wb') as f:
pickle.dump(obj, 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 save_trajs(trajs, fn, meta, key_to_path=None):
"""Save trajectory-like data Data is stored in individual numpy binary files in the directory given by ``fn``.... |
if key_to_path is None:
key_to_path = default_key_to_path
validate_keys(meta.index, key_to_path)
backup(fn)
os.mkdir(fn)
for k in meta.index:
v = trajs[k]
npy_fn = os.path.join(fn, key_to_path(k))
os.makedirs(os.path.dirname(npy_fn), exist_ok=True)
np.save(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 load_trajs(fn, meta='meta.pandas.pickl', key_to_path=None):
"""Load trajectory-like data Data is expected to be stored as if saved by ``save_trajs``. This me... |
if key_to_path is None:
key_to_path = default_key_to_path
if isinstance(meta, str):
meta = load_meta(meta_fn=meta)
trajs = {}
for k in meta.index:
trajs[k] = np.load(os.path.join(fn, key_to_path(k)))
return meta, 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 query(self, x, k=1, p=2, distance_upper_bound=np.inf):
"""Query the kd-tree for nearest neighbors Parameters x : array_like, last dimension self.m An array o... |
cdists, cinds = self._kdtree.query(x, k, p, distance_upper_bound)
return cdists, self._split_indices(cinds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform(self, sequences):
"""Apply dimensionality reduction to sequences Parameters sequences: list of array-like, each of shape (n_samples_i, n_features) ... |
check_iter_of_sequences(sequences)
transforms = []
for X in sequences:
transforms.append(self.partial_transform(X))
return transforms |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_transform(self, sequences, y=None):
"""Fit the model and apply dimensionality reduction Parameters sequences: list of array-like, each of shape (n_sample... |
self.fit(sequences)
transforms = self.transform(sequences)
return transforms |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit(self, sequences, y=None):
"""Fit the clustering on the data Parameters sequences : list of array-like, each of shape [sequence_length, n_features] A list... |
check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)
super(MultiSequenceClusterMixin, self).fit(self._concat(sequences))
if hasattr(self, 'labels_'):
self.labels_ = self._split(self.labels_)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict(self, sequences, y=None):
"""Predict the closest cluster each sample in each sequence in sequences belongs to. In the vector quantization literature,... |
predictions = []
check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)
for X in sequences:
predictions.append(self.partial_predict(X))
return predictions |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fit_predict(self, sequences, y=None):
"""Performs clustering on X and returns cluster labels. Parameters sequences : list of array-like, each of shape [seque... |
if hasattr(super(MultiSequenceClusterMixin, self), 'fit_predict'):
check_iter_of_sequences(sequences, allow_trajectory=self._allow_trajectory)
labels = super(MultiSequenceClusterMixin, self).fit_predict(sequences)
else:
self.fit(sequences)
labels = self.p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(self, minx=-1.5, maxx=1.2, miny=-0.2, maxy=2, **kwargs):
"""Helper function to plot the Muller potential """ |
import matplotlib.pyplot as pp
grid_width = max(maxx-minx, maxy-miny) / 200.0
ax = kwargs.pop('ax', None)
xx, yy = np.mgrid[minx:maxx:grid_width, miny:maxy:grid_width]
V = self.potential(xx, yy)
# clip off any values greater than 200, since they mess up
# the c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gather_metadata(fn_glob, parser):
"""Given a glob and a parser object, create a metadata dataframe. Parameters fn_glob : str Glob string to find trajectory f... |
meta = pd.DataFrame(parser.parse_fn(fn) for fn in glob.iglob(fn_glob))
return meta.set_index(parser.index).sort_index() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def eigtransform(self, sequences, right=True, mode='clip'):
r"""Transform a list of sequences by projecting the sequences onto the first `n_timescales` dynamical... |
result = []
for y in self.transform(sequences, mode=mode):
if right:
op = self.right_eigenvectors_[:, 1:]
else:
op = self.left_eigenvectors_[:, 1:]
is_finite = np.isfinite(y)
if not np.all(is_finite):
valu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def score_ll(self, sequences):
r"""log of the likelihood of sequences with respect to the model Parameters sequences : list of array-like List of sequences, or a... |
counts, mapping = _transition_counts(sequences)
if not set(self.mapping_.keys()).issuperset(mapping.keys()):
return -np.inf
inverse_mapping = {v: k for k, v in mapping.items()}
# maps indices in counts to indices in transmat
m2 = _dict_compose(inverse_mapping, self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summarize(self):
"""Return some diagnostic summary statistics about this Markov model """ |
doc = '''Markov state model
------------------
Lag time : {lag_time}
Reversible type : {reversible_type}
Ergodic cutoff : {ergodic_cutoff}
Prior counts : {prior_counts}
Number of states : {n_states}
Number of nonzero entries in counts matrix : {counts_nz} ({percent_counts_nz}%)
Nonzero counts ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timescales_(self):
"""Implied relaxation timescales of the model. The relaxation of any initial distribution towards equilibrium is given, according to this ... |
u, lv, rv = self._get_eigensystem()
# make sure to leave off equilibrium distribution
with np.errstate(invalid='ignore', divide='ignore'):
timescales = - self.lag_time / np.log(u[1:])
return timescales |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uncertainty_eigenvalues(self):
"""Estimate of the element-wise asymptotic standard deviation in the model eigenvalues. Returns ------- sigma_eigs : np.array,... |
if self.reversible_type is None:
raise NotImplementedError('reversible_type must be "mle" or "transpose"')
n_timescales = min(self.n_timescales if self.n_timescales is not None
else self.n_states_ - 1, self.n_states_ - 1)
u, lv, rv = self._get_eigensyste... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uncertainty_timescales(self):
"""Estimate of the element-wise asymptotic standard deviation in the model implied timescales. Returns ------- sigma_timescales... |
# drop the first eigenvalue
u = self.eigenvalues_[1:]
sigma_eigs = self.uncertainty_eigenvalues()[1:]
sigma_ts = sigma_eigs / (u * np.log(u)**2)
return sigma_ts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_features(self, traj):
""" Return a list of dictionaries describing the features. Follows the ordering of featurizers in self.which_feat. Parameters ... |
all_res = []
for feat in self.which_feat:
all_res.extend(self.features[feat].describe_features(traj))
return all_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 partial_transform(self, sequence):
"""Apply preprocessing to single sequence Parameters sequence: array like, shape (n_samples, n_features) A single sequence... |
s = super(MultiSequencePreprocessingMixin, self)
return s.transform(sequence) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def retry(max_retries=1):
""" Retry a function `max_retries` times. """ |
def retry_func(func):
@wraps(func)
def wrapper(*args, **kwargs):
num_retries = 0
while num_retries <= max_retries:
try:
ret = func(*args, **kwargs)
break
except HTTPError:
if num_ret... |
<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_data_home(data_home=None):
"""Return the path of the msmbuilder data dir. As of msmbuilder v3.6, this function will prefer data downloaded via the msmb_d... |
if data_home is not None:
return _expand_and_makedir(data_home)
msmb_data = has_msmb_data()
if msmb_data is not None:
return _expand_and_makedir(msmb_data)
data_home = environ.get('MSMBUILDER_DATA', join('~', 'msmbuilder_data'))
return _expand_and_makedir(data_home) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def description(cls):
"""Get a description from the Notes section of the docstring.""" |
lines = [s.strip() for s in cls.__doc__.splitlines()]
note_i = lines.index("Notes")
return "\n".join(lines[note_i + 2:]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wildcard_allowed_actions(self, pattern=None):
""" Find statements which allow wildcard actions. A pattern can be specified for the wildcard action """ |
wildcard_allowed = []
for statement in self.statements:
if statement.wildcard_actions(pattern) and statement.effect == "Allow":
wildcard_allowed.append(statement)
return wildcard_allowed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wildcard_allowed_principals(self, pattern=None):
""" Find statements which allow wildcard principals. A pattern can be specified for the wildcard principal "... |
wildcard_allowed = []
for statement in self.statements:
if statement.wildcard_principals(pattern) and statement.effect == "Allow":
wildcard_allowed.append(statement)
return wildcard_allowed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nonwhitelisted_allowed_principals(self, whitelist=None):
"""Find non whitelisted allowed principals.""" |
if not whitelist:
return []
nonwhitelisted = []
for statement in self.statements:
if statement.non_whitelisted_principals(whitelist) and statement.effect == "Allow":
nonwhitelisted.append(statement)
return nonwhitelisted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allows_not_principal(self):
"""Find allowed not-principals.""" |
not_principals = []
for statement in self.statements:
if statement.not_principal and statement.effect == "Allow":
not_principals.append(statement)
return not_principals |
<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_parameters(self, parameters):
"""Parses and sets parameters in the model.""" |
self.parameters = []
for param_name, param_value in parameters.items():
p = Parameter(param_name, param_value)
if p:
self.parameters.append(p) |
<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_resources(self, resources):
"""Parses and sets resources in the model using a factory.""" |
self.resources = {}
resource_factory = ResourceFactory()
for res_id, res_value in resources.items():
r = resource_factory.create_resource(res_id, res_value)
if r:
if r.resource_type in self.resources:
self.resources[r.resource_type].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 session(self):
""" Get session object to benefit from connection pooling. http://docs.python-requests.org/en/master/user/advanced/#session-objects :rtype: re... |
if self._session is None:
self._session = requests.Session()
self._session.headers.update(self._headers)
return self._session |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_id_connect(self, client_id, client_secret):
""" Get OpenID Connect client :param str client_id: :param str client_secret: :rtype: keycloak.openid_connec... |
return KeycloakOpenidConnect(realm=self, client_id=client_id,
client_secret=client_secret) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, username, **kwargs):
""" Create a user in Keycloak http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource :param str username:... |
payload = OrderedDict(username=username)
for key in USER_KWARGS:
from keycloak.admin.clientroles import to_camel_case
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
return self._client.post(
url=self._client.get_full_url(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self):
""" Return all registered users http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource """ |
return self._client.get(
url=self._client.get_full_url(
self.get_path('collection', realm=self._realm_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 get(self):
""" Return registered user with the given user id. http://www.keycloak.org/docs-api/3.4/rest-api/index.html#_users_resource """ |
self._user = self._client.get(
url=self._client.get_full_url(
self.get_path(
'single', realm=self._realm_name, user_id=self._user_id
)
)
)
self._user_id = self.user["id"]
return self._user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, **kwargs):
""" Update existing user. https://www.keycloak.org/docs-api/2.5/rest-api/index.html#_userrepresentation :param str first_name: first_... |
payload = {}
for k, v in self.user.items():
payload[k] = v
for key in USER_KWARGS:
from keycloak.admin.clientroles import to_camel_case
if key in kwargs:
payload[to_camel_case(key)] = kwargs[key]
result = self._client.put(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_set_create(self, token, name, **kwargs):
""" Create a resource set. https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#rfc.se... |
return self._realm.client.post(
self.well_known['resource_registration_endpoint'],
data=self._get_data(name=name, **kwargs),
headers=self.get_headers(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 resource_set_update(self, token, id, name, **kwargs):
""" Update a resource set. https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#up... |
return self._realm.client.put(
'{}/{}'.format(
self.well_known['resource_registration_endpoint'], id),
data=self._get_data(name=name, **kwargs),
headers=self.get_headers(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 resource_set_read(self, token, id):
""" Read a resource set. https://docs.kantarainitiative.org/uma/rec-oauth-resource-reg-v1_0_1.html#read-resource-set :par... |
return self._realm.client.get(
'{}/{}'.format(
self.well_known['resource_registration_endpoint'], id),
headers=self.get_headers(token)
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.