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 _tsne(self, P, degrees_of_freedom, n_samples, random_state, X_embedded, neighbors=None, skip_num_points=0): """Runs t-SNE."""
# t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P # and the Student's t-distributions Q. The optimization algorithm that # we use is batch gradient descent with two stages: # * initial optimization with early exaggeration and momentum at 0.5 # * final optimizat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correct(datasets_full, genes_list, return_dimred=False, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alph...
datasets_full = check_datasets(datasets_full) datasets, genes = merge_datasets(datasets_full, genes_list, ds_names=ds_names, union=union) datasets_dimred, genes = process_data(datasets, genes, hvg=hvg, dimred=dimred) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integrate(datasets_full, genes_list, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, g...
datasets_full = check_datasets(datasets_full) datasets, genes = merge_datasets(datasets_full, genes_list, ds_names=ds_names, union=union) datasets_dimred, genes = process_data(datasets, genes, hvg=hvg, dimred=dimred) for _...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def correct_scanpy(adatas, **kwargs): """Batch correct a list of `scanpy.api.AnnData`. Parameters adatas : `list` of `scanpy.api.AnnData` Data sets to integrate ...
if 'return_dimred' in kwargs and kwargs['return_dimred']: datasets_dimred, datasets, genes = correct( [adata.X for adata in adatas], [adata.var_names.values for adata in adatas], **kwargs ) else: datasets, genes = correct( [adata.X for ada...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integrate_scanpy(adatas, **kwargs): """Integrate a list of `scanpy.api.AnnData`. Parameters adatas : `list` of `scanpy.api.AnnData` Data sets to integrate. k...
datasets_dimred, genes = integrate( [adata.X for adata in adatas], [adata.var_names.values for adata in adatas], **kwargs ) return datasets_dimred
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def augknt(knots, order): """Augment a knot vector. Parameters: knots: Python list or rank-1 array, the original knot vector (without endpoint repeats) order: in...
if isinstance(knots, np.ndarray) and knots.ndim > 1: raise ValueError("knots must be a list or a rank-1 array") knots = list(knots) # ensure Python list # One copy of knots[0] and knots[-1] will come from "knots" itself, # so we only need to prepend/append "order" copies. # return n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aveknt(t, k): """Compute the running average of `k` successive elements of `t`. Return the averaged array. Parameters: t: Python list or rank-1 array k: int,...
t = np.atleast_1d(t) if t.ndim > 1: raise ValueError("t must be a list or a rank-1 array") n = t.shape[0] u = max(0, n - (k-1)) # number of elements in the output array out = np.empty( (u,), dtype=t.dtype ) for j in range(u): out[j] = sum( t[j:(j+k)] ) / k return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def aptknt(tau, order): """Create an acceptable knot vector. Minimal emulation of MATLAB's ``aptknt``. The returned knot vector can be used to generate splines o...
tau = np.atleast_1d(tau) k = order + 1 if tau.ndim > 1: raise ValueError("tau must be a list or a rank-1 array") # emulate MATLAB behavior for the "k" parameter # # See # https://se.mathworks.com/help/curvefit/aptknt.html # if len(tau) < k: k = len(tau) if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def knt2mlt(t): """Count multiplicities of elements in a sorted list or rank-1 array. Minimal emulation of MATLAB's ``knt2mlt``. Parameters: t: Python list or ra...
t = np.atleast_1d(t) if t.ndim > 1: raise ValueError("t must be a list or a rank-1 array") out = [] e = None for k in range(t.shape[0]): if t[k] != e: e = t[k] count = 0 else: count += 1 out.append(count) return np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spcol(knots, order, tau): """Return collocation matrix. Minimal emulation of MATLAB's ``spcol``. Parameters: knots: rank-1 array, knot vector (with appropria...
m = knt2mlt(tau) B = bspline.Bspline(knots, order) dummy = B(0.) nbasis = len(dummy) # perform dummy evaluation to get number of basis functions A = np.empty( (tau.shape[0], nbasis), dtype=dummy.dtype ) for i,item in enumerate(zip(tau,m)): taui,mi = item f = B.diff(orde...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def d(self, xi): """Convenience function to compute first derivative of basis functions. 'Memoized' for speed."""
return self.__basis(xi, self.p, compute_derivatives=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 plot(self): """Plot basis functions over full range of knots. Convenience function. Requires matplotlib. """
try: import matplotlib.pyplot as plt except ImportError: from sys import stderr print("ERROR: matplotlib.pyplot not found, matplotlib must be installed to use this function", file=stderr) raise x_min = np.min(self.knot_vector) x_max = np...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __diff_internal(self): """Differentiate a B-spline once, and return the resulting coefficients and Bspline objects. This preserves the Bspline object nature ...
assert self.p > 0, "order of Bspline must be > 0" # we already handle the other case in diff() # https://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/B-spline/bspline-derv.html # t = self.knot_vector p = self.p Bi = Bspline( t[:-1], p-1 ) Bip1 = Bs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff(self, order=1): """Differentiate a B-spline `order` number of times. Parameters: order: int, >= 0 Returns: The returned function internally uses __call_...
order = int(order) if order < 0: raise ValueError("order must be >= 0, got %d" % (order)) if order == 0: return self.__call__ if order > self.p: # identically zero, but force the same output format as in the general case dummy = self.__call__(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 collmat(self, tau, deriv_order=0): """Compute collocation matrix. Parameters: tau: Python list or rank-1 array, collocation sites deriv_order: int, >=0, orde...
# get number of basis functions and output dtype dummy = self.__call__(0.) nbasis = dummy.shape[0] tau = np.atleast_1d(tau) if tau.ndim > 1: raise ValueError("tau must be a list or a rank-1 array") A = np.empty( (tau.shape[0], nbasis), dtype=dummy.dtype ) ...
<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_normalized_request_string(method, url, nonce, params, ext='', body_hash=None): """ Returns a normalized request string as described iN OAuth2 MAC spec. h...
urlparts = urlparse.urlparse(url) if urlparts.query: norm_url = '%s?%s' % (urlparts.path, urlparts.query) elif params: norm_url = '%s?%s' % (urlparts.path, get_normalized_params(params)) else: norm_url = urlparts.path if not body_hash: body_hash = get_body_hash(para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_viterbi_paths(self): """ Computes the viterbi paths using the current HMM model """
# get parameters K = len(self._observations) A = self._hmm.transition_matrix pi = self._hmm.initial_distribution # compute viterbi path for each trajectory paths = np.empty(K, dtype=object) for itraj in range(K): obs = self._observations[itraj] ...
<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): """ Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm Returns ------- model : HMM The maximum likelihood HMM model. """
logger().info("=================================================================") logger().info("Running Baum-Welch:") logger().info(" input observations: "+str(self.nobservations)+" of lengths "+str(self.observation_lengths)) logger().info(" initial HMM guess:"+str(self._hmm)) ...
<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_gaussian(mean, covar, covariance_type='diag', n_samples=1, random_state=None): """Generate random samples from a Gaussian distribution. Parameters mea...
rng = check_random_state(random_state) n_dim = len(mean) rand = rng.randn(n_dim, n_samples) if n_samples == 1: rand.shape = (n_dim,) if covariance_type == 'spherical': rand *= np.sqrt(covar) elif covariance_type == 'diag': rand = np.dot(np.diag(np.sqrt(covar)), rand) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _covar_mstep_diag(gmm, X, responsibilities, weighted_X_sum, norm, min_covar): """Performing the covariance M step for diagonal cases"""
avg_X2 = np.dot(responsibilities.T, X * X) * norm avg_means2 = gmm.means_ ** 2 avg_X_means = gmm.means_ * weighted_X_sum * norm return avg_X2 - 2 * avg_X_means + avg_means2 + min_covar
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _covar_mstep_spherical(*args): """Performing the covariance M step for spherical cases"""
cv = _covar_mstep_diag(*args) return np.tile(cv.mean(axis=1)[:, np.newaxis], (1, cv.shape[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 _covar_mstep_full(gmm, X, responsibilities, weighted_X_sum, norm, min_covar): """Performing the covariance M step for full cases"""
# Eq. 12 from K. Murphy, "Fitting a Conditional Linear Gaussian # Distribution" n_features = X.shape[1] cv = np.empty((gmm.n_components, n_features, n_features)) for c in range(gmm.n_components): post = responsibilities[:, c] mu = gmm.means_[c] diff = X - mu with np....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_covars(self, covars): """Provide values for covariance"""
covars = np.asarray(covars) _validate_covars(covars, self.covariance_type, self.n_components) self.covars_ = covars
<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_samples(self, X): """Return the per-sample likelihood of the data under the model. Compute the log probability of X under the model and return the post...
check_is_fitted(self, 'means_') X = check_array(X) if X.ndim == 1: X = X[:, np.newaxis] if X.size == 0: return np.array([]), np.empty((0, self.n_components)) if X.shape[1] != self.means_.shape[1]: raise ValueError('The shape of X is not comp...
<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): """Predict label for data. Parameters X : array-like, shape = [n_samples, n_features] Returns ------- C : array, shape = (n_samples,) """
logprob, responsibilities = self.score_samples(X) return responsibilities.argmax(axis=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 fit(self, X, y=None): """Estimate model parameters with the expectation-maximization algorithm. A initialization step is performed before entering the em alg...
# initialization step X = check_array(X, dtype=np.float64) if X.shape[0] < self.n_components: raise ValueError( 'GMM estimation with %s components, but got only %s samples' % (self.n_components, X.shape[0])) max_log_prob = -np.infty ...
<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_mstep(self, X, responsibilities, params, min_covar=0): """ Perform the Mstep of the EM algorithm and return the class weihgts. """
weights = responsibilities.sum(axis=0) weighted_X_sum = np.dot(responsibilities.T, X) inverse_weights = 1.0 / (weights[:, np.newaxis] + 10 * EPS) if 'w' in params: self.weights_ = (weights / (weights.sum() + 10 * EPS) + EPS) if 'm' in params: self.means_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _n_parameters(self): """Return the number of free parameters in the model."""
ndim = self.means_.shape[1] if self.covariance_type == 'full': cov_params = self.n_components * ndim * (ndim + 1) / 2. elif self.covariance_type == 'diag': cov_params = self.n_components * ndim elif self.covariance_type == 'tied': cov_params = ndim * ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bic(self, X): """Bayesian information criterion for the current model fit and the proposed data Parameters X : array of shape(n_samples, n_dimensions) Return...
return (-2 * self.score(X).sum() + self._n_parameters() * np.log(X.shape[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 init_model_gaussian1d(observations, nstates, reversible=True): """Generate an initial model with 1D-Gaussian output densities Parameters observations : list ...
ntrajectories = len(observations) # Concatenate all observations. collected_observations = np.array([], dtype=config.dtype) for o_t in observations: collected_observations = np.append(collected_observations, o_t) # Fit a Gaussian mixture model to obtain emission distributions and state st...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _p_o(self, o): """ Returns the output probability for symbol o from all hidden states Parameters o : float A single observation. Return ------ p_o : ndarray ...
if self.__impl__ == self.__IMPL_C__: return gc.p_o(o, self.means, self.sigmas, out=None, dtype=type(o)) elif self.__impl__ == self.__IMPL_PYTHON__: if np.any(self.sigmas < np.finfo(self.sigmas.dtype).eps): raise RuntimeError('at least one sigma is too small to co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def estimate(self, observations, weights): """ Fits the output model given the observations and weights Parameters observations : [ ndarray(T_k,) ] with K elemen...
# sizes N = self.nstates K = len(observations) # fit means self._means = np.zeros(N) w_sum = np.zeros(N) for k in range(K): # update nominator for i in range(N): self.means[i] += np.dot(weights[k][:, i], observations[k]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initial_distribution_samples(self): r""" Samples of the initial distribution """
res = np.empty((self.nsamples, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :] = self._sampled_hmms[i].stationary_distribution return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transition_matrix_samples(self): r""" Samples of the transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :, :] = self._sampled_hmms[i].transition_matrix return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eigenvalues_samples(self): r""" Samples of the eigenvalues """
res = np.empty((self.nsamples, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :] = self._sampled_hmms[i].eigenvalues return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eigenvectors_left_samples(self): r""" Samples of the left eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :, :] = self._sampled_hmms[i].eigenvectors_left return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eigenvectors_right_samples(self): r""" Samples of the right eigenvectors of the hidden transition matrix """
res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :, :] = self._sampled_hmms[i].eigenvectors_right return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_p_obs(self, obs, out=None, dtype=np.float32): """ Returns the element-wise logarithm of the output probabilities for an entire trajectory and all hidden ...
if out is None: return np.log(self.p_obs(obs)) else: self.p_obs(obs, out=out, dtype=dtype) np.log(out, out=out) return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coarse_grain_transition_matrix(P, M): """ Coarse grain transition matrix P using memberships M Computes .. math: Pc = (M' M)^-1 M' P M Parameters P : ndarray...
# coarse-grain matrix: Pc = (M' M)^-1 M' P M W = np.linalg.inv(np.dot(M.T, M)) A = np.dot(np.dot(M.T, P), M) P_coarse = np.dot(W, A) # this coarse-graining can lead to negative elements. Setting them to zero here. P_coarse = np.maximum(P_coarse, 0) # and renormalize P_coarse /= P_coars...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regularize_hidden(p0, P, reversible=True, stationary=False, C=None, eps=None): """ Regularizes the hidden initial distribution and transition matrix. Makes s...
# input n = P.shape[0] if eps is None: # default output probability, in order to avoid zero columns eps = 0.01 / n # REGULARIZE P P = np.maximum(P, eps) # and renormalize P /= P.sum(axis=1)[:, None] # ensure reversibility if reversible: P = _tmatrix_disconnected.en...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regularize_pobs(B, nonempty=None, separate=None, eps=None): """ Regularizes the output probabilities. Makes sure that the output probability distributions ha...
# input B = B.copy() # modify copy n, m = B.shape # number of hidden / observable states if eps is None: # default output probability, in order to avoid zero columns eps = 0.01 / m # observable sets if nonempty is None: nonempty = np.arange(m) if separate is None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_discrete_hmm_ml(C_full, nstates, reversible=True, stationary=True, active_set=None, P=None, eps_A=None, eps_B=None, separate=None): """Initializes discr...
raise NotImplementedError('ML-initialization not yet implemented')
<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, Pi, Tij): r""" Updates the transition matrix and recomputes all derived quantities """
from msmtools import analysis as msmana # update transition matrix by copy self._Tij = np.array(Tij) assert msmana.is_transition_matrix(self._Tij), 'Given transition matrix is not a stochastic matrix' assert self._Tij.shape[0] == self._nstates, 'Given transition matrix has unex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_stationary(self): r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution of the hidden transition matrix...
# for disconnected matrices, the stationary distribution depends on the estimator, so we can't compute # it directly. Therefore we test whether the initial distribution is stationary. return np.allclose(np.dot(self._Pi, self._Tij), self._Pi)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stationary_distribution(self): r""" Compute stationary distribution of hidden states if possible. Raises ------ ValueError if the HMM is not stationary """
assert _tmatrix_disconnected.is_connected(self._Tij, strong=False), \ 'No unique stationary distribution because transition matrix is not connected' import msmtools.analysis as msmana return msmana.stationary_distribution(self._Tij)
<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): r""" Relaxation timescales of the hidden transition matrix Returns ------- ts : ndarray(m) relaxation timescales in units of the input traj...
from msmtools.analysis.dense.decomposition import timescales_from_eigenvalues as _timescales self._ensure_spectral_decomposition() ts = _timescales(self._eigenvalues, tau=self._lag) return ts[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 lifetimes(self): r""" Lifetimes of states of the hidden transition matrix Returns ------- l : ndarray(nstates) state lifetimes in units of the input trajecto...
return -self._lag / np.log(np.diag(self.transition_matrix))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sub_hmm(self, states): r""" Returns HMM on a subset of states Returns the HMM restricted to the selected subset of states. Will raise exception if the hidden...
# restrict initial distribution pi_sub = self._Pi[states] pi_sub /= pi_sub.sum() # restrict transition matrix P_sub = self._Tij[states, :][:, states] # checks if this selection is possible assert np.all(P_sub.sum(axis=1) > 0), \ 'Illegal sub_hmm requ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_matrix(self): # TODO: does this belong here or to the BHMM sampler, or in a subclass containing HMM with data? """Compute the transition count matrix f...
if self.hidden_state_trajectories is None: raise RuntimeError('HMM model does not have a hidden state trajectory.') C = msmest.count_matrix(self.hidden_state_trajectories, 1, nstates=self._nstates) return C.toarray()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count_init(self): """Compute the counts at the first time step Returns ------- n : ndarray(nstates) n[i] is the number of trajectories starting in state i ""...
if self.hidden_state_trajectories is None: raise RuntimeError('HMM model does not have a hidden state trajectory.') n = [traj[0] for traj in self.hidden_state_trajectories] return np.bincount(n, minlength=self.nstates)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_observations_in_state(self, observations, state_index): # TODO: this would work well in a subclass with data """Collect a vector of all observations ...
if not self.hidden_state_trajectories: raise RuntimeError('HMM model does not have a hidden state trajectory.') dtype = observations[0].dtype collected_observations = np.array([], dtype=dtype) for (s_t, o_t) in zip(self.hidden_state_trajectories, observations): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_synthetic_state_trajectory(self, nsteps, initial_Pi=None, start=None, stop=None, dtype=np.int32): """Generate a synthetic state trajectory. Paramete...
# consistency check if initial_Pi is not None and start is not None: raise ValueError('Arguments initial_Pi and start are exclusive. Only set one of them.') # Generate first state sample. if start is None: if initial_Pi is not None: start = np.ra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_synthetic_observation_trajectory(self, length, initial_Pi=None): """Generate a synthetic realization of observables. Parameters length : int Length ...
# First, generate synthetic state trajetory. s_t = self.generate_synthetic_state_trajectory(length, initial_Pi=initial_Pi) # Next, generate observations from these states. o_t = self.output_model.generate_observation_trajectory(s_t) return [o_t, s_t]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_synthetic_observation_trajectories(self, ntrajectories, length, initial_Pi=None): """Generate a number of synthetic realization of observables from ...
O = list() # observations S = list() # state trajectories for trajectory_index in range(ntrajectories): o_t, s_t = self.generate_synthetic_observation_trajectory(length=length, initial_Pi=initial_Pi) O.append(o_t) S.append(s_t) return O, S
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nb_to_python(nb_path): """convert notebook to python script"""
exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nb_to_html(nb_path): """convert notebook to html"""
exporter = html.HTMLExporter(template_file='full') output, resources = exporter.from_filename(nb_path) header = output.split('<head>', 1)[1].split('</head>',1)[0] body = output.split('<body>', 1)[1].split('</body>',1)[0] # http://imgur.com/eR9bMRH header = header.replace('<style', '<style scop...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def estimate(self, observations, weights): """ Maximum likelihood estimation of output model given the observations and weights Parameters observations : [ ndarr...
# sizes N, M = self._output_probabilities.shape K = len(observations) # initialize output probability matrix self._output_probabilities = np.zeros((N, M)) # update output probability matrix (numerator) if self.__impl__ == self.__IMPL_C__: for k in ran...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def state_counts(gamma, T, out=None): """ Sum the probabilities of being in state i to time t Parameters gamma : ndarray((T,N), dtype = float), optional, default...
return np.sum(gamma[0:T], axis=0, out=out)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logger(name='BHMM', pattern='%(asctime)s %(levelname)s %(name)s: %(message)s', date_format='%H:%M:%S', handler=logging.StreamHandler(sys.stdout)): """ Retrie...
_logger = logging.getLogger(name) _logger.setLevel(config.log_level()) if not _logger.handlers: formatter = logging.Formatter(pattern, date_format) handler.setFormatter(formatter) handler.setLevel(config.log_level()) _logger.addHandler(handler) _logger.propagate = Fa...
<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(self, nsamples, nburn=0, nthin=1, save_hidden_state_trajectory=False, call_back=None): """Sample from the BHMM posterior. Parameters nsamples : int Th...
# Run burn-in. for iteration in range(nburn): logger().info("Burn-in %8d / %8d" % (iteration, nburn)) self._update() # Collect data. models = list() for iteration in range(nsamples): logger().info("Iteration %8d / %8d" % (iteration, nsampl...
<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): """Update the current model using one round of Gibbs sampling. """
initial_time = time.time() self._updateHiddenStateTrajectories() self._updateEmissionProbabilities() self._updateTransitionMatrix() final_time = time.time() elapsed_time = final_time - initial_time logger().info("BHMM update iteration took %.3f s" % elapsed_tim...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _updateTransitionMatrix(self): """ Updates the hidden-state transition matrix and the initial distribution """
# TRANSITION MATRIX C = self.model.count_matrix() + self.prior_C # posterior count matrix # check if we work with these options if self.reversible and not _tmatrix_disconnected.is_connected(C, strong=True): raise NotImplementedError('Encountered disconnected count matrix w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _generateInitialModel(self, output_model_type): """Initialize using an MLHMM. """
logger().info("Generating initial model for BHMM using MLHMM...") from bhmm.estimators.maximum_likelihood import MaximumLikelihoodEstimator mlhmm = MaximumLikelihoodEstimator(self.observations, self.nstates, reversible=self.reversible, output=output_mo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connected_sets(C, mincount_connectivity=0, strong=True): """ Computes the connected sets of C. C : count matrix mincount_connectivity : float Minimum count w...
import msmtools.estimation as msmest Cconn = C.copy() Cconn[np.where(C <= mincount_connectivity)] = 0 # treat each connected set separately S = msmest.connected_sets(Cconn, directed=strong) return S
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def closed_sets(C, mincount_connectivity=0): """ Computes the strongly connected closed sets of C """
n = np.shape(C)[0] S = connected_sets(C, mincount_connectivity=mincount_connectivity, strong=True) closed = [] for s in S: mask = np.zeros(n, dtype=bool) mask[s] = True if C[np.ix_(mask, ~mask)].sum() == 0: # closed set, take it closed.append(s) return closed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nonempty_set(C, mincount_connectivity=0): """ Returns the set of states that have at least one incoming or outgoing count """
# truncate to states with at least one observed incoming or outgoing count. if mincount_connectivity > 0: C = C.copy() C[np.where(C < mincount_connectivity)] = 0 return np.where(C.sum(axis=0) + C.sum(axis=1) > 0)[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 estimate_P(C, reversible=True, fixed_statdist=None, maxiter=1000000, maxerr=1e-8, mincount_connectivity=0): """ Estimates full transition matrix for general ...
import msmtools.estimation as msmest n = np.shape(C)[0] # output matrix. Set initially to Identity matrix in order to handle empty states P = np.eye(n, dtype=np.float64) # decide if we need to proceed by weakly or strongly connected sets if reversible and fixed_statdist is None: # reversible t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transition_matrix_partial_rev(C, P, S, maxiter=1000000, maxerr=1e-8): """Maximum likelihood estimation of transition matrix which is reversible on parts Part...
# test input assert np.array_equal(C.shape, P.shape) # constants A = C[S][:, S] B = C[S][:, ~S] ATA = A + A.T countsums = C[S].sum(axis=1) # initialize X = 0.5 * ATA Y = C[S][:, ~S] # normalize X, Y totalsum = X.sum() + Y.sum() X /= totalsum Y /= totalsum # 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 enforce_reversible_on_closed(P): """ Enforces transition matrix P to be reversible on its closed sets. """
import msmtools.analysis as msmana n = np.shape(P)[0] Prev = P.copy() # treat each weakly connected set separately sets = closed_sets(P) for s in sets: I = np.ix_(s, s) # compute stationary probability pi_s = msmana.stationary_distribution(P[I]) # symmetrize ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_reversible(P): """ Returns if P is reversible on its weakly connected sets """
import msmtools.analysis as msmana # treat each weakly connected set separately sets = connected_sets(P, strong=False) for s in sets: Ps = P[s, :][:, s] if not msmana.is_transition_matrix(Ps): return False # isn't even a transition matrix! pi = msmana.stationary_dis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stationary_distribution(P, C=None, mincount_connectivity=0): """ Simple estimator for stationary distribution for multiple strongly connected sets """
# can be replaced by msmtools.analysis.stationary_distribution in next msmtools release from msmtools.analysis.dense.stationary_vector import stationary_distribution as msmstatdist if C is None: if is_connected(P, strong=True): return msmstatdist(P) else: raise 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 means_samples(self): r""" Samples of the Gaussian distribution means """
res = np.empty((self.nsamples, self.nstates, self.dimension), dtype=config.dtype) for i in range(self.nsamples): for j in range(self.nstates): res[i, j, :] = self._sampled_hmms[i].means[j] return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sigmas_samples(self): r""" Samples of the Gaussian distribution standard deviations """
res = np.empty((self.nsamples, self.nstates, self.dimension), dtype=config.dtype) for i in range(self.nsamples): for j in range(self.nstates): res[i, j, :] = self._sampled_hmms[i].sigmas[j] return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _guess_output_type(observations): """ Suggests a HMM model type based on the observation data Uses simple rules in order to decide which HMM model type makes...
from bhmm.util import types as _types o1 = _np.array(observations[0]) # CASE: vector of int? Then we want a discrete HMM if _types.is_int_vector(o1): return 'discrete' # CASE: not int type, but everything is an integral number. Then we also go for discrete if _np.allclose(o1, _np.rou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lag_observations(observations, lag, stride=1): r""" Create new trajectories that are subsampled at lag but shifted at lag times larger than 1 without discard...
obsnew = [] for obs in observations: for shift in range(0, lag, stride): obs_lagged = (obs[shift:][::lag]) if len(obs_lagged) > 1: obsnew.append(obs_lagged) return obsnew
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gaussian_hmm(pi, P, means, sigmas): """ Initializes a 1D-Gaussian HMM Parameters pi : ndarray(nstates, ) Initial distribution. P : ndarray(nstates,nstates) H...
from bhmm.hmm.gaussian_hmm import GaussianHMM from bhmm.output_models.gaussian import GaussianOutputModel # count states nstates = _np.array(P).shape[0] # initialize output model output_model = GaussianOutputModel(nstates, means, sigmas) # initialize general HMM from bhmm.hmm.generic_hm...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discrete_hmm(pi, P, pout): """ Initializes a discrete HMM Parameters pi : ndarray(nstates, ) Initial distribution. P : ndarray(nstates,nstates) Hidden transi...
from bhmm.hmm.discrete_hmm import DiscreteHMM from bhmm.output_models.discrete import DiscreteOutputModel # initialize output model output_model = DiscreteOutputModel(pout) # initialize general HMM from bhmm.hmm.generic_hmm import HMM as _HMM dhmm = _HMM(pi, P, output_model) # turn it i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def estimate_hmm(observations, nstates, lag=1, initial_model=None, output=None, reversible=True, stationary=False, p=None, accuracy=1e-3, maxit=1000, maxit_P=1000...
# select output model type if output is None: output = _guess_output_type(observations) if lag > 1: observations = lag_observations(observations, lag) # construct estimator from bhmm.estimators.maximum_likelihood import MaximumLikelihoodEstimator as _MaximumLikelihoodEstimator ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bayesian_hmm(observations, estimated_hmm, nsample=100, reversible=True, stationary=False, p0_prior='mixed', transition_matrix_prior='mixed', store_hidden=Fals...
# construct estimator from bhmm.estimators.bayesian_sampling import BayesianHMMSampler as _BHMM sampler = _BHMM(observations, estimated_hmm.nstates, initial_model=estimated_hmm, reversible=reversible, stationary=stationary, transition_matrix_sampling_steps=1000, p0_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 logsumexp(arr, axis=0): """Computes the sum of arr assuming arr is in the log domain. Returns log(sum(exp(arr))) while minimizing the possibility of over/und...
arr = np.rollaxis(arr, axis) # Use the max to normalize, as with the log this is what accumulates # the less errors vmax = arr.max(axis=0) out = np.log(np.sum(np.exp(arr - vmax), axis=0)) out += vmax return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _ensure_sparse_format(spmatrix, accept_sparse, dtype, order, copy, force_all_finite): """Convert a sparse matrix to a given format. Checks the sparse format ...
if accept_sparse is None: raise TypeError('A sparse matrix was passed, but dense ' 'data is required. Use X.toarray() to ' 'convert to a dense numpy array.') sparse_type = spmatrix.format if dtype is None: dtype = spmatrix.dtype if sparse_...
<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_array(array, accept_sparse=None, dtype="numeric", order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, ensure_min_samples=1, e...
if isinstance(accept_sparse, str): accept_sparse = [accept_sparse] # store whether originally we wanted numeric dtype dtype_numeric = dtype == "numeric" if sp.issparse(array): if dtype_numeric: dtype = None array = _ensure_sparse_format(array, accept_sparse, dtype,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def beta_confidence_intervals(ci_X, ntrials, ci=0.95): """ Compute confidence intervals of beta distributions. Parameters ci_X : numpy.array Computed confidence ...
# Compute low and high confidence interval for symmetric CI about mean. ci_low = 0.5 - ci/2; ci_high = 0.5 + ci/2; # Compute for every element of ci_X. from scipy.stats import beta Plow = ci_X * 0.0; Phigh = ci_X * 0.0; for i in range(ci_X.shape[0]): for j in range(ci_X.shape[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 empirical_confidence_interval(sample, interval=0.95): """ Compute specified symmetric confidence interval for empirical sample. Parameters sample : numpy.arr...
# Sort sample in increasing order. sample = np.sort(sample) # Determine sample size. N = len(sample) # Compute low and high indices. low_index = int(np.round((N-1) * (0.5 - interval/2))) + 1 high_index = int(np.round((N-1) * (0.5 + interval/2))) + 1 # Compute low and high. low = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def confidence_interval(data, alpha): """ Computes the mean and alpha-confidence interval of the given sample set Parameters data : ndarray a 1D-array of samples...
if alpha < 0 or alpha > 1: raise ValueError('Not a meaningful confidence level: '+str(alpha)) # compute mean m = np.mean(data) # sort data sdata = np.sort(data) # index of the mean im = np.searchsorted(sdata, m) if im == 0 or im == len(sdata): pm = im else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def status(self, remote=False): """ Return the connection status, both locally and remotely. The local connection status is a dictionary that gives: * the count ...
if remote: components = urlparse.urlparse(self.endpoint) try: result = self.session.get(components[0] + "://" + components[1] + "/status", timeout=self.timeout) except Exception as e: if self.logger: self.logger.debug("Failed to connect to ser...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, **kwargs): """ Add commands at the end of the sequence. Be careful: because this runs in Python 2.x, the order of the kwargs dict may not match ...
for k, v in six.iteritems(kwargs): self.commands.append({k: v}) 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 insert(self, **kwargs): """ Insert commands at the beginning of the sequence. This is provided because certain commands have to come first (such as user crea...
for k, v in six.iteritems(kwargs): self.commands.insert(0, {k: v}) 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 report_command_error(self, error_dict): """ Report a server error executing a command. We keep track of the command's position in the command list, and we ad...
error = dict(error_dict) error["command"] = self.commands[error_dict["step"]] error["target"] = self.frame del error["index"] # throttling can change which action this was in the batch del error["step"] # throttling can change which step this was in the action self.er...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execution_errors(self): """ Return a list of commands that encountered execution errors, with the error. Each dictionary entry gives the command dictionary a...
if self.split_actions: # throttling split this action, get errors from the split return [dict(e) for s in self.split_actions for e in s.errors] else: return [dict(e) for e in self.errors]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _next_page(self): """ Fetch the next page of the query. """
if self._last_page_seen: raise StopIteration new, self._last_page_seen = self.conn.query_multiple(self.object_type, self._next_page_index, self.url_params, self.query_params) self._next_page_index += 1 if len(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 _fetch_result(self): """ Fetch the queried object. """
self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scale2x(self, surface): """ Scales using the AdvanceMAME Scale2X algorithm which does a 'jaggie-less' scale of bitmap graphics. """
assert(self._scale == 2) return self._pygame.transform.scale2x(surface)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smoothscale(self, surface): """ Smooth scaling using MMX or SSE extensions if available """
return self._pygame.transform.smoothscale(surface, self._output_size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def identity(self, surface): """ Fast scale operation that does not sample the results """
return self._pygame.transform.scale(surface, self._output_size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rgb2short(r, g, b): """ Converts RGB values to the nearest equivalent xterm-256 color. """
# Using list of snap points, convert RGB value to cube indexes r, g, b = [len(tuple(s for s in snaps if s < x)) for x in (r, g, b)] # Simple colorcube transform return (r * 36) + (g * 6) + b + 16
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display(self, image): """ Takes an image, scales it according to the nominated transform, and stores it for later building into an animated GIF. """
assert(image.size == self.size) self._last_image = image image = self.preprocess(image) surface = self.to_surface(image, alpha=self._contrast) rawbytes = self._pygame.image.tostring(surface, "RGB", False) im = Image.frombytes("RGB", surface.get_size(), rawbytes) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _char_density(self, c, font=ImageFont.load_default()): """ Count the number of black pixels in a rendered character. """
image = Image.new('1', font.getsize(c), color=255) draw = ImageDraw.Draw(image) draw.text((0, 0), c, fill="white", font=font) return collections.Counter(image.getdata())[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 _CSI(self, cmd): """ Control sequence introducer """
sys.stdout.write('\x1b[') sys.stdout.write(cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find(path, level=None, message=None, time_lower=None, time_upper=None, case_sensitive=False): # pragma: no cover """ Filter log message. **中文文档** 根据level名称, ...
if level: level = level.upper() # level name has to be capitalized. if not case_sensitive: message = message.lower() with open(path, "r") as f: result = Result(path=path, level=level, message=message, time_lower=time_lower, time_upp...