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 the default prior to msmbuilder v3.2 Parameters filename : string The name of the file to load. """ |
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: {}\n"
"Joblib: {}".format(filename, e1, e2)
) |
<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 of unfolded/reactant states. sinks : array_like, int The set of folded/product states. msm : msmbuilder.MarkovStateModel MSM fit to data. for_committors : np.ndarray, optional The forward committors associated with `sources`, `sinks`, and `tprob`. If not provided, is calculated from scratch. If provided, `sources` and `sinks` are ignored. Returns ------- net_flux : np.ndarray The net flux matrix See Also -------- fluxes References .. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of transition paths. J. Stat. Phys. 123, 503-523 (2006). .. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E. Transition path theory for Markov jump processes. Multiscale Model. Simul. 7, 1192-1219 (2009). .. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive flux and folding pathways in network models of coarse-grained protein dynamics. J. Chem. Phys. 130, 205102 (2009). .. [4] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016. """ |
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 List of paths to MD trajectory files featurizer : Featurizer The featurizer to be invoked on each trajectory trajectory as it is loaded topology : str, Topology, Trajectory Topology or path to a topology file, used to load trajectories with MDTraj chunk : {int, None} If chunk is an int, load the trajectories up in chunks using md.iterload for better memory efficiency (less trajectory data needs to be in memory at once) stride : int, default=1 Only read every stride-th frame. Returns ------- data : np.ndarray, shape=(total_length_of_all_trajectories, n_features) indices : np.ndarray, shape=(total_length_of_all_trajectories) fns : np.ndarray shape=(total_length_of_all_trajectories) These three arrays all share the same indexing, such that data[i] is the featurized version of indices[i]-th frame in the MD trajectory with filename fns[i]. """ |
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)
data.append(x)
indices.append(count + (stride * np.arange(n_frames)))
fns.extend([file] * n_frames)
count += (stride * n_frames)
if len(data) == 0:
raise ValueError("None!")
return np.concatenate(data), np.concatenate(indices), np.array(fns) |
<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 : list of dict Dictionary describing each feature with the following information about the atoms participating in each feature - resnames: unique names of residues - atominds: the four atom indicies - resseqs: unique residue sequence ids (not necessarily 0-indexed) - resids: unique residue ids (0-indexed) - featurizer: Featurizer name - featuregroup: Other information Notes ------- Method resorts to returning N/A for everything if describe_features in not implemented in the sub_class """ |
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 describe Returns ------- feature_descs : list of dict Dictionary describing each feature with the following information about the atoms participating in each feature - resnames: unique names of residues - atominds: the four atom indicies - resseqs: unique residue sequence ids (not necessarily 0-indexed) - resids: unique residue ids (0-indexed) - featurizer: Alpha Angle - featuregroup: the type of dihedral angle and whether sin or cos has been applied. """ |
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 = itertools.product(["LandMarkFeaturizer"], ["RMSD"], [self.sigma], zippy)
feature_descs.extend(dict_maker(zippy))
return feature_descs |
<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 molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. See Also -------- transform : simultaneously featurize a collection of MD trajectories """ |
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 describe Returns ------- feature_descs : list of dict Dictionary describing each feature with the following information about the atoms participating in each dihedral - resnames: unique names of residues - atominds: the two atom inds - resseqs: unique residue sequence ids (not necessarily 0-indexed) - resids: unique residue ids (0-indexed) - featurizer: AtomPairsFeaturizer - featuregroup: Distance. - other info : Value of the exponent """ |
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):
aind += [[i for i in self.atom_indices[ind]]]
resseqs += [[top.residue(ri).resSeq for ri in resid_ids]]
resnames += [[top.residue(ri).name for ri in resid_ids]]
zippy = itertools.product(["AtomPairs"], ["Distance"],
["Exponent {}".format(self.exponent)],
zip(aind, resseqs, residue_indices, resnames))
feature_descs.extend(dict_maker(zippy))
return feature_descs |
<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 : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. See Also -------- transform : simultaneously featurize a collection of MD trajectories """ |
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 goes over the columns first. This should put the results
#phi dihedrals(all bin0 then all bin1), psi dihedrals(all_bin1)
x.extend(np.reshape(res, (1, -1, self.n_bins*y.shape[1]), order='F'))
return np.hstack(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):
"""Return a list of dictionaries describing the SASA features. Parameters traj : mdtraj.Trajectory The trajectory to describe Returns ------- feature_descs : list of dict Dictionary describing each feature with the following information about the atoms participating in each SASA feature - resnames: names of residues - atominds: atom index or atom indices in mode="residue" - resseqs: residue ids (not necessarily 0-indexed) - resids: unique residue ids (0-indexed) - featurizer: SASA - featuregroup: atom or residue """ |
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.residue(ri).name for ri in resids]
atoms_in_res = [res.atoms for res in top.residues]
aind_tuples = []
# For each resdiue...
for i,x in enumerate(atoms_in_res):
# For each atom in the residues, append it's index
aind_tuples.append([atom.index for atom in x])
zippy = itertools.product(['SASA'],['N/A'],[self.mode], zip(aind_tuples, resseqs, resids, resnames))
else:
resids = [top.atom(ai).residue.index for ai in mapping]
resseqs = [top.atom(ai).residue.resSeq for ai in mapping]
resnames = [top.atom(ai).residue.name for ai in mapping]
zippy = itertools.product(['SASA'],['N/A'],[self.mode], zip(mapping, resseqs, resids, resnames))
feature_descs.extend(dict_maker(zippy))
return feature_descs |
<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 A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. See Also -------- transform : simultaneously featurize a collection of MD trajectories """ |
# 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
# molecules
atom_pairs[:, 0] = solute_i
atom_pairs[:, 1] = self.solvent_indices
distances = md.compute_distances(traj, atom_pairs, periodic=True)
distances = np.exp(-distances / (2 * sigma * sigma))
# Sum over water atoms for all frames
fingerprints[:, i] = np.sum(distances, axis=1)
return fingerprints |
<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 molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. Notes ----- If you requested superposition (gave `ref_traj` in __init__) the input trajectory will be modified. See Also -------- transform : simultaneously featurize a collection of MD trajectories """ |
# 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_traj, parallel=False)
# Get the positions and reshape.
value = p_traj.xyz.reshape(len(p_traj), -1)
return value |
<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) A sample to slice. Returns ------- sliced_traj : np.ndarray shape=(n_samples, n_feature_subset) Slice of traj """ |
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.BaseEstimator An *instance* of an estimator to be used to fit data. sequences : list of array-like List of sequences, or a single sequence. Each sequence should be a 1D iterable of state labels. Labels can be integers, strings, or other orderable objects. param_grid : dict or sklearn.grid_search.ParameterGrid Parameter grid to specify models to fit. See sklearn.grid_search.ParameterGrid for an explanation n_jobs : int, optional Number of jobs to run in parallel using joblib.Parallel Returns ------- models : list List of models fit to the data according to param_grid """ |
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), sequences)
for params in param_grid)
models = Parallel(n_jobs=n_jobs, verbose=verbose)(
delayed(_param_sweep_helper)(args) for args in iter_args)
return models |
<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 sequences on disk. This function can also be used as a context manager. Parameters path : str The path to the dataset on the filesystem mode : {'r', 'w', 'a'} Open a dataset for reading, writing, or appending. Note that some formats only support a subset of these modes. fmt : {'dir-npy', 'hdf5', 'mdtraj'} The format of the data on disk ``dir-npy`` A directory of binary numpy files, one file per sequence ``hdf5`` A single hdf5 file with each sequence as an array node ``mdtraj`` A read-only set of trajectory files that can be loaded with mdtraj verbose : bool Whether to print information about the dataset """ |
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 MDTrajDataset(path, mode=mode, verbose=verbose, **kwargs)
elif fmt == 'hdf5':
return HDF5Dataset(path, mode=mode, verbose=verbose)
elif fmt.endswith("-union"):
raise ValueError("union datasets have been removed. "
"Please use msmbuilder.featurizer.FeatureUnion")
else:
raise NotImplementedError("Unknown format fmt='%s'" % 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 transform_with(self, estimator, out_ds, fmt=None):
"""Call the partial_transform method of the estimator on this dataset Parameters estimator : object with ``partial_fit`` method This object will be used to transform this dataset into a new dataset. The estimator should be fitted prior to calling this method. out_ds : str or Dataset This dataset will be transformed and saved into out_ds. If out_ds is a path, a new dataset will be created at that path. fmt : str The type of dataset to create if out_ds is a string. Returns ------- out_ds : Dataset The tranformed dataset. """ |
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 existing dataset."
raise ValueError(err)
for key in self.keys():
out_ds[key] = estimator.partial_transform(self[key])
return out_ds |
<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 each trajectory will be transformed by the estimator. Parameters estimator : BaseEstimator This object will be fit and used to transform this dataset into a new dataset. out_ds : str or Dataset This dataset will be transformed and saved into out_ds. If out_ds is a path, a new dataset will be created at that path. fmt : str The type of dataset to create if out_ds is a string. Returns ------- out_ds : Dataset The transformed dataset. Examples -------- diheds = dataset("diheds") tica = diheds.fit_transform_with(tICA(), 'tica') kmeans = tica.fit_transform_with(KMeans(), 'kmeans') msm = kmeans.fit_with(MarkovStateModel()) """ |
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 present. """ |
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_mapped]
except:
pass
return return_vect |
<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. Parameters sources : array_like, int One-dimensional list of nodes to define the source states. sinks : array_like, int One-dimensional list of nodes to define the sink states. net_flux : np.ndarray, shape = [n_states, n_states] Net flux of the MSM Returns ------- top_path : np.ndarray Array corresponding to the top path between sources and sinks. It is an array of states visited along the path. flux : float Flux traveling through this path -- this is equal to the minimum flux over edges in the path. See Also -------- msmbuilder.tpt.paths : function for calculating many high flux paths through a network. References .. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of transition paths. J. Stat. Phys. 123, 503-523 (2006). .. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E. Transition path theory for Markov jump processes. Multiscale Model. Simul. 7, 1192-1219 (2009). .. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive flux and folding pathways in network models of coarse-grained protein dynamics. J. Chem. Phys. 130, 205102 (2009). .. [4] Dijkstra, E. W. A Note on Two Problems in Connexion with Graphs. Numeriche Mathematik 1, 269-271 (1959). .. [5] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016. """ |
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).astype(np.bool)
# have we already checked this node?
previous_node = np.ones(n_states).astype(np.int) * -1
# what node was found before finding this one
min_fluxes = np.ones(n_states) * -1 * np.inf
# what is the flux of the highest flux path
# from this node to the source set.
min_fluxes[sources] = np.inf
# source states are connected to the source
# so this distance is zero which means the flux is infinite
while len(queue) > 0: # iterate until there's nothing to check anymore
test_node = queue.pop(min_fluxes[queue].argmax())
# find the node in the queue that has the
# highest flux path to it from the source set
visited[test_node] = True
if np.all(visited[sinks]):
# if we've visited all of the sink states, then we just have to choose
# the path that goes to the sink state that is closest to the source
break
# if test_node in sinks: # I *think* we want to break ... or are there paths we still
# need to check?
# continue
# I think if sinks is more than one state we have to check everything
# now update the distances for each neighbor of the test_node:
neighbors = np.where(net_flux[test_node, :] > 0)[0]
if len(neighbors) == 0:
continue
new_fluxes = net_flux[test_node, neighbors].flatten()
# flux from test_node to each neighbor
new_fluxes[np.where(new_fluxes > min_fluxes[test_node])] = min_fluxes[test_node]
# previous step to get to test_node was lower flux, so that is still the path flux
ind = np.where((1 - visited[neighbors]) & (new_fluxes > min_fluxes[neighbors]))
min_fluxes[neighbors[ind]] = new_fluxes[ind]
previous_node[neighbors[ind]] = test_node
# each of these neighbors came from this test_node
# we don't want to update the nodes that have already been visited
queue.extend(neighbors[ind])
top_path = []
# populate the path in reverse
top_path.append(int(sinks[min_fluxes[sinks].argmax()]))
# find the closest sink state
while previous_node[top_path[-1]] != -1:
top_path.append(previous_node[top_path[-1]])
return np.array(top_path[::-1]), min_fluxes[top_path[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 _remove_bottleneck(net_flux, path):
""" Internal function for modifying the net flux matrix by removing a particular edge, corresponding to the bottleneck of a particular path. """ |
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()
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 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's algorithm. Parameters sources : array_like, int One-dimensional list of nodes to define the source states. sinks : array_like, int One-dimensional list of nodes to define the sink states. net_flux : np.ndarray Net flux of the MSM remove_path : str or callable, optional Function for removing a path from the net flux matrix. (if str, one of {'subtract', 'bottleneck'}) See note below for more details. num_paths : int, optional Number of paths to find flux_cutoff : float, optional Quit looking for paths once the explained flux is greater than this cutoff (as a percentage of the total). Returns ------- paths : list List of paths. Each item is an array of nodes visited in the path. fluxes : np.ndarray, shape = [n_paths,] Flux of each path returned. Notes ----- The Dijkstra algorithm only allows for computing the *single* top flux pathway through the net flux matrix. If we want many paths, there are many ways of finding the *second* highest flux pathway. The algorithm proceeds as follows: 1. Using the Djikstra algorithm, find the highest flux pathway from the sources to the sink states 2. Remove that pathway from the net flux matrix by some criterion 3. Repeat (1) with the modified net flux matrix Currently, there are two schemes for step (2):
- 'subtract' : Remove the path by subtracting the flux of the path from every edge in the path. This was suggested by Metzner, Schutte, and Vanden-Eijnden. Transition Path Theory for Markov Jump Processes. Multiscale Model. Simul. 7, 1192-1219 (2009). - 'bottleneck' : Remove the path by only removing the edge that corresponds to the bottleneck of the path. If a new scheme is desired, the user may pass a function that takes the net_flux and the path to remove and returns the new net flux matrix. See Also -------- msmbuilder.tpt.top_path : function for computing the single highest flux pathway through a network. References .. [1] Weinan, E. and Vanden-Eijnden, E. Towards a theory of transition paths. J. Stat. Phys. 123, 503-523 (2006). .. [2] Metzner, P., Schutte, C. & Vanden-Eijnden, E. Transition path theory for Markov jump processes. Multiscale Model. Simul. 7, 1192-1219 (2009). .. [3] Berezhkovskii, A., Hummer, G. & Szabo, A. Reactive flux and folding pathways in network models of coarse-grained protein dynamics. J. Chem. Phys. 130, 205102 (2009). .. [4] Dijkstra, E. W. A Note on Two Problems in Connexion with Graphs. Numeriche Mathematik 1, 269-271 (1959). .. [5] Noe, Frank, et al. "Constructing the equilibrium ensemble of folding pathways from short off-equilibrium simulations." PNAS 106.45 (2009):
19011-19016. """ |
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', 'bottleneck']" % str(remove_path))
net_flux = copy.copy(net_flux)
paths = []
fluxes = []
total_flux = net_flux[sources, :].sum()
# total flux is the total flux coming from the sources (or going into the sinks)
not_done = True
counter = 0
expl_flux = 0.0
while not_done:
path, flux = top_path(sources, sinks, net_flux)
if np.isinf(flux):
break
paths.append(path)
fluxes.append(flux)
expl_flux += flux / total_flux
counter += 1
if counter >= num_paths or expl_flux >= flux_cutoff:
break
# modify the net_flux matrix
net_flux = remove_path(net_flux, path)
fluxes = np.array(fluxes)
return paths, fluxes |
<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 covariance matrix (e.g. estimated with np.cov(X.T)) n : int Number of data points. Returns ------- sigma : array, shape=(n, n) shrinkage : float References .. [1] Chen, Yilun, Ami Wiesel, and Alfred O. Hero III. "Shrinkage estimation of high dimensional covariance matrices" ICASSP (2009) """ |
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() or partial_fit() will be cleared. For online learning, use `partial_fit`. Parameters sequences: list of array-like, each of shape (n_samples_i, n_features) Training data, where n_samples_i in the number of samples in sequence i and n_features is the number of features. y : None Ignored Returns ------- self : object Returns the instance itself. """ |
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' % self.lag_time)
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 transform(self, sequences):
"""Apply the dimensionality reduction on X. Parameters sequences: list of array-like, each of shape (n_samples_i, n_features) Training data, where n_samples_i in the number of samples in sequence i and n_features is the number of features. Returns ------- sequence_new : list of array-like, each of shape (n_samples_i, n_components) """ |
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 self.kinetic_mapping:
X_transformed *= self.eigenvalues_
if self.commute_mapping:
# thanks to @maxentile and @jchodera for providing/directing to a
# reference implementation in pyemma
#(markovmodel/PyEMMA#963)
# dampening smaller timescales based recommendtion of [7]
#
# some timescales are NaNs and regularized timescales will
# be negative when they are less than the lag time; all these
# are set to zero using nan_to_num before returning
regularized_timescales = 0.5 * self.timescales_ *\
np.tanh( np.pi *((self.timescales_ - self.lag_time)
/self.lag_time) + 1)
X_transformed *= np.sqrt(regularized_timescales / 2)
X_transformed = np.nan_to_num(X_transformed)
sequences_new.append(X_transformed)
return sequences_new |
<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 : list(np.ndarray), length = len(X_all) The subsampled trajectories. """ |
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_hash = hsh
last_hash_count = 1
if last_hash_count >= max_nc:
if verbose:
print('Termination. Over %d iterations without '
'change.' % max_nc)
break |
<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 of arrays of cluster assignments y : None Unused, present for sklearn compatibility only. Returns ------- self """ |
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 eigenvector within each existing macrostate. 3. Pick the macrostate with the largest eigenvector spread. 4. Split the macrostate based on the sign of the eigenvector. """ |
# 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):
v = right_eigenvectors[:, i]
all_spreads = np.array([spread(v[microstate_mapping == k])
for k in range(i + 1)])
state_to_split = np.argmax(all_spreads)
inds = ((microstate_mapping == state_to_split) &
(v >= self.pcca_tolerance))
microstate_mapping[inds] = i + 1
self.microstate_mapping_ = microstate_mapping |
<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 objective function (e.g. flattened A) T : csr sparse matrix Transition matrix right_eigenvectors : ndarray The right eigenvectors. square_map : ndarray Mapping from square indices (i,j) to flat indices (k). pi : ndarray Equilibrium Populations of transition matrix. Returns ------- obj : float The objective function Notes ------- metastability: try to make metastable fuzzy state decomposition. Defined in ref. [2]. """ |
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
has_constraint_violation(A, right_eigenvectors)):
return -1.0 * np.inf
obj = 0.0
# Calculate metastabilty of the lumped model. Eqn 4.20 in LAA.
for i in range(num_eigen):
obj += np.dot(T.dot(chi[:, i]), pi * chi[:, i]) / np.dot(chi[:, i], pi)
return obj |
<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 function (e.g. flattened A) T : csr sparse matrix Transition matrix right_eigenvectors : ndarray The right eigenvectors. square_map : ndarray Mapping from square indices (i,j) to flat indices (k). pi : ndarray Equilibrium Populations of transition matrix. Returns ------- obj : float The objective function Notes ------- Tries to make crisp state decompostion. This function is defined in [3]. """ |
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)):
return -1.0 * np.inf
obj = tr(dot(diag(1. / A[0]), dot(A.transpose(), A)))
return obj |
<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 The transformation matrix A. Returns ------- flat_map : ndarray Mapping from flat indices (k) to square (i,j) indices. square map : ndarray Mapping from square indices (i,j) to flat indices (k). """ |
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, 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 has_constraint_violation(A, right_eigenvectors, epsilon=1E-8):
"""Check for constraint violations in transformation matrix. Parameters A : ndarray The transformation matrix. right_eigenvectors : ndarray The right eigenvectors. epsilon : float, optional Tolerance of constraint violation. Returns ------- truth : bool Whether or not the violation exists Notes ------- Checks constraints using Eqn 4.25 in [1]. References .. [1] Deuflhard P, Weber, M., "Robust perron cluster analysis in conformation dynamics," Linear Algebra Appl., vol 398 pp 161-184 2005. """ |
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 transition matrix Returns ------- index : ndarray Indices of simplex """ |
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),
right_eigenvectors[index[0]])
for j in range(1, num_eigen):
temp = ortho_sys[index[j - 1]].copy()
for l in range(num_micro):
ortho_sys[l] -= temp * dot(ortho_sys[l], temp)
dist_list = np.array([norm(ortho_sys[l]) for l in range(num_micro)])
index[j] = np.argmax(dist_list)
ortho_sys /= dist_list.max()
return 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 fill_A(A, right_eigenvectors):
"""Construct feasible initial guess for transformation matrix A. Parameters A : ndarray Possibly non-feasible transformation matrix. right_eigenvectors : ndarray Right eigenvectors of transition matrix Returns ------- A : ndarray Feasible transformation matrix. """ |
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
A /= A[0].sum()
return 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 _do_lumping(self):
"""Perform PCCA+ algorithm by optimizing transformation matrix A. Creates the following member variables: ------- A : ndarray The transformation matrix. chi : ndarray The membership matrix microstate_mapping : ndarray Mapping from microstates to macrostates. """ |
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_A(A, right_eigenvectors)
if self.do_minimization:
A = self._optimize_A(A)
self.A_ = fill_A(A, right_eigenvectors)
self.chi_ = dot(right_eigenvectors, self.A_)
self.microstate_mapping_ = np.argmax(self.chi_, 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 _optimize_A(self, A):
"""Find optimal transformation matrix A by minimization. Parameters A : ndarray The transformation matrix A. Returns ------- A : ndarray The transformation matrix. """ |
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,
self.populations_
)
alpha = scipy.optimize.basinhopping(
obj, alpha, niter_success=1000,
)['x']
alpha = scipy.optimize.fmin(
obj, alpha, full_output=True, xtol=1E-4, ftol=1E-4,
maxfun=5000, maxiter=100000
)[0]
if np.isneginf(obj(alpha)):
raise ValueError(
"Error: minimization has not located a feasible point.")
A = to_square(alpha, square_map)
return 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 _solve_msm_eigensystem(transmat, k):
"""Find the dominant eigenpairs of an MSM transition matrix Parameters transmat : np.ndarray, shape=(n_states, n_states) The transition matrix k : int The number of eigenpairs to find. Notes ----- Normalize the left (:math:`\phi`) and right (:math:``\psi``) eigenfunctions according to the following criteria. * The first left eigenvector, \phi_1, _is_ the stationary distribution, and thus should be normalized to sum to 1. * The left-right eigenpairs should be biorthonormal: <\phi_i, \psi_j> = \delta_{ij} * The left eigenvectors should satisfy <\phi_i, \phi_i>_{\mu^{-1}} = 1 * The right eigenvectors should satisfy <\psi_i, \psi_i>_{\mu} = 1 Returns ------- eigvals : np.ndarray, shape=(k,) The largest `k` eigenvalues lv : np.ndarray, shape=(n_states, k) The normalized left eigenvectors (:math:`\phi`) of ``transmat`` rv : np.ndarray, shape=(n_states, k) The normalized right eigenvectors (:math:`\psi`) of ``transmat`` """ |
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]))
for i in range(rv.shape[1]):
# the right eigenvectors to satisfy <\phi_i, \psi_j> = \delta_{ij}
rv[:, i] = rv[:, i] / np.dot(lv[:, i], rv[:, i])
return 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 _strongly_connected_subgraph(counts, weight=1, verbose=True):
"""Trim a transition count matrix down to its maximal strongly ergodic subgraph. From the counts matrix, we define a graph where there exists a directed edge between two nodes, `i` and `j` if `counts[i][j] > weight`. We then find the nodes belonging to the largest strongly connected subgraph of this graph, and return a new counts matrix formed by these rows and columns of the input `counts` matrix. Parameters counts : np.array, shape=(n_states_in, n_states_in) Input set of directed counts. weight : float Threshold by which ergodicity is judged in the input data. Greater or equal to this many transition counts in both directions are required to include an edge in the ergodic subgraph. verbose : bool Print a short statement Returns ------- counts_component : "Trimmed" version of ``counts``, including only states in the maximal strongly ergodic subgraph. mapping : dict Mapping from "input" states indices to "output" state indices The semantics of ``mapping[i] = j`` is that state ``i`` from the "input space" for the counts matrix is represented by the index ``j`` in counts_component """ |
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
i in range(n_components)])
which_component = component_pops.argmax()
def cpop(which):
csum = component_pops.sum()
return 100 * component_pops[which] / csum if csum != 0 else np.nan
percent_retained = cpop(which_component)
if verbose:
print("MSM contains %d strongly connected component%s "
"above weight=%.2f. Component %d selected, with "
"population %f%%" % (
n_components, 's' if (n_components != 1) else '',
weight, which_component, percent_retained))
# keys are all of the "input states" which have a valid mapping to the output.
keys = np.arange(n_states_input)[component_assignments == which_component]
if n_components == n_states_input and counts[np.ix_(keys, keys)] == 0:
# if we have a completely disconnected graph with no self-transitions
return np.zeros((0, 0)), {}, percent_retained
# values are the "output" state that these guys are mapped to
values = np.arange(len(keys))
mapping = dict(zip(keys, values))
n_states_output = len(mapping)
trimmed_counts = np.zeros((n_states_output, n_states_output),
dtype=counts.dtype)
trimmed_counts[np.ix_(values, values)] = counts[np.ix_(keys, keys)]
return trimmed_counts, mapping, percent_retained |
<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. Parameters sequences : list of array-like List of sequences, or a single sequence. Each sequence should be a 1D iterable of state labels. Labels can be integers, strings, or other orderable objects. lag_time : int The time (index) delay for the counts. sliding_window : bool When lag_time > 1, consider *all* ``N = lag_time`` strided sequences starting from index be divided by ``N``. When this is False, only start from index 0. Returns ------- counts : array, shape=(n_states, n_states) ``counts[i][j]`` counts the number of times a sequences was in state `i` at time t, and state `j` at time `t+self.lag_time`, over the full set of trajectories. mapping : dict Mapping from the items in the sequences to the indices in ``(0, n_states-1)`` used for the count matrix. Examples -------- [[2, 1], [0, 1]] {0: 0, 1: 1} [[ 0. 1. 0.] [ 0. 0. 1.] [ 0. 0. 0.]] {100: 0, 200: 1, 300: 2} Notes ----- `None` and `NaN` are recognized immediately as invalid labels. Therefore, transition counts from or to a sequence item which is NaN or None will not be counted. The mapping return value will not include the NaN or None. """ |
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 None for c in classes)
if contains_nan:
classes = classes[~np.isnan(classes)]
if contains_none:
classes = [c for c in classes if c is not None]
n_states = len(classes)
mapping = dict(zip(classes, range(n_states)))
mapping_is_identity = (not contains_nan
and not contains_none
and classes.dtype.kind == 'i'
and np.all(classes == np.arange(n_states)))
mapping_fn = np.vectorize(mapping.get, otypes=[np.int])
none_to_nan = np.vectorize(lambda x: np.nan if x is None else x,
otypes=[np.float])
counts = np.zeros((n_states, n_states), dtype=float)
_transitions = []
for y in sequences:
y = np.asarray(y)
from_states = y[: -lag_time: 1]
to_states = y[lag_time::1]
if contains_none:
from_states = none_to_nan(from_states)
to_states = none_to_nan(to_states)
if contains_nan or contains_none:
# mask out nan in either from_states or to_states
mask = ~(np.isnan(from_states) + np.isnan(to_states))
from_states = from_states[mask]
to_states = to_states[mask]
if (not mapping_is_identity) and len(from_states) > 0 and len(
to_states) > 0:
from_states = mapping_fn(from_states)
to_states = mapping_fn(to_states)
_transitions.append(np.row_stack((from_states, to_states)))
transitions = np.hstack(_transitions)
C = coo_matrix((np.ones(transitions.shape[1], dtype=int), transitions),
shape=(n_states, n_states))
counts = counts + np.asarray(C.todense())
# If sliding window is False, this function will be called recursively
# with strided trajectories and lag_time = 1, which gives the desired
# number of counts. If sliding window is True, the counts are divided
# by the "number of windows" (i.e. the lag_time). Count magnitudes
# will be comparable between sliding-window and non-sliding-window cases.
# If lag_time = 1, sliding_window makes no difference.
counts /= float(lag_time)
return counts, mapping |
<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 ``transmat_`` and ``countsmat_`` are indexed with integers between 0 and ``n_states - 1``. This methods maps a set of sequences from the labels onto this internal indexing. Parameters sequence : array-like A 1D iterable of state labels. Labels can be integers, strings, or other orderable objects. mode : {'clip', 'fill'} Method by which to treat labels in `sequence` which do not have a corresponding index. This can be due, for example, to the ergodic trimming step. ``clip`` Unmapped labels are removed during transform. If they occur at the beginning or end of a sequence, the resulting transformed sequence will be shorted. If they occur in the middle of a sequence, that sequence will be broken into two (or more) sequences. (Default) ``fill`` Unmapped labels will be replaced with NaN, to signal missing data. [The use of NaN to signal missing data is not fantastic, but it's consistent with current behavior of the ``pandas`` library.] Returns ------- mapped_sequence : list or ndarray If mode is "fill", return an ndarray in internal indexing. If mode is "clip", return a list of ndarrays each in internal indexing. """ |
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),
otypes=[np.float])
a = f(sequence)
if mode == 'fill':
if np.all(np.mod(a, 1) == 0):
result = a.astype(int)
else:
result = a
elif mode == 'clip':
result = [a[s].astype(int) for s in
np.ma.clump_unmasked(np.ma.masked_invalid(a))]
else:
raise RuntimeError()
return result |
<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 ``transmat_`` and ``countsmat_`` are indexed with integers between 0 and ``n_states - 1``. This methods maps a set of sequences from the labels onto this internal indexing. Parameters sequences : list of array-like List of sequences, or a single sequence. Each sequence should be a 1D iterable of state labels. Labels can be integers, strings, or other orderable objects. mode : {'clip', 'fill'} Method by which to treat labels in `sequences` which do not have a corresponding index. This can be due, for example, to the ergodic trimming step. ``clip`` Unmapped labels are removed during transform. If they occur at the beginning or end of a sequence, the resulting transformed sequence will be shorted. If they occur in the middle of a sequence, that sequence will be broken into two (or more) sequences. (Default) ``fill`` Unmapped labels will be replaced with NaN, to signal missing data. [The use of NaN to signal missing data is not fantastic, but it's consistent with current behavior of the ``pandas`` library.] Returns ------- mapped_sequences : list List of sequences in internal indexing """ |
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))
elif mode == 'clip':
result.extend(self.partial_transform(y, mode))
else:
raise RuntimeError()
return result |
<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':
return 0.0
else:
return self.ergodic_cutoff |
<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 of which is one-dimensional array of Returns ------- sequences : list List of sequences, each of which is one-dimensional array of labels. """ |
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_)):
raise ValueError('sequence must be between 0 and n_states-1')
result.append(f(y))
return result |
<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 steps given by the model lagtime. Parameters state : {None, ndarray, label} Specify the starting state for the chain. ``None`` Choose the initial state by randomly drawing from the model's stationary distribution. ``array-like`` If ``state`` is a 1D array with length equal to ``n_states_``, then it is is interpreted as an initial multinomial distribution from which to draw the chain's initial state. Note that the indexing semantics of this array must match the _internal_ indexing of this model. otherwise Otherwise, ``state`` is interpreted as a particular deterministic state label from which to begin the trajectory. n_steps : int Lengths of the resulting trajectory random_state : int or RandomState instance or None (default) Pseudo Random Number generator seed control. If None, use the numpy.random singleton. Returns ------- sequence : array of length n_steps A randomly sampled label sequence """ |
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:
initial = self.mapping_[state]
cstr = np.cumsum(self.transmat_, axis=1)
chain = [initial]
for i in range(1, n_steps):
chain.append(np.sum(cstr[chain[i - 1], :] < r[i]))
return self.inverse_transform([chain])[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 draw_samples(self, sequences, n_samples, random_state=None):
"""Sample conformations for a sequences of states. Parameters sequences : list or list of lists A sequence or list of sequences, in which each element corresponds to a state label. n_samples : int How many samples to return for any given state. Returns ------- selected_pairs_by_state : np.array, dtype=int, shape=(n_states, n_samples, 2) selected_pairs_by_state[state] gives an array of randomly selected (trj, frame) pairs from the specified state. See Also -------- utils.map_drawn_samples : Extract conformations from MD trajectories by index. """ |
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] for a in sequences]
pairs = [(trj, frame) for (trj, frames) in enumerate(all_frames)
for frame in frames]
if pairs:
selected_pairs_by_state.append(
[pairs[random.choice(len(pairs))]
for i in range(n_samples)])
else:
selected_pairs_by_state.append([])
return np.array(selected_pairs_by_state) |
<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_strategy,
random_state=self.random_state)
model.fit([self.transmat_])
if self.fit_only:
microstate_mapping_ = model.landmark_labels_
else:
microstate_mapping_ = model.transform([self.transmat_])[0]
self.microstate_mapping_ = microstate_mapping_ |
<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. "Truncated Power Method for Sparse Eigenvalue Problems."
Journal of Machine Learning Research. Vol. 14. 2013.
http://www.jmlr.org/papers/volume14/yuan13a/yuan13a.pdf
'''
xts = [x0]
for t in range(max_iter):
xts.append(self._normalize(self._truncate(np.dot(A, xts[-1]), k)))
if np.linalg.norm(xts[-1] - xts[-2]) < thresh: break
return xts[-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 _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):
self.__max_state = -1
self.__micro_stack = []
for k in range(n_macrostates):
self._do_split(micro_state=k, sub_clus=self.sub_clus)
self._do_time_clustering(macro_state=k)
# do Lumping
n_micro_states = np.amax(self.__temp_labels_) + 1
if n_micro_states > self.n_macrostates:
# print("PCCA Lumping...", n_micro_states, "microstates")
self.__temp_MacroAssignments_ = self._do_lumping(
n_macrostates=n_macrostates)
#self.__temp_labels_ = [copy.copy(element) for element in self.__temp_MacroAssignments_]
#Calculate Metastabilty
prevQ = metaQ
metaQ = self.__temp_transmat_.diagonal().sum()
metaQ /= len(self.__temp_transmat_)
else:
self.__temp_MacroAssignments_ = [
copy.copy(element) for element in self.__temp_labels_
]
# Optimization / Monte-Carlo
acceptedMove = False
MCacc = np.exp(metaQ * metaQ - prevQ * prevQ)
if MCacc > 1.0:
MCacc = 1.0
optLim = 0.95
if MCacc > optLim:
acceptedMove = True
if acceptedMove:
local_maxQ = metaQ
if metaQ > global_maxQ:
global_maxQ = metaQ
self.MacroAssignments_ = [
copy.copy(element)
for element in self.__temp_MacroAssignments_
]
self.labels_ = [copy.copy(element)
for element in self.__temp_labels_]
self.transmat_ = self.__temp_transmat_
# print("Loop:", iter, "AcceptedMove?", acceptedMove, "metaQ:",
# metaQ, "prevQ:", prevQ, "global_maxQ:", global_maxQ,
# "local_maxQ:", local_maxQ, "macroCount:", n_macrostates)
#set n_macrostates
n_macrostates = self.n_macrostates
self.__temp_labels_ = [copy.copy(element)
for element in self.__temp_MacroAssignments_
] |
<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_traj : mdtraj.Trajectory Trajectory to grab atom pairs from keep_atoms : np.ndarray, dtype=string, optional Select only these atom names. Defaults to N, CA, CB, C, O, H exclude_atoms : np.ndarray, dtype=string, optional Exclude these atom names reject_bonded : bool, default=True If True, exclude bonded atompairs. Returns ------- atom_indices : np.ndarray, dtype=int The atom indices that pass your criteria pair_indices : np.ndarray, dtype=int, shape=(N, 2) Pairs of atom indices that pass your criteria. Notes ----- This function has been optimized for speed. A naive implementation can be slow (~minutes) for large proteins. """ |
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].index.values
pair_indices = np.array(list(itertools.combinations(atom_indices, 2)))
if reject_bonded:
a_list = bonds.min(1)
b_list = bonds.max(1)
n = atom_indices.max() + 1
bond_hashes = a_list + b_list * n
pair_hashes = pair_indices[:, 0] + pair_indices[:, 1] * n
not_bonds = ~np.in1d(pair_hashes, bond_hashes)
pair_indices = np.array([(a, b) for k, (a, b)
in enumerate(pair_indices)
if not_bonds[k]])
return atom_indices, pair_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 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 ignored, so this might result in a really "jumpy" sampled trajectory. Parameters trajs : dictionary of np.ndarray Dictionary of tica-transformed trajectories, keyed by arbitrary keys. The resulting trajectory indices will use these keys. dimension : int dimension to sample on n_frames : int Number of frames requested scheme : {'linear', 'random', 'edges'} 'linear' samples the tic linearly, 'random' samples randomly (thereby taking approximate free energies into account), and 'edges' samples the edges of the tic only. Returns ------- inds : list of tuples Tuples of (trajectory_index, frame_index), where trajectory_index is in the domain of the keys of the input dictionary. """ |
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 scheme == "random":
spaced_points = np.sort(np.random.choice(txx, n_frames))
spaced_points = spaced_points[:, np.newaxis]
elif scheme == "edge":
_cut_point = n_frames // 2
txx = np.sort(txx)
spaced_points = np.hstack((txx[:_cut_point],
txx[-_cut_point:]))
spaced_points = np.reshape(spaced_points, newshape=(len(spaced_points), 1))
else:
raise ValueError("Scheme has be to one of linear, random or edge")
tree = KDTree(trajs)
dists, inds = tree.query(spaced_points)
return [(fixed_indices[i], j) for i, j in inds] |
<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:
min = np.asarray(self.min)
if not min.shape == (self.n_features,):
raise ValueError('min shape error')
if self.max is None:
max = np.max(X, axis=0)
elif isinstance(self.max, numbers.Number):
max = self.max * np.ones(self.n_features)
else:
max = np.asarray(self.max)
if not max.shape == (self.n_features,):
raise ValueError('max shape error')
self.grid = np.array(
[np.linspace(min[i] - EPS, max[i] + EPS, self.n_bins_per_feature + 1)
for i in range(self.n_features)])
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, 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 ------- y : array, shape = [n_samples,] Index of the grid cell containing each sample """ |
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
labels = np.dot(self.n_bins_per_feature ** np.arange(self.n_features), binassign)
assert np.max(labels) < self.n_bins
return labels |
<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. Returns ------- features : list(np.ndarray), length = len(traj_list) The featurized trajectories. features[i] is the featurized version of traj_list[i] and has shape (n_samples_i, n_features) """ |
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 that gives a filename that doesn't exist. This naively uses a while loop to find such a filename, so there shouldn't be too many existing backups or performance will degrade. Parameters fn : str The filename to check. """ |
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}"
.format(fn=fn, newfn=trial_fn),
BackupWarning)
shutil.move(fn, trial_fn) |
<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 map to unique strings. If the key is a tuple, it will join each element of the tuple with '/', resulting in a filesystem hierarchy of files. """ |
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 try to load in. Typically, you have far fewer (possibly 1) topologies than trajectories Parameters meta : pd.DataFrame The DataFrame of metadata with a column named 'top_fn' Returns ------- tops : dict Dictionary of ``md.Topology`` objects, keyed by "top_fn" values. """ |
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 have to have all the same topology to concatenate. Parameters meta : pd.DataFrame The DataFrame of metadata with a column named 'top_fn' Returns ------- top : md.Topology The one topology file that can be used for all trajectories. """ |
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 performs a stride. We join(iterload) to conserve memory. """ |
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,
check_topology=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 render_meta(meta, fn="meta.pandas.html", title="Project Metadata - MSMBuilder", pandas_kwargs=None):
"""Render a metadata dataframe as an html webpage for inspection. Parameters meta : pd.Dataframe The DataFrame of metadata fn : str Output filename (should end in html) title : str Page title pandas_kwargs : dict Arguments to be passed to pandas """ |
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-bootstrap.html")
rendered = templ.render(
title=title,
content=meta.to_html(**kwargs_with_defaults)
)
# Ugh, pandas hardcodes border="1"
rendered = re.sub(r' border="1"', '', rendered)
backup(fn)
with open(fn, 'w') as f:
f.write(rendered) |
<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. This protocol is backwards-compatible among Python versions, but may not be "forwards-compatible". A file saved with Python 3 won't be able to be opened under Python 2. Please read the pickle docs (specifically related to the ``protocol`` parameter) to specify broader compatibility. If a file already exists at the given filename, it will be backed up. Parameters obj : object A Python object to serialize (save to disk) fn : str Filename to save the object. We recommend using the '.pickl' extension, but don't do anything to enforce that convention. """ |
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``. This method will automatically back up existing files named ``fn``. Parameters trajs : dict of (key, np.ndarray) Dictionary of trajectory-like ndarray's keyed on ``meta.index`` values. fn : str Where to save the data. This will be a directory containing one file per trajectory meta : pd.DataFrame The DataFrame of metadata """ |
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(npy_fn, 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 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 method finds trajectories based on the ``meta`` dataframe. If you remove a file (trajectory) from disk, be sure to remove its row from the dataframe. If you remove a row from the dataframe, be aware that that trajectory (file) will not be loaded, even if it exists on disk. Parameters fn : str Where the data is saved. This should be a directory containing one file per trajectory. meta : pd.DataFrame or str The DataFrame of metadata. If this is a string, it is interpreted as a filename and the dataframe is loaded from disk. Returns ------- meta : pd.DataFrame The DataFrame of metadata. If you passed in a string (filename) to the ``meta`` input, this will be the loaded DataFrame. If you gave a DataFrame object, this will just be a reference back to that object trajs : dict Dictionary of trajectory-like np.ndarray's keyed on the values of ``meta.index``. """ |
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 of points to query. k : int, optional The number of nearest neighbors to return. eps : nonnegative float, optional Return approximate nearest neighbors; the kth returned value is guaranteed to be no further than (1+eps) times the distance to the real kth nearest neighbor. p : float, 1<=p<=infinity, optional Which Minkowski p-norm to use. 1 is the sum-of-absolute-values "Manhattan" distance 2 is the usual Euclidean distance infinity is the maximum-coordinate-difference distance distance_upper_bound : nonnegative float, optional Return only neighbors within this distance. This is used to prune tree searches, so if you are doing a series of nearest-neighbor queries, it may help to supply the distance to the nearest neighbor of the most recent point. Returns ------- d : float or array of floats The distances to the nearest neighbors. If x has shape tuple+(self.m,), then d has shape tuple if k is one, or tuple+(k,) if k is larger than one. Missing neighbors (e.g. when k > n or distance_upper_bound is given) are indicated with infinite distances. If k is None, then d is an object array of shape tuple, containing lists of distances. In either case the hits are sorted by distance (nearest first). i : tuple(int, int) or array of tuple(int, int) The locations of the neighbors in self.data. Locations are given by tuples of (traj_i, frame_i) Examples -------- (array([ 0.0034, 0.0102]), array([[ 0, 410], [ 1, 670]])) (0.0034, array([ 0, 410])) """ |
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) Sequence data to transform, where n_samples_i in the number of samples in sequence i and n_features is the number of features. Returns ------- sequence_new : list of array-like, each of shape (n_samples_i, n_components) """ |
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_samples_i, n_features) Training data, where n_samples_i in the number of samples in sequence i and n_features is the number of features. y : None Ignored Returns ------- sequence_new : list of array-like, each of shape (n_samples_i, n_components) """ |
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 of multivariate timeseries. Each sequence may have a different length, but they all must have the same number of features. Returns ------- self """ |
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, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters sequences : list of array-like, each of shape [sequence_length, n_features] A list of multivariate timeseries. Each sequence may have a different length, but they all must have the same number of features. Returns ------- Y : list of arrays, each of shape [sequence_length,] Index of the closest center each sample belongs to. """ |
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 [sequence_length, n_features] A list of multivariate timeseries. Each sequence may have a different length, but they all must have the same number of features. Returns ------- Y : list of ndarray, each of shape [sequence_length, ] Cluster labels """ |
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.predict(sequences)
if not isinstance(labels, list):
labels = self._split(labels)
return labels |
<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 color scheme
if ax is None:
ax = pp
ax.contourf(xx, yy, V.clip(max=200), 40, **kwargs) |
<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 files. parser : descendant of _Parser Object that handles conversion of filenames to metadata rows. """ |
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 eigenvectors. Parameters sequences : list of array-like List of sequences, or a single sequence. Each sequence should be a 1D iterable of state labels. Labels can be integers, strings, or other orderable objects. right : bool Which eigenvectors to map onto. Both the left (:math:`\Phi`) and the right (:math`\Psi`) eigenvectors of the transition matrix are commonly used, and differ in their normalization. The two sets of eigenvectors are related by the stationary distribution :: \Phi_i(x) = \Psi_i(x) * \mu(x) In the MSM literature, the right vectors (default here) are approximations to the transfer operator eigenfunctions, whereas the left eigenfunction are approximations to the propagator eigenfunctions. For more details, refer to reference [1]. mode : {'clip', 'fill'} Method by which to treat labels in `sequences` which do not have a corresponding index. This can be due, for example, to the ergodic trimming step. ``clip`` Unmapped labels are removed during transform. If they occur at the beginning or end of a sequence, the resulting transformed sequence will be shorted. If they occur in the middle of a sequence, that sequence will be broken into two (or more) sequences. (Default) ``fill`` Unmapped labels will be replaced with NaN, to signal missing data. [The use of NaN to signal missing data is not fantastic, but it's consistent with current behavior of the ``pandas`` library.] Returns ------- transformed : list of 2d arrays Each element of transformed is an array of shape ``(n_samples, n_timescales)`` containing the transformed data. References .. [1] Prinz, Jan-Hendrik, et al. "Markov models of molecular kinetics: Generation and validation." J. Chem. Phys. 134.17 (2011):
174105. """ |
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):
value = np.empty((y.shape[0], op.shape[1]))
value[is_finite, :] = np.take(op, y[is_finite].astype(np.int), axis=0)
value[~is_finite, :] = np.nan
else:
value = np.take(op, y, axis=0)
result.append(value)
return result |
<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 single sequence. Each sequence should be a 1D iterable of state labels. Labels can be integers, strings, or other orderable objects. Returns ------- loglikelihood : float The natural log of the likelihood, computed as :math:`\sum_{ij} C_{ij} \log(P_{ij})` where C is a matrix of counts computed from the input sequences. """ |
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.mapping_)
indices = [e[1] for e in sorted(m2.items())]
transmat_slice = self.transmat_[np.ix_(indices, indices)]
return np.nansum(np.log(transmat_slice) * 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 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 matrix entries:
Min. : {cnz_min:.1f}
1st Qu.: {cnz_1st:.1f}
Median : {cnz_med:.1f}
Mean : {cnz_mean:.1f}
3rd Qu.: {cnz_3rd:.1f}
Max. : {cnz_max:.1f}
Total transition counts :
{cnz_sum} counts
Total transition counts / lag_time:
{cnz_sum_per_lag} units
Timescales:
[{ts}] units
'''
counts_nz = np.count_nonzero(self.countsmat_)
cnz = self.countsmat_[np.nonzero(self.countsmat_)]
return doc.format(
lag_time=self.lag_time,
reversible_type=self.reversible_type,
ergodic_cutoff=self.ergodic_cutoff,
prior_counts=self.prior_counts,
n_states=self.n_states_,
counts_nz=counts_nz,
percent_counts_nz=(100 * counts_nz / self.countsmat_.size),
cnz_min=np.min(cnz),
cnz_1st=np.percentile(cnz, 25),
cnz_med=np.percentile(cnz, 50),
cnz_mean=np.mean(cnz),
cnz_3rd=np.percentile(cnz, 75),
cnz_max=np.max(cnz),
cnz_sum=np.sum(cnz),
cnz_sum_per_lag=np.sum(cnz)/self.lag_time,
ts=', '.join(['{:.2f}'.format(t) for t in self.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 timescales_(self):
"""Implied relaxation timescales of the model. The relaxation of any initial distribution towards equilibrium is given, according to this model, by a sum of terms -- each corresponding to the relaxation along a specific direction (eigenvector) in state space -- which decay exponentially in time. See equation 19. from [1]. Returns ------- timescales : array-like, shape = (n_timescales,) The longest implied relaxation timescales of the model, expressed in units of time-step between indices in the source data supplied to ``fit()``. References .. [1] Prinz, Jan-Hendrik, et al. "Markov models of molecular kinetics: Generation and validation." J. Chem. Phys. 134.17 (2011):
174105. """ |
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, shape=(n_timescales+1,) The estimated symptotic standard deviation in the eigenvalues. References .. [1] Hinrichs, Nina Singhal, and Vijay S. Pande. "Calculation of the distribution of eigenvalues and eigenvectors in Markovian state models for molecular dynamics." J. Chem. Phys. 126.24 (2007):
244101. """ |
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_eigensystem()
sigma2 = np.zeros(n_timescales + 1)
for k in range(n_timescales + 1):
dLambda_dT = np.outer(lv[:, k], rv[:, k])
for i in range(self.n_states_):
ui = self.countsmat_[:, i]
wi = np.sum(ui)
cov = wi*np.diag(ui) - np.outer(ui, ui)
quad_form = dLambda_dT[i].dot(cov).dot(dLambda_dT[i])
sigma2[k] += quad_form / (wi**2*(wi+1))
return np.sqrt(sigma2) |
<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 : np.array, shape=(n_timescales,) The estimated symptotic standard deviation in the implied timescales. References .. [1] Hinrichs, Nina Singhal, and Vijay S. Pande. "Calculation of the distribution of eigenvalues and eigenvectors in Markovian state models for molecular dynamics." J. Chem. Phys. 126.24 (2007):
244101. """ |
# 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 traj : mdtraj.Trajectory The trajectory to describe Returns ------- feature_descs : list of dict Dictionary describing each feature with the following information about the atoms participating in each feature - resnames: unique names of residues - atominds: atom indicies involved in the feature - resseqs: unique residue sequence ids (not necessarily 0-indexed) - resids: unique residue ids (0-indexed) - featurizer: featurizer dependent - featuregroup: other info for the featurizer """ |
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 to transform Returns ------- out : array like, shape (n_samples, n_features) """ |
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_retries == max_retries:
raise
num_retries += 1
time.sleep(5)
return ret
return wrapper
return retry_func |
<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_data conda package (and located within the python installation directory). If this package exists, we will use its data directory as the data home. Otherwise, we use the old logic: This folder is used by some large dataset loaders to avoid downloading the data several times. By default the data dir is set to a folder named 'msmbuilder_data' in the user's home folder. Alternatively, it can be set by the 'MSMBUILDER_DATA' environment variable or programmatically by giving an explicit folder path. The '~' symbol is expanded to the user home folder. If the folder does not already exist, it is automatically created. """ |
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].append(r)
else:
self.resources[r.resource_type] = [r] |
<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: requests.Session """ |
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_connect.KeycloakOpenidConnect """ |
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: :param object credentials: (optional) :param str first_name: (optional) :param str last_name: (optional) :param str email: (optional) :param boolean enabled: (optional) """ |
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(
self.get_path('collection', realm=self._realm_name)
),
data=json.dumps(payload, sort_keys=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 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_name for user :param str last_name: last_name for user :param str email: Email for user :param bool email_verified: User email verified :param Map attributes: Atributes in user :param string array realm_roles: Realm Roles :param Map client_roles: Client Roles :param string array groups: Groups for user """ |
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(
url=self._client.get_full_url(
self.get_path(
'single', realm=self._realm_name, user_id=self._user_id
)
),
data=json.dumps(payload, sort_keys=True)
)
self.get()
return result |
<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.section.2.2.1 :param str token: client access token :param str id: Identifier of the resource set :param str name: :param str uri: (optional) :param str type: (optional) :param list scopes: (optional) :param str icon_url: (optional) :param str DisplayName: (optional) :param boolean ownerManagedAccess: (optional) :param str owner: (optional) :rtype: str """ |
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#update-resource-set :param str token: client access token :param str id: Identifier of the resource set :param str name: :param str uri: (optional) :param str type: (optional) :param list scopes: (optional) :param str icon_url: (optional) :rtype: str """ |
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 :param str token: client access token :param str id: Identifier of the resource set :rtype: dict """ |
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.