repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.predict
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)
python
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)
[ "def", "predict", "(", "self", ",", "X", ")", ":", "logprob", ",", "responsibilities", "=", "self", ".", "score_samples", "(", "X", ")", "return", "responsibilities", ".", "argmax", "(", "axis", "=", "1", ")" ]
Predict label for data. Parameters ---------- X : array-like, shape = [n_samples, n_features] Returns ------- C : array, shape = (n_samples,)
[ "Predict", "label", "for", "data", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L341-L353
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.sample
def sample(self, n_samples=1, random_state=None): """Generate random samples from the model. Parameters ---------- n_samples : int, optional Number of samples to generate. Defaults to 1. Returns ------- X : array_like, shape (n_samples, n_features) List of samples """ check_is_fitted(self, 'means_') if random_state is None: random_state = self.random_state random_state = check_random_state(random_state) weight_cdf = np.cumsum(self.weights_) X = np.empty((n_samples, self.means_.shape[1])) rand = random_state.rand(n_samples) # decide which component to use for each sample comps = weight_cdf.searchsorted(rand) # for each component, generate all needed samples for comp in range(self.n_components): # occurrences of current component in X comp_in_X = (comp == comps) # number of those occurrences num_comp_in_X = comp_in_X.sum() if num_comp_in_X > 0: if self.covariance_type == 'tied': cv = self.covars_ elif self.covariance_type == 'spherical': cv = self.covars_[comp][0] else: cv = self.covars_[comp] X[comp_in_X] = sample_gaussian( self.means_[comp], cv, self.covariance_type, num_comp_in_X, random_state=random_state).T return X
python
def sample(self, n_samples=1, random_state=None): """Generate random samples from the model. Parameters ---------- n_samples : int, optional Number of samples to generate. Defaults to 1. Returns ------- X : array_like, shape (n_samples, n_features) List of samples """ check_is_fitted(self, 'means_') if random_state is None: random_state = self.random_state random_state = check_random_state(random_state) weight_cdf = np.cumsum(self.weights_) X = np.empty((n_samples, self.means_.shape[1])) rand = random_state.rand(n_samples) # decide which component to use for each sample comps = weight_cdf.searchsorted(rand) # for each component, generate all needed samples for comp in range(self.n_components): # occurrences of current component in X comp_in_X = (comp == comps) # number of those occurrences num_comp_in_X = comp_in_X.sum() if num_comp_in_X > 0: if self.covariance_type == 'tied': cv = self.covars_ elif self.covariance_type == 'spherical': cv = self.covars_[comp][0] else: cv = self.covars_[comp] X[comp_in_X] = sample_gaussian( self.means_[comp], cv, self.covariance_type, num_comp_in_X, random_state=random_state).T return X
[ "def", "sample", "(", "self", ",", "n_samples", "=", "1", ",", "random_state", "=", "None", ")", ":", "check_is_fitted", "(", "self", ",", "'means_'", ")", "if", "random_state", "is", "None", ":", "random_state", "=", "self", ".", "random_state", "random_state", "=", "check_random_state", "(", "random_state", ")", "weight_cdf", "=", "np", ".", "cumsum", "(", "self", ".", "weights_", ")", "X", "=", "np", ".", "empty", "(", "(", "n_samples", ",", "self", ".", "means_", ".", "shape", "[", "1", "]", ")", ")", "rand", "=", "random_state", ".", "rand", "(", "n_samples", ")", "# decide which component to use for each sample", "comps", "=", "weight_cdf", ".", "searchsorted", "(", "rand", ")", "# for each component, generate all needed samples", "for", "comp", "in", "range", "(", "self", ".", "n_components", ")", ":", "# occurrences of current component in X", "comp_in_X", "=", "(", "comp", "==", "comps", ")", "# number of those occurrences", "num_comp_in_X", "=", "comp_in_X", ".", "sum", "(", ")", "if", "num_comp_in_X", ">", "0", ":", "if", "self", ".", "covariance_type", "==", "'tied'", ":", "cv", "=", "self", ".", "covars_", "elif", "self", ".", "covariance_type", "==", "'spherical'", ":", "cv", "=", "self", ".", "covars_", "[", "comp", "]", "[", "0", "]", "else", ":", "cv", "=", "self", ".", "covars_", "[", "comp", "]", "X", "[", "comp_in_X", "]", "=", "sample_gaussian", "(", "self", ".", "means_", "[", "comp", "]", ",", "cv", ",", "self", ".", "covariance_type", ",", "num_comp_in_X", ",", "random_state", "=", "random_state", ")", ".", "T", "return", "X" ]
Generate random samples from the model. Parameters ---------- n_samples : int, optional Number of samples to generate. Defaults to 1. Returns ------- X : array_like, shape (n_samples, n_features) List of samples
[ "Generate", "random", "samples", "from", "the", "model", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L372-L412
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.fit
def fit(self, X, y=None): """Estimate model parameters with the expectation-maximization algorithm. A initialization step is performed before entering the em algorithm. If you want to avoid this step, set the keyword argument init_params to the empty string '' when creating the GMM object. Likewise, if you would like just to do an initialization, set n_iter=0. Parameters ---------- X : array_like, shape (n, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. """ # 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 for _ in range(self.n_init): if 'm' in self.init_params or not hasattr(self, 'means_'): if np.issubdtype(X.dtype, np.float32): from bhmm._external.clustering.kmeans_clustering_32 import init_centers elif np.issubdtype(X.dtype, np.float64): from bhmm._external.clustering.kmeans_clustering_64 import init_centers else: raise ValueError("Could not handle dtype %s for clustering!" % X.dtype) centers = init_centers(X, 'euclidean', self.n_components) self.means_ = centers if 'w' in self.init_params or not hasattr(self, 'weights_'): self.weights_ = np.tile(1.0 / self.n_components, self.n_components) if 'c' in self.init_params or not hasattr(self, 'covars_'): cv = np.cov(X.T) + self.min_covar * np.eye(X.shape[1]) if not cv.shape: cv.shape = (1, 1) self.covars_ = \ distribute_covar_matrix_to_match_covariance_type( cv, self.covariance_type, self.n_components) # EM algorithms current_log_likelihood = None # reset self.converged_ to False self.converged_ = False # this line should be removed when 'thresh' is removed in v0.18 tol = (self.tol if self.thresh is None else self.thresh / float(X.shape[0])) for i in range(self.n_iter): prev_log_likelihood = current_log_likelihood # Expectation step log_likelihoods, responsibilities = self.score_samples(X) current_log_likelihood = log_likelihoods.mean() # Check for convergence. # (should compare to self.tol when dreprecated 'thresh' is # removed in v0.18) if prev_log_likelihood is not None: change = abs(current_log_likelihood - prev_log_likelihood) if change < tol: self.converged_ = True break # Maximization step self._do_mstep(X, responsibilities, self.params, self.min_covar) # if the results are better, keep it if self.n_iter: if current_log_likelihood > max_log_prob: max_log_prob = current_log_likelihood best_params = {'weights': self.weights_, 'means': self.means_, 'covars': self.covars_} # check the existence of an init param that was not subject to # likelihood computation issue. if np.isneginf(max_log_prob) and self.n_iter: raise RuntimeError( "EM algorithm was never able to compute a valid likelihood " + "given initial parameters. Try different init parameters " + "(or increasing n_init) or check for degenerate data.") # self.n_iter == 0 occurs when using GMM within HMM if self.n_iter: self.covars_ = best_params['covars'] self.means_ = best_params['means'] self.weights_ = best_params['weights'] return self
python
def fit(self, X, y=None): """Estimate model parameters with the expectation-maximization algorithm. A initialization step is performed before entering the em algorithm. If you want to avoid this step, set the keyword argument init_params to the empty string '' when creating the GMM object. Likewise, if you would like just to do an initialization, set n_iter=0. Parameters ---------- X : array_like, shape (n, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. """ # 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 for _ in range(self.n_init): if 'm' in self.init_params or not hasattr(self, 'means_'): if np.issubdtype(X.dtype, np.float32): from bhmm._external.clustering.kmeans_clustering_32 import init_centers elif np.issubdtype(X.dtype, np.float64): from bhmm._external.clustering.kmeans_clustering_64 import init_centers else: raise ValueError("Could not handle dtype %s for clustering!" % X.dtype) centers = init_centers(X, 'euclidean', self.n_components) self.means_ = centers if 'w' in self.init_params or not hasattr(self, 'weights_'): self.weights_ = np.tile(1.0 / self.n_components, self.n_components) if 'c' in self.init_params or not hasattr(self, 'covars_'): cv = np.cov(X.T) + self.min_covar * np.eye(X.shape[1]) if not cv.shape: cv.shape = (1, 1) self.covars_ = \ distribute_covar_matrix_to_match_covariance_type( cv, self.covariance_type, self.n_components) # EM algorithms current_log_likelihood = None # reset self.converged_ to False self.converged_ = False # this line should be removed when 'thresh' is removed in v0.18 tol = (self.tol if self.thresh is None else self.thresh / float(X.shape[0])) for i in range(self.n_iter): prev_log_likelihood = current_log_likelihood # Expectation step log_likelihoods, responsibilities = self.score_samples(X) current_log_likelihood = log_likelihoods.mean() # Check for convergence. # (should compare to self.tol when dreprecated 'thresh' is # removed in v0.18) if prev_log_likelihood is not None: change = abs(current_log_likelihood - prev_log_likelihood) if change < tol: self.converged_ = True break # Maximization step self._do_mstep(X, responsibilities, self.params, self.min_covar) # if the results are better, keep it if self.n_iter: if current_log_likelihood > max_log_prob: max_log_prob = current_log_likelihood best_params = {'weights': self.weights_, 'means': self.means_, 'covars': self.covars_} # check the existence of an init param that was not subject to # likelihood computation issue. if np.isneginf(max_log_prob) and self.n_iter: raise RuntimeError( "EM algorithm was never able to compute a valid likelihood " + "given initial parameters. Try different init parameters " + "(or increasing n_init) or check for degenerate data.") # self.n_iter == 0 occurs when using GMM within HMM if self.n_iter: self.covars_ = best_params['covars'] self.means_ = best_params['means'] self.weights_ = best_params['weights'] return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "# 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", "for", "_", "in", "range", "(", "self", ".", "n_init", ")", ":", "if", "'m'", "in", "self", ".", "init_params", "or", "not", "hasattr", "(", "self", ",", "'means_'", ")", ":", "if", "np", ".", "issubdtype", "(", "X", ".", "dtype", ",", "np", ".", "float32", ")", ":", "from", "bhmm", ".", "_external", ".", "clustering", ".", "kmeans_clustering_32", "import", "init_centers", "elif", "np", ".", "issubdtype", "(", "X", ".", "dtype", ",", "np", ".", "float64", ")", ":", "from", "bhmm", ".", "_external", ".", "clustering", ".", "kmeans_clustering_64", "import", "init_centers", "else", ":", "raise", "ValueError", "(", "\"Could not handle dtype %s for clustering!\"", "%", "X", ".", "dtype", ")", "centers", "=", "init_centers", "(", "X", ",", "'euclidean'", ",", "self", ".", "n_components", ")", "self", ".", "means_", "=", "centers", "if", "'w'", "in", "self", ".", "init_params", "or", "not", "hasattr", "(", "self", ",", "'weights_'", ")", ":", "self", ".", "weights_", "=", "np", ".", "tile", "(", "1.0", "/", "self", ".", "n_components", ",", "self", ".", "n_components", ")", "if", "'c'", "in", "self", ".", "init_params", "or", "not", "hasattr", "(", "self", ",", "'covars_'", ")", ":", "cv", "=", "np", ".", "cov", "(", "X", ".", "T", ")", "+", "self", ".", "min_covar", "*", "np", ".", "eye", "(", "X", ".", "shape", "[", "1", "]", ")", "if", "not", "cv", ".", "shape", ":", "cv", ".", "shape", "=", "(", "1", ",", "1", ")", "self", ".", "covars_", "=", "distribute_covar_matrix_to_match_covariance_type", "(", "cv", ",", "self", ".", "covariance_type", ",", "self", ".", "n_components", ")", "# EM algorithms", "current_log_likelihood", "=", "None", "# reset self.converged_ to False", "self", ".", "converged_", "=", "False", "# this line should be removed when 'thresh' is removed in v0.18", "tol", "=", "(", "self", ".", "tol", "if", "self", ".", "thresh", "is", "None", "else", "self", ".", "thresh", "/", "float", "(", "X", ".", "shape", "[", "0", "]", ")", ")", "for", "i", "in", "range", "(", "self", ".", "n_iter", ")", ":", "prev_log_likelihood", "=", "current_log_likelihood", "# Expectation step", "log_likelihoods", ",", "responsibilities", "=", "self", ".", "score_samples", "(", "X", ")", "current_log_likelihood", "=", "log_likelihoods", ".", "mean", "(", ")", "# Check for convergence.", "# (should compare to self.tol when dreprecated 'thresh' is", "# removed in v0.18)", "if", "prev_log_likelihood", "is", "not", "None", ":", "change", "=", "abs", "(", "current_log_likelihood", "-", "prev_log_likelihood", ")", "if", "change", "<", "tol", ":", "self", ".", "converged_", "=", "True", "break", "# Maximization step", "self", ".", "_do_mstep", "(", "X", ",", "responsibilities", ",", "self", ".", "params", ",", "self", ".", "min_covar", ")", "# if the results are better, keep it", "if", "self", ".", "n_iter", ":", "if", "current_log_likelihood", ">", "max_log_prob", ":", "max_log_prob", "=", "current_log_likelihood", "best_params", "=", "{", "'weights'", ":", "self", ".", "weights_", ",", "'means'", ":", "self", ".", "means_", ",", "'covars'", ":", "self", ".", "covars_", "}", "# check the existence of an init param that was not subject to", "# likelihood computation issue.", "if", "np", ".", "isneginf", "(", "max_log_prob", ")", "and", "self", ".", "n_iter", ":", "raise", "RuntimeError", "(", "\"EM algorithm was never able to compute a valid likelihood \"", "+", "\"given initial parameters. Try different init parameters \"", "+", "\"(or increasing n_init) or check for degenerate data.\"", ")", "# self.n_iter == 0 occurs when using GMM within HMM", "if", "self", ".", "n_iter", ":", "self", ".", "covars_", "=", "best_params", "[", "'covars'", "]", "self", ".", "means_", "=", "best_params", "[", "'means'", "]", "self", ".", "weights_", "=", "best_params", "[", "'weights'", "]", "return", "self" ]
Estimate model parameters with the expectation-maximization algorithm. A initialization step is performed before entering the em algorithm. If you want to avoid this step, set the keyword argument init_params to the empty string '' when creating the GMM object. Likewise, if you would like just to do an initialization, set n_iter=0. Parameters ---------- X : array_like, shape (n, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point.
[ "Estimate", "model", "parameters", "with", "the", "expectation", "-", "maximization", "algorithm", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L414-L509
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM._do_mstep
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_ = weighted_X_sum * inverse_weights if 'c' in params: covar_mstep_func = _covar_mstep_funcs[self.covariance_type] self.covars_ = covar_mstep_func( self, X, responsibilities, weighted_X_sum, inverse_weights, min_covar) return weights
python
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_ = weighted_X_sum * inverse_weights if 'c' in params: covar_mstep_func = _covar_mstep_funcs[self.covariance_type] self.covars_ = covar_mstep_func( self, X, responsibilities, weighted_X_sum, inverse_weights, min_covar) return weights
[ "def", "_do_mstep", "(", "self", ",", "X", ",", "responsibilities", ",", "params", ",", "min_covar", "=", "0", ")", ":", "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_", "=", "weighted_X_sum", "*", "inverse_weights", "if", "'c'", "in", "params", ":", "covar_mstep_func", "=", "_covar_mstep_funcs", "[", "self", ".", "covariance_type", "]", "self", ".", "covars_", "=", "covar_mstep_func", "(", "self", ",", "X", ",", "responsibilities", ",", "weighted_X_sum", ",", "inverse_weights", ",", "min_covar", ")", "return", "weights" ]
Perform the Mstep of the EM algorithm and return the class weihgts.
[ "Perform", "the", "Mstep", "of", "the", "EM", "algorithm", "and", "return", "the", "class", "weihgts", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L511-L527
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM._n_parameters
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 * (ndim + 1) / 2. elif self.covariance_type == 'spherical': cov_params = self.n_components mean_params = ndim * self.n_components return int(cov_params + mean_params + self.n_components - 1)
python
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 * (ndim + 1) / 2. elif self.covariance_type == 'spherical': cov_params = self.n_components mean_params = ndim * self.n_components return int(cov_params + mean_params + self.n_components - 1)
[ "def", "_n_parameters", "(", "self", ")", ":", "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", "*", "(", "ndim", "+", "1", ")", "/", "2.", "elif", "self", ".", "covariance_type", "==", "'spherical'", ":", "cov_params", "=", "self", ".", "n_components", "mean_params", "=", "ndim", "*", "self", ".", "n_components", "return", "int", "(", "cov_params", "+", "mean_params", "+", "self", ".", "n_components", "-", "1", ")" ]
Return the number of free parameters in the model.
[ "Return", "the", "number", "of", "free", "parameters", "in", "the", "model", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L529-L541
bhmm/bhmm
bhmm/_external/sklearn/mixture/gmm.py
GMM.bic
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) Returns ------- bic: float (the lower the better) """ return (-2 * self.score(X).sum() + self._n_parameters() * np.log(X.shape[0]))
python
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) Returns ------- bic: float (the lower the better) """ return (-2 * self.score(X).sum() + self._n_parameters() * np.log(X.shape[0]))
[ "def", "bic", "(", "self", ",", "X", ")", ":", "return", "(", "-", "2", "*", "self", ".", "score", "(", "X", ")", ".", "sum", "(", ")", "+", "self", ".", "_n_parameters", "(", ")", "*", "np", ".", "log", "(", "X", ".", "shape", "[", "0", "]", ")", ")" ]
Bayesian information criterion for the current model fit and the proposed data Parameters ---------- X : array of shape(n_samples, n_dimensions) Returns ------- bic: float (the lower the better)
[ "Bayesian", "information", "criterion", "for", "the", "current", "model", "fit", "and", "the", "proposed", "data" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/mixture/gmm.py#L543-L556
bhmm/bhmm
bhmm/_external/sklearn/base.py
BaseEstimator._get_param_names
def _get_param_names(cls): """Get parameter names for the estimator""" # fetch the constructor or the original constructor before # deprecation wrapping if any init = getattr(cls.__init__, 'deprecated_original', cls.__init__) if init is object.__init__: # No explicit constructor to introspect return [] # introspect the constructor arguments to find the model parameters # to represent args, varargs, kw, default = inspect.getargspec(init) if varargs is not None: raise RuntimeError("scikit-learn estimators should always " "specify their parameters in the signature" " of their __init__ (no varargs)." " %s doesn't follow this convention." % (cls, )) # Remove 'self' # XXX: This is going to fail if the init is a staticmethod, but # who would do this? args.pop(0) args.sort() return args
python
def _get_param_names(cls): """Get parameter names for the estimator""" # fetch the constructor or the original constructor before # deprecation wrapping if any init = getattr(cls.__init__, 'deprecated_original', cls.__init__) if init is object.__init__: # No explicit constructor to introspect return [] # introspect the constructor arguments to find the model parameters # to represent args, varargs, kw, default = inspect.getargspec(init) if varargs is not None: raise RuntimeError("scikit-learn estimators should always " "specify their parameters in the signature" " of their __init__ (no varargs)." " %s doesn't follow this convention." % (cls, )) # Remove 'self' # XXX: This is going to fail if the init is a staticmethod, but # who would do this? args.pop(0) args.sort() return args
[ "def", "_get_param_names", "(", "cls", ")", ":", "# fetch the constructor or the original constructor before", "# deprecation wrapping if any", "init", "=", "getattr", "(", "cls", ".", "__init__", ",", "'deprecated_original'", ",", "cls", ".", "__init__", ")", "if", "init", "is", "object", ".", "__init__", ":", "# No explicit constructor to introspect", "return", "[", "]", "# introspect the constructor arguments to find the model parameters", "# to represent", "args", ",", "varargs", ",", "kw", ",", "default", "=", "inspect", ".", "getargspec", "(", "init", ")", "if", "varargs", "is", "not", "None", ":", "raise", "RuntimeError", "(", "\"scikit-learn estimators should always \"", "\"specify their parameters in the signature\"", "\" of their __init__ (no varargs).\"", "\" %s doesn't follow this convention.\"", "%", "(", "cls", ",", ")", ")", "# Remove 'self'", "# XXX: This is going to fail if the init is a staticmethod, but", "# who would do this?", "args", ".", "pop", "(", "0", ")", "args", ".", "sort", "(", ")", "return", "args" ]
Get parameter names for the estimator
[ "Get", "parameter", "names", "for", "the", "estimator" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/base.py#L67-L90
bhmm/bhmm
bhmm/_external/sklearn/base.py
BaseEstimator.set_params
def set_params(self, **params): """Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as pipelines). The former have parameters of the form ``<component>__<parameter>`` so that it's possible to update each component of a nested object. Returns ------- self """ if not params: # Simple optimisation to gain speed (inspect is slow) return self valid_params = self.get_params(deep=True) for key, value in six.iteritems(params): split = key.split('__', 1) if len(split) > 1: # nested objects case name, sub_name = split if not name in valid_params: raise ValueError('Invalid parameter %s for estimator %s' % (name, self)) sub_object = valid_params[name] sub_object.set_params(**{sub_name: value}) else: # simple objects case if not key in valid_params: raise ValueError('Invalid parameter %s ' 'for estimator %s' % (key, self.__class__.__name__)) setattr(self, key, value) return self
python
def set_params(self, **params): """Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as pipelines). The former have parameters of the form ``<component>__<parameter>`` so that it's possible to update each component of a nested object. Returns ------- self """ if not params: # Simple optimisation to gain speed (inspect is slow) return self valid_params = self.get_params(deep=True) for key, value in six.iteritems(params): split = key.split('__', 1) if len(split) > 1: # nested objects case name, sub_name = split if not name in valid_params: raise ValueError('Invalid parameter %s for estimator %s' % (name, self)) sub_object = valid_params[name] sub_object.set_params(**{sub_name: value}) else: # simple objects case if not key in valid_params: raise ValueError('Invalid parameter %s ' 'for estimator %s' % (key, self.__class__.__name__)) setattr(self, key, value) return self
[ "def", "set_params", "(", "self", ",", "*", "*", "params", ")", ":", "if", "not", "params", ":", "# Simple optimisation to gain speed (inspect is slow)", "return", "self", "valid_params", "=", "self", ".", "get_params", "(", "deep", "=", "True", ")", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "params", ")", ":", "split", "=", "key", ".", "split", "(", "'__'", ",", "1", ")", "if", "len", "(", "split", ")", ">", "1", ":", "# nested objects case", "name", ",", "sub_name", "=", "split", "if", "not", "name", "in", "valid_params", ":", "raise", "ValueError", "(", "'Invalid parameter %s for estimator %s'", "%", "(", "name", ",", "self", ")", ")", "sub_object", "=", "valid_params", "[", "name", "]", "sub_object", ".", "set_params", "(", "*", "*", "{", "sub_name", ":", "value", "}", ")", "else", ":", "# simple objects case", "if", "not", "key", "in", "valid_params", ":", "raise", "ValueError", "(", "'Invalid parameter %s '", "'for estimator %s'", "%", "(", "key", ",", "self", ".", "__class__", ".", "__name__", ")", ")", "setattr", "(", "self", ",", "key", ",", "value", ")", "return", "self" ]
Set the parameters of this estimator. The method works on simple estimators as well as on nested objects (such as pipelines). The former have parameters of the form ``<component>__<parameter>`` so that it's possible to update each component of a nested object. Returns ------- self
[ "Set", "the", "parameters", "of", "this", "estimator", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/base.py#L129-L161
bhmm/bhmm
bhmm/init/gaussian.py
init_model_gaussian1d
def init_model_gaussian1d(observations, nstates, reversible=True): """Generate an initial model with 1D-Gaussian output densities Parameters ---------- observations : list of ndarray((T_i), dtype=float) list of arrays of length T_i with observation data nstates : int The number of states. Examples -------- Generate initial model for a gaussian output model. >>> from bhmm import testsystems >>> [model, observations, states] = testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_model_gaussian1d(observations, model.nstates) """ 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 stationary probabilities. from bhmm._external.sklearn import mixture gmm = mixture.GMM(n_components=nstates) gmm.fit(collected_observations[:,None]) from bhmm import GaussianOutputModel output_model = GaussianOutputModel(nstates, means=gmm.means_[:,0], sigmas=np.sqrt(gmm.covars_[:,0])) logger().info("Gaussian output model:\n"+str(output_model)) # Extract stationary distributions. Pi = np.zeros([nstates], np.float64) Pi[:] = gmm.weights_[:] logger().info("GMM weights: %s" % str(gmm.weights_)) # Compute fractional state memberships. Nij = np.zeros([nstates, nstates], np.float64) for o_t in observations: # length of trajectory T = o_t.shape[0] # output probability pobs = output_model.p_obs(o_t) # normalize pobs /= pobs.sum(axis=1)[:,None] # Accumulate fractional transition counts from this trajectory. for t in range(T-1): Nij[:,:] = Nij[:,:] + np.outer(pobs[t,:], pobs[t+1,:]) logger().info("Nij\n"+str(Nij)) # Compute transition matrix maximum likelihood estimate. import msmtools.estimation as msmest import msmtools.analysis as msmana Tij = msmest.transition_matrix(Nij, reversible=reversible) pi = msmana.stationary_distribution(Tij) # Update model. model = HMM(pi, Tij, output_model) return model
python
def init_model_gaussian1d(observations, nstates, reversible=True): """Generate an initial model with 1D-Gaussian output densities Parameters ---------- observations : list of ndarray((T_i), dtype=float) list of arrays of length T_i with observation data nstates : int The number of states. Examples -------- Generate initial model for a gaussian output model. >>> from bhmm import testsystems >>> [model, observations, states] = testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_model_gaussian1d(observations, model.nstates) """ 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 stationary probabilities. from bhmm._external.sklearn import mixture gmm = mixture.GMM(n_components=nstates) gmm.fit(collected_observations[:,None]) from bhmm import GaussianOutputModel output_model = GaussianOutputModel(nstates, means=gmm.means_[:,0], sigmas=np.sqrt(gmm.covars_[:,0])) logger().info("Gaussian output model:\n"+str(output_model)) # Extract stationary distributions. Pi = np.zeros([nstates], np.float64) Pi[:] = gmm.weights_[:] logger().info("GMM weights: %s" % str(gmm.weights_)) # Compute fractional state memberships. Nij = np.zeros([nstates, nstates], np.float64) for o_t in observations: # length of trajectory T = o_t.shape[0] # output probability pobs = output_model.p_obs(o_t) # normalize pobs /= pobs.sum(axis=1)[:,None] # Accumulate fractional transition counts from this trajectory. for t in range(T-1): Nij[:,:] = Nij[:,:] + np.outer(pobs[t,:], pobs[t+1,:]) logger().info("Nij\n"+str(Nij)) # Compute transition matrix maximum likelihood estimate. import msmtools.estimation as msmest import msmtools.analysis as msmana Tij = msmest.transition_matrix(Nij, reversible=reversible) pi = msmana.stationary_distribution(Tij) # Update model. model = HMM(pi, Tij, output_model) return model
[ "def", "init_model_gaussian1d", "(", "observations", ",", "nstates", ",", "reversible", "=", "True", ")", ":", "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 stationary probabilities.", "from", "bhmm", ".", "_external", ".", "sklearn", "import", "mixture", "gmm", "=", "mixture", ".", "GMM", "(", "n_components", "=", "nstates", ")", "gmm", ".", "fit", "(", "collected_observations", "[", ":", ",", "None", "]", ")", "from", "bhmm", "import", "GaussianOutputModel", "output_model", "=", "GaussianOutputModel", "(", "nstates", ",", "means", "=", "gmm", ".", "means_", "[", ":", ",", "0", "]", ",", "sigmas", "=", "np", ".", "sqrt", "(", "gmm", ".", "covars_", "[", ":", ",", "0", "]", ")", ")", "logger", "(", ")", ".", "info", "(", "\"Gaussian output model:\\n\"", "+", "str", "(", "output_model", ")", ")", "# Extract stationary distributions.", "Pi", "=", "np", ".", "zeros", "(", "[", "nstates", "]", ",", "np", ".", "float64", ")", "Pi", "[", ":", "]", "=", "gmm", ".", "weights_", "[", ":", "]", "logger", "(", ")", ".", "info", "(", "\"GMM weights: %s\"", "%", "str", "(", "gmm", ".", "weights_", ")", ")", "# Compute fractional state memberships.", "Nij", "=", "np", ".", "zeros", "(", "[", "nstates", ",", "nstates", "]", ",", "np", ".", "float64", ")", "for", "o_t", "in", "observations", ":", "# length of trajectory", "T", "=", "o_t", ".", "shape", "[", "0", "]", "# output probability", "pobs", "=", "output_model", ".", "p_obs", "(", "o_t", ")", "# normalize", "pobs", "/=", "pobs", ".", "sum", "(", "axis", "=", "1", ")", "[", ":", ",", "None", "]", "# Accumulate fractional transition counts from this trajectory.", "for", "t", "in", "range", "(", "T", "-", "1", ")", ":", "Nij", "[", ":", ",", ":", "]", "=", "Nij", "[", ":", ",", ":", "]", "+", "np", ".", "outer", "(", "pobs", "[", "t", ",", ":", "]", ",", "pobs", "[", "t", "+", "1", ",", ":", "]", ")", "logger", "(", ")", ".", "info", "(", "\"Nij\\n\"", "+", "str", "(", "Nij", ")", ")", "# Compute transition matrix maximum likelihood estimate.", "import", "msmtools", ".", "estimation", "as", "msmest", "import", "msmtools", ".", "analysis", "as", "msmana", "Tij", "=", "msmest", ".", "transition_matrix", "(", "Nij", ",", "reversible", "=", "reversible", ")", "pi", "=", "msmana", ".", "stationary_distribution", "(", "Tij", ")", "# Update model.", "model", "=", "HMM", "(", "pi", ",", "Tij", ",", "output_model", ")", "return", "model" ]
Generate an initial model with 1D-Gaussian output densities Parameters ---------- observations : list of ndarray((T_i), dtype=float) list of arrays of length T_i with observation data nstates : int The number of states. Examples -------- Generate initial model for a gaussian output model. >>> from bhmm import testsystems >>> [model, observations, states] = testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_model_gaussian1d(observations, model.nstates)
[ "Generate", "an", "initial", "model", "with", "1D", "-", "Gaussian", "output", "densities" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/gaussian.py#L26-L92
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel._p_o
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 (N) p_o[i] is the probability density of the observation o from state i emission distribution Examples -------- Create an observation model. >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, 1], sigmas=[0.5, 1, 2]) Compute the output probability of a single observation from all hidden states. >>> observation = 0 >>> p_o = output_model._p_o(observation) """ 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 continue.') C = 1.0 / (np.sqrt(2.0 * np.pi) * self.sigmas) Pobs = C * np.exp(-0.5 * ((o-self.means)/self.sigmas)**2) return Pobs else: raise RuntimeError('Implementation '+str(self.__impl__)+' not available')
python
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 (N) p_o[i] is the probability density of the observation o from state i emission distribution Examples -------- Create an observation model. >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, 1], sigmas=[0.5, 1, 2]) Compute the output probability of a single observation from all hidden states. >>> observation = 0 >>> p_o = output_model._p_o(observation) """ 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 continue.') C = 1.0 / (np.sqrt(2.0 * np.pi) * self.sigmas) Pobs = C * np.exp(-0.5 * ((o-self.means)/self.sigmas)**2) return Pobs else: raise RuntimeError('Implementation '+str(self.__impl__)+' not available')
[ "def", "_p_o", "(", "self", ",", "o", ")", ":", "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 continue.'", ")", "C", "=", "1.0", "/", "(", "np", ".", "sqrt", "(", "2.0", "*", "np", ".", "pi", ")", "*", "self", ".", "sigmas", ")", "Pobs", "=", "C", "*", "np", ".", "exp", "(", "-", "0.5", "*", "(", "(", "o", "-", "self", ".", "means", ")", "/", "self", ".", "sigmas", ")", "**", "2", ")", "return", "Pobs", "else", ":", "raise", "RuntimeError", "(", "'Implementation '", "+", "str", "(", "self", ".", "__impl__", ")", "+", "' not available'", ")" ]
Returns the output probability for symbol o from all hidden states Parameters ---------- o : float A single observation. Return ------ p_o : ndarray (N) p_o[i] is the probability density of the observation o from state i emission distribution Examples -------- Create an observation model. >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, 1], sigmas=[0.5, 1, 2]) Compute the output probability of a single observation from all hidden states. >>> observation = 0 >>> p_o = output_model._p_o(observation)
[ "Returns", "the", "output", "probability", "for", "symbol", "o", "from", "all", "hidden", "states" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L132-L168
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.p_obs
def p_obs(self, obs, out=None): """ Returns the output probabilities for an entire trajectory and all hidden states Parameters ---------- oobs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the probability of generating the symbol at time point t from any of the N hidden states Examples -------- Generate an observation model and synthetic observation trajectory. >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) >>> o_t = output_model.generate_observation_trajectory(s_t) Compute output probabilities for entire trajectory and all hidden states. >>> p_o = output_model.p_obs(o_t) """ if self.__impl__ == self.__IMPL_C__: res = gc.p_obs(obs, self.means, self.sigmas, out=out, dtype=config.dtype) return self._handle_outliers(res) elif self.__impl__ == self.__IMPL_PYTHON__: T = len(obs) if out is None: res = np.zeros((T, self.nstates), dtype=config.dtype) else: res = out for t in range(T): res[t, :] = self._p_o(obs[t]) return self._handle_outliers(res) else: raise RuntimeError('Implementation '+str(self.__impl__)+' not available')
python
def p_obs(self, obs, out=None): """ Returns the output probabilities for an entire trajectory and all hidden states Parameters ---------- oobs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the probability of generating the symbol at time point t from any of the N hidden states Examples -------- Generate an observation model and synthetic observation trajectory. >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) >>> o_t = output_model.generate_observation_trajectory(s_t) Compute output probabilities for entire trajectory and all hidden states. >>> p_o = output_model.p_obs(o_t) """ if self.__impl__ == self.__IMPL_C__: res = gc.p_obs(obs, self.means, self.sigmas, out=out, dtype=config.dtype) return self._handle_outliers(res) elif self.__impl__ == self.__IMPL_PYTHON__: T = len(obs) if out is None: res = np.zeros((T, self.nstates), dtype=config.dtype) else: res = out for t in range(T): res[t, :] = self._p_o(obs[t]) return self._handle_outliers(res) else: raise RuntimeError('Implementation '+str(self.__impl__)+' not available')
[ "def", "p_obs", "(", "self", ",", "obs", ",", "out", "=", "None", ")", ":", "if", "self", ".", "__impl__", "==", "self", ".", "__IMPL_C__", ":", "res", "=", "gc", ".", "p_obs", "(", "obs", ",", "self", ".", "means", ",", "self", ".", "sigmas", ",", "out", "=", "out", ",", "dtype", "=", "config", ".", "dtype", ")", "return", "self", ".", "_handle_outliers", "(", "res", ")", "elif", "self", ".", "__impl__", "==", "self", ".", "__IMPL_PYTHON__", ":", "T", "=", "len", "(", "obs", ")", "if", "out", "is", "None", ":", "res", "=", "np", ".", "zeros", "(", "(", "T", ",", "self", ".", "nstates", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "else", ":", "res", "=", "out", "for", "t", "in", "range", "(", "T", ")", ":", "res", "[", "t", ",", ":", "]", "=", "self", ".", "_p_o", "(", "obs", "[", "t", "]", ")", "return", "self", ".", "_handle_outliers", "(", "res", ")", "else", ":", "raise", "RuntimeError", "(", "'Implementation '", "+", "str", "(", "self", ".", "__impl__", ")", "+", "' not available'", ")" ]
Returns the output probabilities for an entire trajectory and all hidden states Parameters ---------- oobs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the probability of generating the symbol at time point t from any of the N hidden states Examples -------- Generate an observation model and synthetic observation trajectory. >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) >>> o_t = output_model.generate_observation_trajectory(s_t) Compute output probabilities for entire trajectory and all hidden states. >>> p_o = output_model.p_obs(o_t)
[ "Returns", "the", "output", "probabilities", "for", "an", "entire", "trajectory", "and", "all", "hidden", "states" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L170-L212
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.estimate
def estimate(self, observations, weights): """ Fits the output model given the observations and weights Parameters ---------- observations : [ ndarray(T_k,) ] with K elements A list of K observation trajectories, each having length T_k and d dimensions weights : [ ndarray(T_k,nstates) ] with K elements A list of K weight matrices, each having length T_k weights[k][t,n] is the weight assignment from observations[k][t] to state index n Examples -------- Generate an observation model and samples from each state. >>> ntrajectories = 3 >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> observations = [ np.random.randn(nobs) for _ in range(ntrajectories) ] # random observations >>> weights = [ np.random.dirichlet([2, 3, 4], size=nobs) for _ in range(ntrajectories) ] # random weights Update the observation model parameters my a maximum-likelihood fit. >>> output_model.estimate(observations, weights) """ # 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]) # update denominator w_sum += np.sum(weights[k], axis=0) # normalize self._means /= w_sum # fit variances self._sigmas = np.zeros(N) w_sum = np.zeros(N) for k in range(K): # update nominator for i in range(N): Y = (observations[k] - self.means[i])**2 self.sigmas[i] += np.dot(weights[k][:, i], Y) # update denominator w_sum += np.sum(weights[k], axis=0) # normalize self._sigmas /= w_sum self._sigmas = np.sqrt(self.sigmas) if np.any(self._sigmas < np.finfo(self._sigmas.dtype).eps): raise RuntimeError('at least one sigma is too small to continue.')
python
def estimate(self, observations, weights): """ Fits the output model given the observations and weights Parameters ---------- observations : [ ndarray(T_k,) ] with K elements A list of K observation trajectories, each having length T_k and d dimensions weights : [ ndarray(T_k,nstates) ] with K elements A list of K weight matrices, each having length T_k weights[k][t,n] is the weight assignment from observations[k][t] to state index n Examples -------- Generate an observation model and samples from each state. >>> ntrajectories = 3 >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> observations = [ np.random.randn(nobs) for _ in range(ntrajectories) ] # random observations >>> weights = [ np.random.dirichlet([2, 3, 4], size=nobs) for _ in range(ntrajectories) ] # random weights Update the observation model parameters my a maximum-likelihood fit. >>> output_model.estimate(observations, weights) """ # 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]) # update denominator w_sum += np.sum(weights[k], axis=0) # normalize self._means /= w_sum # fit variances self._sigmas = np.zeros(N) w_sum = np.zeros(N) for k in range(K): # update nominator for i in range(N): Y = (observations[k] - self.means[i])**2 self.sigmas[i] += np.dot(weights[k][:, i], Y) # update denominator w_sum += np.sum(weights[k], axis=0) # normalize self._sigmas /= w_sum self._sigmas = np.sqrt(self.sigmas) if np.any(self._sigmas < np.finfo(self._sigmas.dtype).eps): raise RuntimeError('at least one sigma is too small to continue.')
[ "def", "estimate", "(", "self", ",", "observations", ",", "weights", ")", ":", "# 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", "]", ")", "# update denominator", "w_sum", "+=", "np", ".", "sum", "(", "weights", "[", "k", "]", ",", "axis", "=", "0", ")", "# normalize", "self", ".", "_means", "/=", "w_sum", "# fit variances", "self", ".", "_sigmas", "=", "np", ".", "zeros", "(", "N", ")", "w_sum", "=", "np", ".", "zeros", "(", "N", ")", "for", "k", "in", "range", "(", "K", ")", ":", "# update nominator", "for", "i", "in", "range", "(", "N", ")", ":", "Y", "=", "(", "observations", "[", "k", "]", "-", "self", ".", "means", "[", "i", "]", ")", "**", "2", "self", ".", "sigmas", "[", "i", "]", "+=", "np", ".", "dot", "(", "weights", "[", "k", "]", "[", ":", ",", "i", "]", ",", "Y", ")", "# update denominator", "w_sum", "+=", "np", ".", "sum", "(", "weights", "[", "k", "]", ",", "axis", "=", "0", ")", "# normalize", "self", ".", "_sigmas", "/=", "w_sum", "self", ".", "_sigmas", "=", "np", ".", "sqrt", "(", "self", ".", "sigmas", ")", "if", "np", ".", "any", "(", "self", ".", "_sigmas", "<", "np", ".", "finfo", "(", "self", ".", "_sigmas", ".", "dtype", ")", ".", "eps", ")", ":", "raise", "RuntimeError", "(", "'at least one sigma is too small to continue.'", ")" ]
Fits the output model given the observations and weights Parameters ---------- observations : [ ndarray(T_k,) ] with K elements A list of K observation trajectories, each having length T_k and d dimensions weights : [ ndarray(T_k,nstates) ] with K elements A list of K weight matrices, each having length T_k weights[k][t,n] is the weight assignment from observations[k][t] to state index n Examples -------- Generate an observation model and samples from each state. >>> ntrajectories = 3 >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> observations = [ np.random.randn(nobs) for _ in range(ntrajectories) ] # random observations >>> weights = [ np.random.dirichlet([2, 3, 4], size=nobs) for _ in range(ntrajectories) ] # random weights Update the observation model parameters my a maximum-likelihood fit. >>> output_model.estimate(observations, weights)
[ "Fits", "the", "output", "model", "given", "the", "observations", "and", "weights" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L214-L272
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.sample
def sample(self, observations, prior=None): """ Sample a new set of distribution parameters given a sample of observations from the given state. Both the internal parameters and the attached HMM model are updated. Parameters ---------- observations : [ numpy.array with shape (N_k,) ] with `nstates` elements observations[k] is a set of observations sampled from state `k` prior : object prior option for compatibility Examples -------- Generate synthetic observations. >>> nstates = 3 >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=nstates, means=[-1, 0, 1], sigmas=[0.5, 1, 2]) >>> observations = [ output_model.generate_observations_from_state(state_index, nobs) for state_index in range(nstates) ] Update output parameters by sampling. >>> output_model.sample(observations) """ for state_index in range(self.nstates): # Update state emission distribution parameters. observations_in_state = observations[state_index] # Determine number of samples in this state. nsamples_in_state = len(observations_in_state) # Skip update if no observations. if nsamples_in_state == 0: logger().warn('Warning: State %d has no observations.' % state_index) if nsamples_in_state > 0: # Sample new mu. self.means[state_index] = np.random.randn()*self.sigmas[state_index]/np.sqrt(nsamples_in_state) + np.mean(observations_in_state) if nsamples_in_state > 1: # Sample new sigma # This scheme uses the improper Jeffreys prior on sigma^2, P(mu, sigma^2) \propto 1/sigma chisquared = np.random.chisquare(nsamples_in_state-1) sigmahat2 = np.mean((observations_in_state - self.means[state_index])**2) self.sigmas[state_index] = np.sqrt(sigmahat2) / np.sqrt(chisquared / nsamples_in_state) return
python
def sample(self, observations, prior=None): """ Sample a new set of distribution parameters given a sample of observations from the given state. Both the internal parameters and the attached HMM model are updated. Parameters ---------- observations : [ numpy.array with shape (N_k,) ] with `nstates` elements observations[k] is a set of observations sampled from state `k` prior : object prior option for compatibility Examples -------- Generate synthetic observations. >>> nstates = 3 >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=nstates, means=[-1, 0, 1], sigmas=[0.5, 1, 2]) >>> observations = [ output_model.generate_observations_from_state(state_index, nobs) for state_index in range(nstates) ] Update output parameters by sampling. >>> output_model.sample(observations) """ for state_index in range(self.nstates): # Update state emission distribution parameters. observations_in_state = observations[state_index] # Determine number of samples in this state. nsamples_in_state = len(observations_in_state) # Skip update if no observations. if nsamples_in_state == 0: logger().warn('Warning: State %d has no observations.' % state_index) if nsamples_in_state > 0: # Sample new mu. self.means[state_index] = np.random.randn()*self.sigmas[state_index]/np.sqrt(nsamples_in_state) + np.mean(observations_in_state) if nsamples_in_state > 1: # Sample new sigma # This scheme uses the improper Jeffreys prior on sigma^2, P(mu, sigma^2) \propto 1/sigma chisquared = np.random.chisquare(nsamples_in_state-1) sigmahat2 = np.mean((observations_in_state - self.means[state_index])**2) self.sigmas[state_index] = np.sqrt(sigmahat2) / np.sqrt(chisquared / nsamples_in_state) return
[ "def", "sample", "(", "self", ",", "observations", ",", "prior", "=", "None", ")", ":", "for", "state_index", "in", "range", "(", "self", ".", "nstates", ")", ":", "# Update state emission distribution parameters.", "observations_in_state", "=", "observations", "[", "state_index", "]", "# Determine number of samples in this state.", "nsamples_in_state", "=", "len", "(", "observations_in_state", ")", "# Skip update if no observations.", "if", "nsamples_in_state", "==", "0", ":", "logger", "(", ")", ".", "warn", "(", "'Warning: State %d has no observations.'", "%", "state_index", ")", "if", "nsamples_in_state", ">", "0", ":", "# Sample new mu.", "self", ".", "means", "[", "state_index", "]", "=", "np", ".", "random", ".", "randn", "(", ")", "*", "self", ".", "sigmas", "[", "state_index", "]", "/", "np", ".", "sqrt", "(", "nsamples_in_state", ")", "+", "np", ".", "mean", "(", "observations_in_state", ")", "if", "nsamples_in_state", ">", "1", ":", "# Sample new sigma", "# This scheme uses the improper Jeffreys prior on sigma^2, P(mu, sigma^2) \\propto 1/sigma", "chisquared", "=", "np", ".", "random", ".", "chisquare", "(", "nsamples_in_state", "-", "1", ")", "sigmahat2", "=", "np", ".", "mean", "(", "(", "observations_in_state", "-", "self", ".", "means", "[", "state_index", "]", ")", "**", "2", ")", "self", ".", "sigmas", "[", "state_index", "]", "=", "np", ".", "sqrt", "(", "sigmahat2", ")", "/", "np", ".", "sqrt", "(", "chisquared", "/", "nsamples_in_state", ")", "return" ]
Sample a new set of distribution parameters given a sample of observations from the given state. Both the internal parameters and the attached HMM model are updated. Parameters ---------- observations : [ numpy.array with shape (N_k,) ] with `nstates` elements observations[k] is a set of observations sampled from state `k` prior : object prior option for compatibility Examples -------- Generate synthetic observations. >>> nstates = 3 >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=nstates, means=[-1, 0, 1], sigmas=[0.5, 1, 2]) >>> observations = [ output_model.generate_observations_from_state(state_index, nobs) for state_index in range(nstates) ] Update output parameters by sampling. >>> output_model.sample(observations)
[ "Sample", "a", "new", "set", "of", "distribution", "parameters", "given", "a", "sample", "of", "observations", "from", "the", "given", "state", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L274-L320
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.generate_observation_from_state
def generate_observation_from_state(self, state_index): """ Generate a single synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. Returns ------- observation : float A single observation from the given state. Examples -------- Generate an observation model. >>> output_model = GaussianOutputModel(nstates=2, means=[0, 1], sigmas=[1, 2]) Generate sample from a state. >>> observation = output_model.generate_observation_from_state(0) """ observation = self.sigmas[state_index] * np.random.randn() + self.means[state_index] return observation
python
def generate_observation_from_state(self, state_index): """ Generate a single synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. Returns ------- observation : float A single observation from the given state. Examples -------- Generate an observation model. >>> output_model = GaussianOutputModel(nstates=2, means=[0, 1], sigmas=[1, 2]) Generate sample from a state. >>> observation = output_model.generate_observation_from_state(0) """ observation = self.sigmas[state_index] * np.random.randn() + self.means[state_index] return observation
[ "def", "generate_observation_from_state", "(", "self", ",", "state_index", ")", ":", "observation", "=", "self", ".", "sigmas", "[", "state_index", "]", "*", "np", ".", "random", ".", "randn", "(", ")", "+", "self", ".", "means", "[", "state_index", "]", "return", "observation" ]
Generate a single synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. Returns ------- observation : float A single observation from the given state. Examples -------- Generate an observation model. >>> output_model = GaussianOutputModel(nstates=2, means=[0, 1], sigmas=[1, 2]) Generate sample from a state. >>> observation = output_model.generate_observation_from_state(0)
[ "Generate", "a", "single", "synthetic", "observation", "data", "from", "a", "given", "state", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L322-L349
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.generate_observations_from_state
def generate_observations_from_state(self, state_index, nobs): """ Generate synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. nobs : int The number of observations to generate. Returns ------- observations : numpy.array of shape(nobs,) A sample of `nobs` observations from the specified state. Examples -------- Generate an observation model. >>> output_model = GaussianOutputModel(nstates=2, means=[0, 1], sigmas=[1, 2]) Generate samples from each state. >>> observations = [ output_model.generate_observations_from_state(state_index, nobs=100) for state_index in range(output_model.nstates) ] """ observations = self.sigmas[state_index] * np.random.randn(nobs) + self.means[state_index] return observations
python
def generate_observations_from_state(self, state_index, nobs): """ Generate synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. nobs : int The number of observations to generate. Returns ------- observations : numpy.array of shape(nobs,) A sample of `nobs` observations from the specified state. Examples -------- Generate an observation model. >>> output_model = GaussianOutputModel(nstates=2, means=[0, 1], sigmas=[1, 2]) Generate samples from each state. >>> observations = [ output_model.generate_observations_from_state(state_index, nobs=100) for state_index in range(output_model.nstates) ] """ observations = self.sigmas[state_index] * np.random.randn(nobs) + self.means[state_index] return observations
[ "def", "generate_observations_from_state", "(", "self", ",", "state_index", ",", "nobs", ")", ":", "observations", "=", "self", ".", "sigmas", "[", "state_index", "]", "*", "np", ".", "random", ".", "randn", "(", "nobs", ")", "+", "self", ".", "means", "[", "state_index", "]", "return", "observations" ]
Generate synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. nobs : int The number of observations to generate. Returns ------- observations : numpy.array of shape(nobs,) A sample of `nobs` observations from the specified state. Examples -------- Generate an observation model. >>> output_model = GaussianOutputModel(nstates=2, means=[0, 1], sigmas=[1, 2]) Generate samples from each state. >>> observations = [ output_model.generate_observations_from_state(state_index, nobs=100) for state_index in range(output_model.nstates) ]
[ "Generate", "synthetic", "observation", "data", "from", "a", "given", "state", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L351-L380
bhmm/bhmm
bhmm/output_models/gaussian.py
GaussianOutputModel.generate_observation_trajectory
def generate_observation_trajectory(self, s_t): """ Generate synthetic observation data from a given state sequence. Parameters ---------- s_t : numpy.array with shape (T,) of int type s_t[t] is the hidden state sampled at time t Returns ------- o_t : numpy.array with shape (T,) of type dtype o_t[t] is the observation associated with state s_t[t] Examples -------- Generate an observation model and synthetic state trajectory. >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) Generate a synthetic trajectory >>> o_t = output_model.generate_observation_trajectory(s_t) """ # Determine number of samples to generate. T = s_t.shape[0] o_t = np.zeros([T], dtype=config.dtype) for t in range(T): s = s_t[t] o_t[t] = self.sigmas[s] * np.random.randn() + self.means[s] return o_t
python
def generate_observation_trajectory(self, s_t): """ Generate synthetic observation data from a given state sequence. Parameters ---------- s_t : numpy.array with shape (T,) of int type s_t[t] is the hidden state sampled at time t Returns ------- o_t : numpy.array with shape (T,) of type dtype o_t[t] is the observation associated with state s_t[t] Examples -------- Generate an observation model and synthetic state trajectory. >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) Generate a synthetic trajectory >>> o_t = output_model.generate_observation_trajectory(s_t) """ # Determine number of samples to generate. T = s_t.shape[0] o_t = np.zeros([T], dtype=config.dtype) for t in range(T): s = s_t[t] o_t[t] = self.sigmas[s] * np.random.randn() + self.means[s] return o_t
[ "def", "generate_observation_trajectory", "(", "self", ",", "s_t", ")", ":", "# Determine number of samples to generate.", "T", "=", "s_t", ".", "shape", "[", "0", "]", "o_t", "=", "np", ".", "zeros", "(", "[", "T", "]", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "t", "in", "range", "(", "T", ")", ":", "s", "=", "s_t", "[", "t", "]", "o_t", "[", "t", "]", "=", "self", ".", "sigmas", "[", "s", "]", "*", "np", ".", "random", ".", "randn", "(", ")", "+", "self", ".", "means", "[", "s", "]", "return", "o_t" ]
Generate synthetic observation data from a given state sequence. Parameters ---------- s_t : numpy.array with shape (T,) of int type s_t[t] is the hidden state sampled at time t Returns ------- o_t : numpy.array with shape (T,) of type dtype o_t[t] is the observation associated with state s_t[t] Examples -------- Generate an observation model and synthetic state trajectory. >>> nobs = 1000 >>> output_model = GaussianOutputModel(nstates=3, means=[-1, 0, +1], sigmas=[0.5, 1, 2]) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) Generate a synthetic trajectory >>> o_t = output_model.generate_observation_trajectory(s_t)
[ "Generate", "synthetic", "observation", "data", "from", "a", "given", "state", "sequence", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/gaussian.py#L382-L418
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.initial_distribution_samples
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
python
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
[ "def", "initial_distribution_samples", "(", "self", ")", ":", "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" ]
r""" Samples of the initial distribution
[ "r", "Samples", "of", "the", "initial", "distribution" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L70-L75
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.transition_matrix_samples
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
python
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
[ "def", "transition_matrix_samples", "(", "self", ")", ":", "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" ]
r""" Samples of the transition matrix
[ "r", "Samples", "of", "the", "transition", "matrix" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L116-L121
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.eigenvalues_samples
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
python
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
[ "def", "eigenvalues_samples", "(", "self", ")", ":", "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" ]
r""" Samples of the eigenvalues
[ "r", "Samples", "of", "the", "eigenvalues" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L139-L144
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.eigenvectors_left_samples
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
python
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
[ "def", "eigenvectors_left_samples", "(", "self", ")", ":", "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" ]
r""" Samples of the left eigenvectors of the hidden transition matrix
[ "r", "Samples", "of", "the", "left", "eigenvectors", "of", "the", "hidden", "transition", "matrix" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L162-L167
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.eigenvectors_right_samples
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
python
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
[ "def", "eigenvectors_right_samples", "(", "self", ")", ":", "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" ]
r""" Samples of the right eigenvectors of the hidden transition matrix
[ "r", "Samples", "of", "the", "right", "eigenvectors", "of", "the", "hidden", "transition", "matrix" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L185-L190
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.timescales_samples
def timescales_samples(self): r""" Samples of the timescales """ res = np.empty((self.nsamples, self.nstates-1), dtype=config.dtype) for i in range(self.nsamples): res[i, :] = self._sampled_hmms[i].timescales return res
python
def timescales_samples(self): r""" Samples of the timescales """ res = np.empty((self.nsamples, self.nstates-1), dtype=config.dtype) for i in range(self.nsamples): res[i, :] = self._sampled_hmms[i].timescales return res
[ "def", "timescales_samples", "(", "self", ")", ":", "res", "=", "np", ".", "empty", "(", "(", "self", ".", "nsamples", ",", "self", ".", "nstates", "-", "1", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "i", "in", "range", "(", "self", ".", "nsamples", ")", ":", "res", "[", "i", ",", ":", "]", "=", "self", ".", "_sampled_hmms", "[", "i", "]", ".", "timescales", "return", "res" ]
r""" Samples of the timescales
[ "r", "Samples", "of", "the", "timescales" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L208-L213
bhmm/bhmm
bhmm/hmm/generic_sampled_hmm.py
SampledHMM.lifetimes_samples
def lifetimes_samples(self): r""" Samples of the timescales """ res = np.empty((self.nsamples, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :] = self._sampled_hmms[i].lifetimes return res
python
def lifetimes_samples(self): r""" Samples of the timescales """ res = np.empty((self.nsamples, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :] = self._sampled_hmms[i].lifetimes return res
[ "def", "lifetimes_samples", "(", "self", ")", ":", "res", "=", "np", ".", "empty", "(", "(", "self", ".", "nsamples", ",", "self", ".", "nstates", ")", ",", "dtype", "=", "config", ".", "dtype", ")", "for", "i", "in", "range", "(", "self", ".", "nsamples", ")", ":", "res", "[", "i", ",", ":", "]", "=", "self", ".", "_sampled_hmms", "[", "i", "]", ".", "lifetimes", "return", "res" ]
r""" Samples of the timescales
[ "r", "Samples", "of", "the", "timescales" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L231-L236
bhmm/bhmm
bhmm/output_models/outputmodel.py
OutputModel.set_implementation
def set_implementation(self, impl): """ Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"] """ if impl.lower() == 'python': self.__impl__ = self.__IMPL_PYTHON__ elif impl.lower() == 'c': self.__impl__ = self.__IMPL_C__ else: import warnings warnings.warn('Implementation '+impl+' is not known. Using the fallback python implementation.') self.__impl__ = self.__IMPL_PYTHON__
python
def set_implementation(self, impl): """ Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"] """ if impl.lower() == 'python': self.__impl__ = self.__IMPL_PYTHON__ elif impl.lower() == 'c': self.__impl__ = self.__IMPL_C__ else: import warnings warnings.warn('Implementation '+impl+' is not known. Using the fallback python implementation.') self.__impl__ = self.__IMPL_PYTHON__
[ "def", "set_implementation", "(", "self", ",", "impl", ")", ":", "if", "impl", ".", "lower", "(", ")", "==", "'python'", ":", "self", ".", "__impl__", "=", "self", ".", "__IMPL_PYTHON__", "elif", "impl", ".", "lower", "(", ")", "==", "'c'", ":", "self", ".", "__impl__", "=", "self", ".", "__IMPL_C__", "else", ":", "import", "warnings", "warnings", ".", "warn", "(", "'Implementation '", "+", "impl", "+", "' is not known. Using the fallback python implementation.'", ")", "self", ".", "__impl__", "=", "self", ".", "__IMPL_PYTHON__" ]
Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"]
[ "Sets", "the", "implementation", "of", "this", "module" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/outputmodel.py#L69-L86
bhmm/bhmm
bhmm/output_models/outputmodel.py
OutputModel.log_p_obs
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 states This is a default implementation that will take the log of p_obs(obs) and should only be used if p_obs(obs) is numerically stable. If there is any danger of running into numerical problems *during* the calculation of p_obs, this function should be overwritten in order to compute the log-probabilities directly. Parameters ---------- obs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the log probability of generating the symbol at time point t from any of the N hidden states """ 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
python
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 states This is a default implementation that will take the log of p_obs(obs) and should only be used if p_obs(obs) is numerically stable. If there is any danger of running into numerical problems *during* the calculation of p_obs, this function should be overwritten in order to compute the log-probabilities directly. Parameters ---------- obs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the log probability of generating the symbol at time point t from any of the N hidden states """ 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
[ "def", "log_p_obs", "(", "self", ",", "obs", ",", "out", "=", "None", ",", "dtype", "=", "np", ".", "float32", ")", ":", "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" ]
Returns the element-wise logarithm of the output probabilities for an entire trajectory and all hidden states This is a default implementation that will take the log of p_obs(obs) and should only be used if p_obs(obs) is numerically stable. If there is any danger of running into numerical problems *during* the calculation of p_obs, this function should be overwritten in order to compute the log-probabilities directly. Parameters ---------- obs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the log probability of generating the symbol at time point t from any of the N hidden states
[ "Returns", "the", "element", "-", "wise", "logarithm", "of", "the", "output", "probabilities", "for", "an", "entire", "trajectory", "and", "all", "hidden", "states" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/outputmodel.py#L93-L117
bhmm/bhmm
bhmm/output_models/outputmodel.py
OutputModel._handle_outliers
def _handle_outliers(self, p_o): """ Sets observation probabilities of outliers to uniform if ignore_outliers is set. Parameters ---------- p_o : ndarray((T, N)) output probabilities """ if self.ignore_outliers: outliers = np.where(p_o.sum(axis=1)==0)[0] if outliers.size > 0: p_o[outliers, :] = 1.0 self.found_outliers = True return p_o
python
def _handle_outliers(self, p_o): """ Sets observation probabilities of outliers to uniform if ignore_outliers is set. Parameters ---------- p_o : ndarray((T, N)) output probabilities """ if self.ignore_outliers: outliers = np.where(p_o.sum(axis=1)==0)[0] if outliers.size > 0: p_o[outliers, :] = 1.0 self.found_outliers = True return p_o
[ "def", "_handle_outliers", "(", "self", ",", "p_o", ")", ":", "if", "self", ".", "ignore_outliers", ":", "outliers", "=", "np", ".", "where", "(", "p_o", ".", "sum", "(", "axis", "=", "1", ")", "==", "0", ")", "[", "0", "]", "if", "outliers", ".", "size", ">", "0", ":", "p_o", "[", "outliers", ",", ":", "]", "=", "1.0", "self", ".", "found_outliers", "=", "True", "return", "p_o" ]
Sets observation probabilities of outliers to uniform if ignore_outliers is set. Parameters ---------- p_o : ndarray((T, N)) output probabilities
[ "Sets", "observation", "probabilities", "of", "outliers", "to", "uniform", "if", "ignore_outliers", "is", "set", ".", "Parameters", "----------", "p_o", ":", "ndarray", "((", "T", "N", "))", "output", "probabilities" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/outputmodel.py#L119-L131
bhmm/bhmm
bhmm/hidden/impl_python/hidden.py
forward
def forward(A, pobs, pi, T=None, alpha_out=None, dtype=np.float32): """Compute P( obs | A, B, pi ) and all forward coefficients. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states T : int, optional, default = None trajectory length. If not given, T = pobs.shape[0] will be used. alpha_out : ndarray((T,N), dtype = float), optional, default = None container for the alpha result variables. If None, a new container will be created. dtype : type, optional, default = np.float32 data type of the result. Returns ------- logprob : float The probability to observe the sequence `ob` with the model given by `A`, `B` and `pi`. alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. These can be used in many different algorithms related to HMMs. """ # set T if T is None: T = pobs.shape[0] # if not set, use the length of pobs as trajectory length elif T > pobs.shape[0]: raise ValueError('T must be at most the length of pobs.') # set N N = A.shape[0] # initialize output if necessary if alpha_out is None: alpha_out = np.zeros((T, N), dtype=dtype) elif T > alpha_out.shape[0]: raise ValueError('alpha_out must at least have length T in order to fit trajectory.') # log-likelihood logprob = 0.0 # initial values # alpha_i(0) = pi_i * B_i,ob[0] np.multiply(pi, pobs[0, :], out=alpha_out[0]) # scaling factor scale = np.sum(alpha_out[0, :]) # scale alpha_out[0, :] /= scale logprob += np.log(scale) # induction for t in range(T-1): # alpha_j(t+1) = sum_i alpha_i(t) * A_i,j * B_j,ob(t+1) np.multiply(np.dot(alpha_out[t, :], A), pobs[t+1, :], out=alpha_out[t+1]) # scaling factor scale = np.sum(alpha_out[t+1, :]) # scale alpha_out[t+1, :] /= scale # update logprob logprob += np.log(scale) return logprob, alpha_out
python
def forward(A, pobs, pi, T=None, alpha_out=None, dtype=np.float32): """Compute P( obs | A, B, pi ) and all forward coefficients. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states T : int, optional, default = None trajectory length. If not given, T = pobs.shape[0] will be used. alpha_out : ndarray((T,N), dtype = float), optional, default = None container for the alpha result variables. If None, a new container will be created. dtype : type, optional, default = np.float32 data type of the result. Returns ------- logprob : float The probability to observe the sequence `ob` with the model given by `A`, `B` and `pi`. alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. These can be used in many different algorithms related to HMMs. """ # set T if T is None: T = pobs.shape[0] # if not set, use the length of pobs as trajectory length elif T > pobs.shape[0]: raise ValueError('T must be at most the length of pobs.') # set N N = A.shape[0] # initialize output if necessary if alpha_out is None: alpha_out = np.zeros((T, N), dtype=dtype) elif T > alpha_out.shape[0]: raise ValueError('alpha_out must at least have length T in order to fit trajectory.') # log-likelihood logprob = 0.0 # initial values # alpha_i(0) = pi_i * B_i,ob[0] np.multiply(pi, pobs[0, :], out=alpha_out[0]) # scaling factor scale = np.sum(alpha_out[0, :]) # scale alpha_out[0, :] /= scale logprob += np.log(scale) # induction for t in range(T-1): # alpha_j(t+1) = sum_i alpha_i(t) * A_i,j * B_j,ob(t+1) np.multiply(np.dot(alpha_out[t, :], A), pobs[t+1, :], out=alpha_out[t+1]) # scaling factor scale = np.sum(alpha_out[t+1, :]) # scale alpha_out[t+1, :] /= scale # update logprob logprob += np.log(scale) return logprob, alpha_out
[ "def", "forward", "(", "A", ",", "pobs", ",", "pi", ",", "T", "=", "None", ",", "alpha_out", "=", "None", ",", "dtype", "=", "np", ".", "float32", ")", ":", "# set T", "if", "T", "is", "None", ":", "T", "=", "pobs", ".", "shape", "[", "0", "]", "# if not set, use the length of pobs as trajectory length", "elif", "T", ">", "pobs", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "'T must be at most the length of pobs.'", ")", "# set N", "N", "=", "A", ".", "shape", "[", "0", "]", "# initialize output if necessary", "if", "alpha_out", "is", "None", ":", "alpha_out", "=", "np", ".", "zeros", "(", "(", "T", ",", "N", ")", ",", "dtype", "=", "dtype", ")", "elif", "T", ">", "alpha_out", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "'alpha_out must at least have length T in order to fit trajectory.'", ")", "# log-likelihood", "logprob", "=", "0.0", "# initial values", "# alpha_i(0) = pi_i * B_i,ob[0]", "np", ".", "multiply", "(", "pi", ",", "pobs", "[", "0", ",", ":", "]", ",", "out", "=", "alpha_out", "[", "0", "]", ")", "# scaling factor", "scale", "=", "np", ".", "sum", "(", "alpha_out", "[", "0", ",", ":", "]", ")", "# scale", "alpha_out", "[", "0", ",", ":", "]", "/=", "scale", "logprob", "+=", "np", ".", "log", "(", "scale", ")", "# induction", "for", "t", "in", "range", "(", "T", "-", "1", ")", ":", "# alpha_j(t+1) = sum_i alpha_i(t) * A_i,j * B_j,ob(t+1)", "np", ".", "multiply", "(", "np", ".", "dot", "(", "alpha_out", "[", "t", ",", ":", "]", ",", "A", ")", ",", "pobs", "[", "t", "+", "1", ",", ":", "]", ",", "out", "=", "alpha_out", "[", "t", "+", "1", "]", ")", "# scaling factor", "scale", "=", "np", ".", "sum", "(", "alpha_out", "[", "t", "+", "1", ",", ":", "]", ")", "# scale", "alpha_out", "[", "t", "+", "1", ",", ":", "]", "/=", "scale", "# update logprob", "logprob", "+=", "np", ".", "log", "(", "scale", ")", "return", "logprob", ",", "alpha_out" ]
Compute P( obs | A, B, pi ) and all forward coefficients. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states T : int, optional, default = None trajectory length. If not given, T = pobs.shape[0] will be used. alpha_out : ndarray((T,N), dtype = float), optional, default = None container for the alpha result variables. If None, a new container will be created. dtype : type, optional, default = np.float32 data type of the result. Returns ------- logprob : float The probability to observe the sequence `ob` with the model given by `A`, `B` and `pi`. alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. These can be used in many different algorithms related to HMMs.
[ "Compute", "P", "(", "obs", "|", "A", "B", "pi", ")", "and", "all", "forward", "coefficients", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/impl_python/hidden.py#L33-L96
bhmm/bhmm
bhmm/hidden/impl_python/hidden.py
backward
def backward(A, pobs, T=None, beta_out=None, dtype=np.float32): """Compute all backward coefficients. With scaling! Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i beta_out : ndarray((T,N), dtype = float), optional, default = None containter for the beta result variables. If None, a new container will be created. dtype : type, optional, default = np.float32 data type of the result. Returns ------- beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith backward coefficient of time t. These can be used in many different algorithms related to HMMs. """ # set T if T is None: T = pobs.shape[0] # if not set, use the length of pobs as trajectory length elif T > pobs.shape[0]: raise ValueError('T must be at most the length of pobs.') # set N N = A.shape[0] # initialize output if necessary if beta_out is None: beta_out = np.zeros((T, N), dtype=dtype) elif T > beta_out.shape[0]: raise ValueError('beta_out must at least have length T in order to fit trajectory.') # initialization beta_out[T-1, :] = 1.0 # scaling factor scale = np.sum(beta_out[T-1, :]) # scale beta_out[T-1, :] /= scale # induction for t in range(T-2, -1, -1): # beta_i(t) = sum_j A_i,j * beta_j(t+1) * B_j,ob(t+1) np.dot(A, beta_out[t+1, :] * pobs[t+1, :], out=beta_out[t, :]) # scaling factor scale = np.sum(beta_out[t, :]) # scale beta_out[t, :] /= scale return beta_out
python
def backward(A, pobs, T=None, beta_out=None, dtype=np.float32): """Compute all backward coefficients. With scaling! Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i beta_out : ndarray((T,N), dtype = float), optional, default = None containter for the beta result variables. If None, a new container will be created. dtype : type, optional, default = np.float32 data type of the result. Returns ------- beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith backward coefficient of time t. These can be used in many different algorithms related to HMMs. """ # set T if T is None: T = pobs.shape[0] # if not set, use the length of pobs as trajectory length elif T > pobs.shape[0]: raise ValueError('T must be at most the length of pobs.') # set N N = A.shape[0] # initialize output if necessary if beta_out is None: beta_out = np.zeros((T, N), dtype=dtype) elif T > beta_out.shape[0]: raise ValueError('beta_out must at least have length T in order to fit trajectory.') # initialization beta_out[T-1, :] = 1.0 # scaling factor scale = np.sum(beta_out[T-1, :]) # scale beta_out[T-1, :] /= scale # induction for t in range(T-2, -1, -1): # beta_i(t) = sum_j A_i,j * beta_j(t+1) * B_j,ob(t+1) np.dot(A, beta_out[t+1, :] * pobs[t+1, :], out=beta_out[t, :]) # scaling factor scale = np.sum(beta_out[t, :]) # scale beta_out[t, :] /= scale return beta_out
[ "def", "backward", "(", "A", ",", "pobs", ",", "T", "=", "None", ",", "beta_out", "=", "None", ",", "dtype", "=", "np", ".", "float32", ")", ":", "# set T", "if", "T", "is", "None", ":", "T", "=", "pobs", ".", "shape", "[", "0", "]", "# if not set, use the length of pobs as trajectory length", "elif", "T", ">", "pobs", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "'T must be at most the length of pobs.'", ")", "# set N", "N", "=", "A", ".", "shape", "[", "0", "]", "# initialize output if necessary", "if", "beta_out", "is", "None", ":", "beta_out", "=", "np", ".", "zeros", "(", "(", "T", ",", "N", ")", ",", "dtype", "=", "dtype", ")", "elif", "T", ">", "beta_out", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "'beta_out must at least have length T in order to fit trajectory.'", ")", "# initialization", "beta_out", "[", "T", "-", "1", ",", ":", "]", "=", "1.0", "# scaling factor", "scale", "=", "np", ".", "sum", "(", "beta_out", "[", "T", "-", "1", ",", ":", "]", ")", "# scale", "beta_out", "[", "T", "-", "1", ",", ":", "]", "/=", "scale", "# induction", "for", "t", "in", "range", "(", "T", "-", "2", ",", "-", "1", ",", "-", "1", ")", ":", "# beta_i(t) = sum_j A_i,j * beta_j(t+1) * B_j,ob(t+1)", "np", ".", "dot", "(", "A", ",", "beta_out", "[", "t", "+", "1", ",", ":", "]", "*", "pobs", "[", "t", "+", "1", ",", ":", "]", ",", "out", "=", "beta_out", "[", "t", ",", ":", "]", ")", "# scaling factor", "scale", "=", "np", ".", "sum", "(", "beta_out", "[", "t", ",", ":", "]", ")", "# scale", "beta_out", "[", "t", ",", ":", "]", "/=", "scale", "return", "beta_out" ]
Compute all backward coefficients. With scaling! Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i beta_out : ndarray((T,N), dtype = float), optional, default = None containter for the beta result variables. If None, a new container will be created. dtype : type, optional, default = np.float32 data type of the result. Returns ------- beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith backward coefficient of time t. These can be used in many different algorithms related to HMMs.
[ "Compute", "all", "backward", "coefficients", ".", "With", "scaling!" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/impl_python/hidden.py#L99-L148
bhmm/bhmm
bhmm/hidden/impl_python/hidden.py
transition_counts
def transition_counts(alpha, beta, A, pobs, T=None, out=None, dtype=np.float32): """ Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int number of time steps out : ndarray((N,N), dtype = float), optional, default = None containter for the resulting count matrix. If None, a new matrix will be created. dtype : type, optional, default = np.float32 data type of the result. Returns ------- counts : numpy.array shape (N, N) counts[i, j] is the summed probability to transition from i to j in time [0,T) See Also -------- forward : calculate forward coefficients `alpha` backward : calculate backward coefficients `beta` """ # set T if T is None: T = pobs.shape[0] # if not set, use the length of pobs as trajectory length elif T > pobs.shape[0]: raise ValueError('T must be at most the length of pobs.') # set N N = len(A) # output if out is None: out = np.zeros((N, N), dtype=dtype, order='C') else: out[:] = 0.0 # compute transition counts xi = np.zeros((N, N), dtype=dtype, order='C') for t in range(T-1): # xi_i,j(t) = alpha_i(t) * A_i,j * B_j,ob(t+1) * beta_j(t+1) np.dot(alpha[t, :][:, None] * A, np.diag(pobs[t+1, :] * beta[t+1, :]), out=xi) # normalize to 1 for each time step xi /= np.sum(xi) # add to counts np.add(out, xi, out) # return return out
python
def transition_counts(alpha, beta, A, pobs, T=None, out=None, dtype=np.float32): """ Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int number of time steps out : ndarray((N,N), dtype = float), optional, default = None containter for the resulting count matrix. If None, a new matrix will be created. dtype : type, optional, default = np.float32 data type of the result. Returns ------- counts : numpy.array shape (N, N) counts[i, j] is the summed probability to transition from i to j in time [0,T) See Also -------- forward : calculate forward coefficients `alpha` backward : calculate backward coefficients `beta` """ # set T if T is None: T = pobs.shape[0] # if not set, use the length of pobs as trajectory length elif T > pobs.shape[0]: raise ValueError('T must be at most the length of pobs.') # set N N = len(A) # output if out is None: out = np.zeros((N, N), dtype=dtype, order='C') else: out[:] = 0.0 # compute transition counts xi = np.zeros((N, N), dtype=dtype, order='C') for t in range(T-1): # xi_i,j(t) = alpha_i(t) * A_i,j * B_j,ob(t+1) * beta_j(t+1) np.dot(alpha[t, :][:, None] * A, np.diag(pobs[t+1, :] * beta[t+1, :]), out=xi) # normalize to 1 for each time step xi /= np.sum(xi) # add to counts np.add(out, xi, out) # return return out
[ "def", "transition_counts", "(", "alpha", ",", "beta", ",", "A", ",", "pobs", ",", "T", "=", "None", ",", "out", "=", "None", ",", "dtype", "=", "np", ".", "float32", ")", ":", "# set T", "if", "T", "is", "None", ":", "T", "=", "pobs", ".", "shape", "[", "0", "]", "# if not set, use the length of pobs as trajectory length", "elif", "T", ">", "pobs", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "'T must be at most the length of pobs.'", ")", "# set N", "N", "=", "len", "(", "A", ")", "# output", "if", "out", "is", "None", ":", "out", "=", "np", ".", "zeros", "(", "(", "N", ",", "N", ")", ",", "dtype", "=", "dtype", ",", "order", "=", "'C'", ")", "else", ":", "out", "[", ":", "]", "=", "0.0", "# compute transition counts", "xi", "=", "np", ".", "zeros", "(", "(", "N", ",", "N", ")", ",", "dtype", "=", "dtype", ",", "order", "=", "'C'", ")", "for", "t", "in", "range", "(", "T", "-", "1", ")", ":", "# xi_i,j(t) = alpha_i(t) * A_i,j * B_j,ob(t+1) * beta_j(t+1)", "np", ".", "dot", "(", "alpha", "[", "t", ",", ":", "]", "[", ":", ",", "None", "]", "*", "A", ",", "np", ".", "diag", "(", "pobs", "[", "t", "+", "1", ",", ":", "]", "*", "beta", "[", "t", "+", "1", ",", ":", "]", ")", ",", "out", "=", "xi", ")", "# normalize to 1 for each time step", "xi", "/=", "np", ".", "sum", "(", "xi", ")", "# add to counts", "np", ".", "add", "(", "out", ",", "xi", ",", "out", ")", "# return", "return", "out" ]
Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int number of time steps out : ndarray((N,N), dtype = float), optional, default = None containter for the resulting count matrix. If None, a new matrix will be created. dtype : type, optional, default = np.float32 data type of the result. Returns ------- counts : numpy.array shape (N, N) counts[i, j] is the summed probability to transition from i to j in time [0,T) See Also -------- forward : calculate forward coefficients `alpha` backward : calculate backward coefficients `beta`
[ "Sum", "for", "all", "t", "the", "probability", "to", "transition", "from", "state", "i", "to", "state", "j", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/impl_python/hidden.py#L151-L204
bhmm/bhmm
bhmm/hidden/impl_python/hidden.py
viterbi
def viterbi(A, pobs, pi, dtype=np.float32): """ Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states Returns ------- q : numpy.array shape (T) maximum likelihood hidden path """ T, N = pobs.shape[0], pobs.shape[1] # temporary viterbi state psi = np.zeros((T, N), dtype=int) # initialize v = pi * pobs[0, :] # rescale v /= v.sum() psi[0] = 0.0 # iterate for t in range(1, T): vA = np.dot(np.diag(v), A) # propagate v v = pobs[t, :] * np.max(vA, axis=0) # rescale v /= v.sum() psi[t] = np.argmax(vA, axis=0) # iterate q = np.zeros(T, dtype=int) q[T-1] = np.argmax(v) for t in range(T-2, -1, -1): q[t] = psi[t+1, q[t+1]] # done return q
python
def viterbi(A, pobs, pi, dtype=np.float32): """ Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states Returns ------- q : numpy.array shape (T) maximum likelihood hidden path """ T, N = pobs.shape[0], pobs.shape[1] # temporary viterbi state psi = np.zeros((T, N), dtype=int) # initialize v = pi * pobs[0, :] # rescale v /= v.sum() psi[0] = 0.0 # iterate for t in range(1, T): vA = np.dot(np.diag(v), A) # propagate v v = pobs[t, :] * np.max(vA, axis=0) # rescale v /= v.sum() psi[t] = np.argmax(vA, axis=0) # iterate q = np.zeros(T, dtype=int) q[T-1] = np.argmax(v) for t in range(T-2, -1, -1): q[t] = psi[t+1, q[t+1]] # done return q
[ "def", "viterbi", "(", "A", ",", "pobs", ",", "pi", ",", "dtype", "=", "np", ".", "float32", ")", ":", "T", ",", "N", "=", "pobs", ".", "shape", "[", "0", "]", ",", "pobs", ".", "shape", "[", "1", "]", "# temporary viterbi state", "psi", "=", "np", ".", "zeros", "(", "(", "T", ",", "N", ")", ",", "dtype", "=", "int", ")", "# initialize", "v", "=", "pi", "*", "pobs", "[", "0", ",", ":", "]", "# rescale", "v", "/=", "v", ".", "sum", "(", ")", "psi", "[", "0", "]", "=", "0.0", "# iterate", "for", "t", "in", "range", "(", "1", ",", "T", ")", ":", "vA", "=", "np", ".", "dot", "(", "np", ".", "diag", "(", "v", ")", ",", "A", ")", "# propagate v", "v", "=", "pobs", "[", "t", ",", ":", "]", "*", "np", ".", "max", "(", "vA", ",", "axis", "=", "0", ")", "# rescale", "v", "/=", "v", ".", "sum", "(", ")", "psi", "[", "t", "]", "=", "np", ".", "argmax", "(", "vA", ",", "axis", "=", "0", ")", "# iterate", "q", "=", "np", ".", "zeros", "(", "T", ",", "dtype", "=", "int", ")", "q", "[", "T", "-", "1", "]", "=", "np", ".", "argmax", "(", "v", ")", "for", "t", "in", "range", "(", "T", "-", "2", ",", "-", "1", ",", "-", "1", ")", ":", "q", "[", "t", "]", "=", "psi", "[", "t", "+", "1", ",", "q", "[", "t", "+", "1", "]", "]", "# done", "return", "q" ]
Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states Returns ------- q : numpy.array shape (T) maximum likelihood hidden path
[ "Estimate", "the", "hidden", "pathway", "of", "maximum", "likelihood", "using", "the", "Viterbi", "algorithm", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/impl_python/hidden.py#L207-L247
bhmm/bhmm
bhmm/hidden/impl_python/hidden.py
sample_path
def sample_path(alpha, A, pobs, T=None, dtype=np.float32): """ alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i """ N = pobs.shape[1] # set T if T is None: T = pobs.shape[0] # if not set, use the length of pobs as trajectory length elif T > pobs.shape[0] or T > alpha.shape[0]: raise ValueError('T must be at most the length of pobs and alpha.') # initialize path S = np.zeros(T, dtype=int) # Sample final state. psel = alpha[T-1, :] psel /= psel.sum() # make sure it's normalized # Draw from this distribution. S[T-1] = np.random.choice(range(N), size=1, p=psel) # Work backwards from T-2 to 0. for t in range(T-2, -1, -1): # Compute P(s_t = i | s_{t+1}..s_T). psel = alpha[t, :] * A[:, S[t+1]] psel /= psel.sum() # make sure it's normalized # Draw from this distribution. S[t] = np.random.choice(range(N), size=1, p=psel) return S
python
def sample_path(alpha, A, pobs, T=None, dtype=np.float32): """ alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i """ N = pobs.shape[1] # set T if T is None: T = pobs.shape[0] # if not set, use the length of pobs as trajectory length elif T > pobs.shape[0] or T > alpha.shape[0]: raise ValueError('T must be at most the length of pobs and alpha.') # initialize path S = np.zeros(T, dtype=int) # Sample final state. psel = alpha[T-1, :] psel /= psel.sum() # make sure it's normalized # Draw from this distribution. S[T-1] = np.random.choice(range(N), size=1, p=psel) # Work backwards from T-2 to 0. for t in range(T-2, -1, -1): # Compute P(s_t = i | s_{t+1}..s_T). psel = alpha[t, :] * A[:, S[t+1]] psel /= psel.sum() # make sure it's normalized # Draw from this distribution. S[t] = np.random.choice(range(N), size=1, p=psel) return S
[ "def", "sample_path", "(", "alpha", ",", "A", ",", "pobs", ",", "T", "=", "None", ",", "dtype", "=", "np", ".", "float32", ")", ":", "N", "=", "pobs", ".", "shape", "[", "1", "]", "# set T", "if", "T", "is", "None", ":", "T", "=", "pobs", ".", "shape", "[", "0", "]", "# if not set, use the length of pobs as trajectory length", "elif", "T", ">", "pobs", ".", "shape", "[", "0", "]", "or", "T", ">", "alpha", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "'T must be at most the length of pobs and alpha.'", ")", "# initialize path", "S", "=", "np", ".", "zeros", "(", "T", ",", "dtype", "=", "int", ")", "# Sample final state.", "psel", "=", "alpha", "[", "T", "-", "1", ",", ":", "]", "psel", "/=", "psel", ".", "sum", "(", ")", "# make sure it's normalized", "# Draw from this distribution.", "S", "[", "T", "-", "1", "]", "=", "np", ".", "random", ".", "choice", "(", "range", "(", "N", ")", ",", "size", "=", "1", ",", "p", "=", "psel", ")", "# Work backwards from T-2 to 0.", "for", "t", "in", "range", "(", "T", "-", "2", ",", "-", "1", ",", "-", "1", ")", ":", "# Compute P(s_t = i | s_{t+1}..s_T).", "psel", "=", "alpha", "[", "t", ",", ":", "]", "*", "A", "[", ":", ",", "S", "[", "t", "+", "1", "]", "]", "psel", "/=", "psel", ".", "sum", "(", ")", "# make sure it's normalized", "# Draw from this distribution.", "S", "[", "t", "]", "=", "np", ".", "random", ".", "choice", "(", "range", "(", "N", ")", ",", "size", "=", "1", ",", "p", "=", "psel", ")", "return", "S" ]
alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i
[ "alpha", ":", "ndarray", "((", "T", "N", ")", "dtype", "=", "float", ")", "optional", "default", "=", "None", "alpha", "[", "t", "i", "]", "is", "the", "ith", "forward", "coefficient", "of", "time", "t", ".", "beta", ":", "ndarray", "((", "T", "N", ")", "dtype", "=", "float", ")", "optional", "default", "=", "None", "beta", "[", "t", "i", "]", "is", "the", "ith", "forward", "coefficient", "of", "time", "t", ".", "A", ":", "ndarray", "((", "N", "N", ")", "dtype", "=", "float", ")", "transition", "matrix", "of", "the", "hidden", "states", "pobs", ":", "ndarray", "((", "T", "N", ")", "dtype", "=", "float", ")", "pobs", "[", "t", "i", "]", "is", "the", "observation", "probability", "for", "observation", "at", "time", "t", "given", "hidden", "state", "i" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/impl_python/hidden.py#L250-L285
bhmm/bhmm
bhmm/init/discrete.py
coarse_grain_transition_matrix
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(n, n) microstate transition matrix M : ndarray(n, m) membership matrix. Membership to macrostate m for each microstate. Returns ------- Pc : ndarray(m, m) coarse-grained transition matrix. """ # 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_coarse.sum(axis=1)[:, None] return P_coarse
python
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(n, n) microstate transition matrix M : ndarray(n, m) membership matrix. Membership to macrostate m for each microstate. Returns ------- Pc : ndarray(m, m) coarse-grained transition matrix. """ # 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_coarse.sum(axis=1)[:, None] return P_coarse
[ "def", "coarse_grain_transition_matrix", "(", "P", ",", "M", ")", ":", "# 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_coarse", ".", "sum", "(", "axis", "=", "1", ")", "[", ":", ",", "None", "]", "return", "P_coarse" ]
Coarse grain transition matrix P using memberships M Computes .. math: Pc = (M' M)^-1 M' P M Parameters ---------- P : ndarray(n, n) microstate transition matrix M : ndarray(n, m) membership matrix. Membership to macrostate m for each microstate. Returns ------- Pc : ndarray(m, m) coarse-grained transition matrix.
[ "Coarse", "grain", "transition", "matrix", "P", "using", "memberships", "M" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/discrete.py#L26-L57
bhmm/bhmm
bhmm/init/discrete.py
regularize_hidden
def regularize_hidden(p0, P, reversible=True, stationary=False, C=None, eps=None): """ Regularizes the hidden initial distribution and transition matrix. Makes sure that the hidden initial distribution and transition matrix have nonzero probabilities by setting them to eps and then renormalizing. Avoids zeros that would cause estimation algorithms to crash or get stuck in suboptimal states. Parameters ---------- p0 : ndarray(n) Initial hidden distribution of the HMM P : ndarray(n, n) Hidden transition matrix reversible : bool HMM is reversible. Will make sure it is still reversible after modification. stationary : bool p0 is the stationary distribution of P. In this case, will not regularize p0 separately. If stationary=False, the regularization will be applied to p0. C : ndarray(n, n) Hidden count matrix. Only needed for stationary=True and P disconnected. epsilon : float or None minimum value of the resulting transition matrix. Default: evaluates to 0.01 / n. The coarse-graining equation can lead to negative elements and thus epsilon should be set to at least 0. Positive settings of epsilon are similar to a prior and enforce minimum positive values for all transition probabilities. Return ------ p0 : ndarray(n) regularized initial distribution P : ndarray(n, n) regularized transition matrix """ # 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.enforce_reversible_on_closed(P) # REGULARIZE p0 if stationary: _tmatrix_disconnected.stationary_distribution(P, C=C) else: p0 = np.maximum(p0, eps) p0 /= p0.sum() return p0, P
python
def regularize_hidden(p0, P, reversible=True, stationary=False, C=None, eps=None): """ Regularizes the hidden initial distribution and transition matrix. Makes sure that the hidden initial distribution and transition matrix have nonzero probabilities by setting them to eps and then renormalizing. Avoids zeros that would cause estimation algorithms to crash or get stuck in suboptimal states. Parameters ---------- p0 : ndarray(n) Initial hidden distribution of the HMM P : ndarray(n, n) Hidden transition matrix reversible : bool HMM is reversible. Will make sure it is still reversible after modification. stationary : bool p0 is the stationary distribution of P. In this case, will not regularize p0 separately. If stationary=False, the regularization will be applied to p0. C : ndarray(n, n) Hidden count matrix. Only needed for stationary=True and P disconnected. epsilon : float or None minimum value of the resulting transition matrix. Default: evaluates to 0.01 / n. The coarse-graining equation can lead to negative elements and thus epsilon should be set to at least 0. Positive settings of epsilon are similar to a prior and enforce minimum positive values for all transition probabilities. Return ------ p0 : ndarray(n) regularized initial distribution P : ndarray(n, n) regularized transition matrix """ # 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.enforce_reversible_on_closed(P) # REGULARIZE p0 if stationary: _tmatrix_disconnected.stationary_distribution(P, C=C) else: p0 = np.maximum(p0, eps) p0 /= p0.sum() return p0, P
[ "def", "regularize_hidden", "(", "p0", ",", "P", ",", "reversible", "=", "True", ",", "stationary", "=", "False", ",", "C", "=", "None", ",", "eps", "=", "None", ")", ":", "# 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", ".", "enforce_reversible_on_closed", "(", "P", ")", "# REGULARIZE p0", "if", "stationary", ":", "_tmatrix_disconnected", ".", "stationary_distribution", "(", "P", ",", "C", "=", "C", ")", "else", ":", "p0", "=", "np", ".", "maximum", "(", "p0", ",", "eps", ")", "p0", "/=", "p0", ".", "sum", "(", ")", "return", "p0", ",", "P" ]
Regularizes the hidden initial distribution and transition matrix. Makes sure that the hidden initial distribution and transition matrix have nonzero probabilities by setting them to eps and then renormalizing. Avoids zeros that would cause estimation algorithms to crash or get stuck in suboptimal states. Parameters ---------- p0 : ndarray(n) Initial hidden distribution of the HMM P : ndarray(n, n) Hidden transition matrix reversible : bool HMM is reversible. Will make sure it is still reversible after modification. stationary : bool p0 is the stationary distribution of P. In this case, will not regularize p0 separately. If stationary=False, the regularization will be applied to p0. C : ndarray(n, n) Hidden count matrix. Only needed for stationary=True and P disconnected. epsilon : float or None minimum value of the resulting transition matrix. Default: evaluates to 0.01 / n. The coarse-graining equation can lead to negative elements and thus epsilon should be set to at least 0. Positive settings of epsilon are similar to a prior and enforce minimum positive values for all transition probabilities. Return ------ p0 : ndarray(n) regularized initial distribution P : ndarray(n, n) regularized transition matrix
[ "Regularizes", "the", "hidden", "initial", "distribution", "and", "transition", "matrix", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/discrete.py#L60-L116
bhmm/bhmm
bhmm/init/discrete.py
regularize_pobs
def regularize_pobs(B, nonempty=None, separate=None, eps=None): """ Regularizes the output probabilities. Makes sure that the output probability distributions has nonzero probabilities by setting them to eps and then renormalizing. Avoids zeros that would cause estimation algorithms to crash or get stuck in suboptimal states. Parameters ---------- B : ndarray(n, m) HMM output probabilities nonempty : None or iterable of int Nonempty set. Only regularize on this subset. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. reversible : bool HMM is reversible. Will make sure it is still reversible after modification. Returns ------- B : ndarray(n, m) Regularized output probabilities """ # 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: B[:, nonempty] = np.maximum(B[:, nonempty], eps) else: nonempty_nonseparate = np.array(list(set(nonempty) - set(separate)), dtype=int) nonempty_separate = np.array(list(set(nonempty).intersection(set(separate))), dtype=int) B[:n-1, nonempty_nonseparate] = np.maximum(B[:n-1, nonempty_nonseparate], eps) B[n-1, nonempty_separate] = np.maximum(B[n-1, nonempty_separate], eps) # renormalize and return copy B /= B.sum(axis=1)[:, None] return B
python
def regularize_pobs(B, nonempty=None, separate=None, eps=None): """ Regularizes the output probabilities. Makes sure that the output probability distributions has nonzero probabilities by setting them to eps and then renormalizing. Avoids zeros that would cause estimation algorithms to crash or get stuck in suboptimal states. Parameters ---------- B : ndarray(n, m) HMM output probabilities nonempty : None or iterable of int Nonempty set. Only regularize on this subset. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. reversible : bool HMM is reversible. Will make sure it is still reversible after modification. Returns ------- B : ndarray(n, m) Regularized output probabilities """ # 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: B[:, nonempty] = np.maximum(B[:, nonempty], eps) else: nonempty_nonseparate = np.array(list(set(nonempty) - set(separate)), dtype=int) nonempty_separate = np.array(list(set(nonempty).intersection(set(separate))), dtype=int) B[:n-1, nonempty_nonseparate] = np.maximum(B[:n-1, nonempty_nonseparate], eps) B[n-1, nonempty_separate] = np.maximum(B[n-1, nonempty_separate], eps) # renormalize and return copy B /= B.sum(axis=1)[:, None] return B
[ "def", "regularize_pobs", "(", "B", ",", "nonempty", "=", "None", ",", "separate", "=", "None", ",", "eps", "=", "None", ")", ":", "# 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", ":", "B", "[", ":", ",", "nonempty", "]", "=", "np", ".", "maximum", "(", "B", "[", ":", ",", "nonempty", "]", ",", "eps", ")", "else", ":", "nonempty_nonseparate", "=", "np", ".", "array", "(", "list", "(", "set", "(", "nonempty", ")", "-", "set", "(", "separate", ")", ")", ",", "dtype", "=", "int", ")", "nonempty_separate", "=", "np", ".", "array", "(", "list", "(", "set", "(", "nonempty", ")", ".", "intersection", "(", "set", "(", "separate", ")", ")", ")", ",", "dtype", "=", "int", ")", "B", "[", ":", "n", "-", "1", ",", "nonempty_nonseparate", "]", "=", "np", ".", "maximum", "(", "B", "[", ":", "n", "-", "1", ",", "nonempty_nonseparate", "]", ",", "eps", ")", "B", "[", "n", "-", "1", ",", "nonempty_separate", "]", "=", "np", ".", "maximum", "(", "B", "[", "n", "-", "1", ",", "nonempty_separate", "]", ",", "eps", ")", "# renormalize and return copy", "B", "/=", "B", ".", "sum", "(", "axis", "=", "1", ")", "[", ":", ",", "None", "]", "return", "B" ]
Regularizes the output probabilities. Makes sure that the output probability distributions has nonzero probabilities by setting them to eps and then renormalizing. Avoids zeros that would cause estimation algorithms to crash or get stuck in suboptimal states. Parameters ---------- B : ndarray(n, m) HMM output probabilities nonempty : None or iterable of int Nonempty set. Only regularize on this subset. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. reversible : bool HMM is reversible. Will make sure it is still reversible after modification. Returns ------- B : ndarray(n, m) Regularized output probabilities
[ "Regularizes", "the", "output", "probabilities", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/discrete.py#L119-L164
bhmm/bhmm
bhmm/init/discrete.py
init_discrete_hmm_spectral
def init_discrete_hmm_spectral(C_full, nstates, reversible=True, stationary=True, active_set=None, P=None, eps_A=None, eps_B=None, separate=None): """Initializes discrete HMM using spectral clustering of observation counts Initializes HMM as described in [1]_. First estimates a Markov state model on the given observations, then uses PCCA+ to coarse-grain the transition matrix [2]_ which initializes the HMM transition matrix. The HMM output probabilities are given by Bayesian inversion from the PCCA+ memberships [1]_. The regularization parameters eps_A and eps_B are used to guarantee that the hidden transition matrix and output probability matrix have no zeros. HMM estimation algorithms such as the EM algorithm and the Bayesian sampling algorithm cannot recover from zero entries, i.e. once they are zero, they will stay zero. Parameters ---------- C_full : ndarray(N, N) Transition count matrix on the full observable state space nstates : int The number of hidden states. reversible : bool Estimate reversible HMM transition matrix. stationary : bool p0 is the stationary distribution of P. In this case, will not active_set : ndarray(n, dtype=int) or None Index area. Will estimate kinetics only on the given subset of C P : ndarray(n, n) Transition matrix estimated from C (with option reversible). Use this option if P has already been estimated to avoid estimating it twice. eps_A : float or None Minimum transition probability. Default: 0.01 / nstates eps_B : float or None Minimum output probability. Default: 0.01 / nfull separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. Returns ------- p0 : ndarray(n) Hidden state initial distribution A : ndarray(n, n) Hidden state transition matrix B : ndarray(n, N) Hidden-to-observable state output probabilities Raises ------ ValueError If the given active set is illegal. NotImplementedError If the number of hidden states exceeds the number of observed states. Examples -------- Generate initial model for a discrete output model. >>> import numpy as np >>> C = np.array([[0.5, 0.5, 0.0], [0.4, 0.5, 0.1], [0.0, 0.1, 0.9]]) >>> initial_model = init_discrete_hmm_spectral(C, 2) References ---------- .. [1] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) .. [2] S. Kube and M. Weber: A coarse graining method for the identification of transition rates between molecular conformations. J. Chem. Phys. 126, 024103 (2007) """ # MICROSTATE COUNT MATRIX nfull = C_full.shape[0] # INPUTS if eps_A is None: # default transition probability, in order to avoid zero columns eps_A = 0.01 / nstates if eps_B is None: # default output probability, in order to avoid zero columns eps_B = 0.01 / nfull # Manage sets symsum = C_full.sum(axis=0) + C_full.sum(axis=1) nonempty = np.where(symsum > 0)[0] if active_set is None: active_set = nonempty else: if np.any(symsum[active_set] == 0): raise ValueError('Given active set has empty states') # don't tolerate empty states if P is not None: if np.shape(P)[0] != active_set.size: # needs to fit to active raise ValueError('Given initial transition matrix P has shape ' + str(np.shape(P)) + 'while active set has size ' + str(active_set.size)) # when using separate states, only keep the nonempty ones (the others don't matter) if separate is None: active_nonseparate = active_set.copy() nmeta = nstates else: if np.max(separate) >= nfull: raise ValueError('Separate set has indexes that do not exist in full state space: ' + str(np.max(separate))) active_nonseparate = np.array(list(set(active_set) - set(separate))) nmeta = nstates - 1 # check if we can proceed if active_nonseparate.size < nmeta: raise NotImplementedError('Trying to initialize ' + str(nmeta) + '-state HMM from smaller ' + str(active_nonseparate.size) + '-state MSM.') # MICROSTATE TRANSITION MATRIX (MSM). C_active = C_full[np.ix_(active_set, active_set)] if P is None: # This matrix may be disconnected and have transient states P_active = _tmatrix_disconnected.estimate_P(C_active, reversible=reversible, maxiter=10000) # short iteration else: P_active = P # MICROSTATE EQUILIBRIUM DISTRIBUTION pi_active = _tmatrix_disconnected.stationary_distribution(P_active, C=C_active) pi_full = np.zeros(nfull) pi_full[active_set] = pi_active # NONSEPARATE TRANSITION MATRIX FOR PCCA+ C_active_nonseparate = C_full[np.ix_(active_nonseparate, active_nonseparate)] if reversible and separate is None: # in this case we already have a reversible estimate with the right size P_active_nonseparate = P_active else: # not yet reversible. re-estimate P_active_nonseparate = _tmatrix_disconnected.estimate_P(C_active_nonseparate, reversible=True) # COARSE-GRAINING WITH PCCA+ if active_nonseparate.size > nmeta: from msmtools.analysis.dense.pcca import PCCA pcca_obj = PCCA(P_active_nonseparate, nmeta) M_active_nonseparate = pcca_obj.memberships # memberships B_active_nonseparate = pcca_obj.output_probabilities # output probabilities else: # equal size M_active_nonseparate = np.eye(nmeta) B_active_nonseparate = np.eye(nmeta) # ADD SEPARATE STATE IF NEEDED if separate is None: M_active = M_active_nonseparate else: M_full = np.zeros((nfull, nstates)) M_full[active_nonseparate, :nmeta] = M_active_nonseparate M_full[separate, -1] = 1 M_active = M_full[active_set] # COARSE-GRAINED TRANSITION MATRIX P_hmm = coarse_grain_transition_matrix(P_active, M_active) if reversible: P_hmm = _tmatrix_disconnected.enforce_reversible_on_closed(P_hmm) C_hmm = M_active.T.dot(C_active).dot(M_active) pi_hmm = _tmatrix_disconnected.stationary_distribution(P_hmm, C=C_hmm) # need C_hmm in case if A is disconnected # COARSE-GRAINED OUTPUT DISTRIBUTION B_hmm = np.zeros((nstates, nfull)) B_hmm[:nmeta, active_nonseparate] = B_active_nonseparate if separate is not None: # add separate states B_hmm[-1, separate] = pi_full[separate] # REGULARIZE SOLUTION pi_hmm, P_hmm = regularize_hidden(pi_hmm, P_hmm, reversible=reversible, stationary=stationary, C=C_hmm, eps=eps_A) B_hmm = regularize_pobs(B_hmm, nonempty=nonempty, separate=separate, eps=eps_B) # print 'cg pi: ', pi_hmm # print 'cg A:\n ', P_hmm # print 'cg B:\n ', B_hmm logger().info('Initial model: ') logger().info('initial distribution = \n'+str(pi_hmm)) logger().info('transition matrix = \n'+str(P_hmm)) logger().info('output matrix = \n'+str(B_hmm.T)) return pi_hmm, P_hmm, B_hmm
python
def init_discrete_hmm_spectral(C_full, nstates, reversible=True, stationary=True, active_set=None, P=None, eps_A=None, eps_B=None, separate=None): """Initializes discrete HMM using spectral clustering of observation counts Initializes HMM as described in [1]_. First estimates a Markov state model on the given observations, then uses PCCA+ to coarse-grain the transition matrix [2]_ which initializes the HMM transition matrix. The HMM output probabilities are given by Bayesian inversion from the PCCA+ memberships [1]_. The regularization parameters eps_A and eps_B are used to guarantee that the hidden transition matrix and output probability matrix have no zeros. HMM estimation algorithms such as the EM algorithm and the Bayesian sampling algorithm cannot recover from zero entries, i.e. once they are zero, they will stay zero. Parameters ---------- C_full : ndarray(N, N) Transition count matrix on the full observable state space nstates : int The number of hidden states. reversible : bool Estimate reversible HMM transition matrix. stationary : bool p0 is the stationary distribution of P. In this case, will not active_set : ndarray(n, dtype=int) or None Index area. Will estimate kinetics only on the given subset of C P : ndarray(n, n) Transition matrix estimated from C (with option reversible). Use this option if P has already been estimated to avoid estimating it twice. eps_A : float or None Minimum transition probability. Default: 0.01 / nstates eps_B : float or None Minimum output probability. Default: 0.01 / nfull separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. Returns ------- p0 : ndarray(n) Hidden state initial distribution A : ndarray(n, n) Hidden state transition matrix B : ndarray(n, N) Hidden-to-observable state output probabilities Raises ------ ValueError If the given active set is illegal. NotImplementedError If the number of hidden states exceeds the number of observed states. Examples -------- Generate initial model for a discrete output model. >>> import numpy as np >>> C = np.array([[0.5, 0.5, 0.0], [0.4, 0.5, 0.1], [0.0, 0.1, 0.9]]) >>> initial_model = init_discrete_hmm_spectral(C, 2) References ---------- .. [1] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) .. [2] S. Kube and M. Weber: A coarse graining method for the identification of transition rates between molecular conformations. J. Chem. Phys. 126, 024103 (2007) """ # MICROSTATE COUNT MATRIX nfull = C_full.shape[0] # INPUTS if eps_A is None: # default transition probability, in order to avoid zero columns eps_A = 0.01 / nstates if eps_B is None: # default output probability, in order to avoid zero columns eps_B = 0.01 / nfull # Manage sets symsum = C_full.sum(axis=0) + C_full.sum(axis=1) nonempty = np.where(symsum > 0)[0] if active_set is None: active_set = nonempty else: if np.any(symsum[active_set] == 0): raise ValueError('Given active set has empty states') # don't tolerate empty states if P is not None: if np.shape(P)[0] != active_set.size: # needs to fit to active raise ValueError('Given initial transition matrix P has shape ' + str(np.shape(P)) + 'while active set has size ' + str(active_set.size)) # when using separate states, only keep the nonempty ones (the others don't matter) if separate is None: active_nonseparate = active_set.copy() nmeta = nstates else: if np.max(separate) >= nfull: raise ValueError('Separate set has indexes that do not exist in full state space: ' + str(np.max(separate))) active_nonseparate = np.array(list(set(active_set) - set(separate))) nmeta = nstates - 1 # check if we can proceed if active_nonseparate.size < nmeta: raise NotImplementedError('Trying to initialize ' + str(nmeta) + '-state HMM from smaller ' + str(active_nonseparate.size) + '-state MSM.') # MICROSTATE TRANSITION MATRIX (MSM). C_active = C_full[np.ix_(active_set, active_set)] if P is None: # This matrix may be disconnected and have transient states P_active = _tmatrix_disconnected.estimate_P(C_active, reversible=reversible, maxiter=10000) # short iteration else: P_active = P # MICROSTATE EQUILIBRIUM DISTRIBUTION pi_active = _tmatrix_disconnected.stationary_distribution(P_active, C=C_active) pi_full = np.zeros(nfull) pi_full[active_set] = pi_active # NONSEPARATE TRANSITION MATRIX FOR PCCA+ C_active_nonseparate = C_full[np.ix_(active_nonseparate, active_nonseparate)] if reversible and separate is None: # in this case we already have a reversible estimate with the right size P_active_nonseparate = P_active else: # not yet reversible. re-estimate P_active_nonseparate = _tmatrix_disconnected.estimate_P(C_active_nonseparate, reversible=True) # COARSE-GRAINING WITH PCCA+ if active_nonseparate.size > nmeta: from msmtools.analysis.dense.pcca import PCCA pcca_obj = PCCA(P_active_nonseparate, nmeta) M_active_nonseparate = pcca_obj.memberships # memberships B_active_nonseparate = pcca_obj.output_probabilities # output probabilities else: # equal size M_active_nonseparate = np.eye(nmeta) B_active_nonseparate = np.eye(nmeta) # ADD SEPARATE STATE IF NEEDED if separate is None: M_active = M_active_nonseparate else: M_full = np.zeros((nfull, nstates)) M_full[active_nonseparate, :nmeta] = M_active_nonseparate M_full[separate, -1] = 1 M_active = M_full[active_set] # COARSE-GRAINED TRANSITION MATRIX P_hmm = coarse_grain_transition_matrix(P_active, M_active) if reversible: P_hmm = _tmatrix_disconnected.enforce_reversible_on_closed(P_hmm) C_hmm = M_active.T.dot(C_active).dot(M_active) pi_hmm = _tmatrix_disconnected.stationary_distribution(P_hmm, C=C_hmm) # need C_hmm in case if A is disconnected # COARSE-GRAINED OUTPUT DISTRIBUTION B_hmm = np.zeros((nstates, nfull)) B_hmm[:nmeta, active_nonseparate] = B_active_nonseparate if separate is not None: # add separate states B_hmm[-1, separate] = pi_full[separate] # REGULARIZE SOLUTION pi_hmm, P_hmm = regularize_hidden(pi_hmm, P_hmm, reversible=reversible, stationary=stationary, C=C_hmm, eps=eps_A) B_hmm = regularize_pobs(B_hmm, nonempty=nonempty, separate=separate, eps=eps_B) # print 'cg pi: ', pi_hmm # print 'cg A:\n ', P_hmm # print 'cg B:\n ', B_hmm logger().info('Initial model: ') logger().info('initial distribution = \n'+str(pi_hmm)) logger().info('transition matrix = \n'+str(P_hmm)) logger().info('output matrix = \n'+str(B_hmm.T)) return pi_hmm, P_hmm, B_hmm
[ "def", "init_discrete_hmm_spectral", "(", "C_full", ",", "nstates", ",", "reversible", "=", "True", ",", "stationary", "=", "True", ",", "active_set", "=", "None", ",", "P", "=", "None", ",", "eps_A", "=", "None", ",", "eps_B", "=", "None", ",", "separate", "=", "None", ")", ":", "# MICROSTATE COUNT MATRIX", "nfull", "=", "C_full", ".", "shape", "[", "0", "]", "# INPUTS", "if", "eps_A", "is", "None", ":", "# default transition probability, in order to avoid zero columns", "eps_A", "=", "0.01", "/", "nstates", "if", "eps_B", "is", "None", ":", "# default output probability, in order to avoid zero columns", "eps_B", "=", "0.01", "/", "nfull", "# Manage sets", "symsum", "=", "C_full", ".", "sum", "(", "axis", "=", "0", ")", "+", "C_full", ".", "sum", "(", "axis", "=", "1", ")", "nonempty", "=", "np", ".", "where", "(", "symsum", ">", "0", ")", "[", "0", "]", "if", "active_set", "is", "None", ":", "active_set", "=", "nonempty", "else", ":", "if", "np", ".", "any", "(", "symsum", "[", "active_set", "]", "==", "0", ")", ":", "raise", "ValueError", "(", "'Given active set has empty states'", ")", "# don't tolerate empty states", "if", "P", "is", "not", "None", ":", "if", "np", ".", "shape", "(", "P", ")", "[", "0", "]", "!=", "active_set", ".", "size", ":", "# needs to fit to active", "raise", "ValueError", "(", "'Given initial transition matrix P has shape '", "+", "str", "(", "np", ".", "shape", "(", "P", ")", ")", "+", "'while active set has size '", "+", "str", "(", "active_set", ".", "size", ")", ")", "# when using separate states, only keep the nonempty ones (the others don't matter)", "if", "separate", "is", "None", ":", "active_nonseparate", "=", "active_set", ".", "copy", "(", ")", "nmeta", "=", "nstates", "else", ":", "if", "np", ".", "max", "(", "separate", ")", ">=", "nfull", ":", "raise", "ValueError", "(", "'Separate set has indexes that do not exist in full state space: '", "+", "str", "(", "np", ".", "max", "(", "separate", ")", ")", ")", "active_nonseparate", "=", "np", ".", "array", "(", "list", "(", "set", "(", "active_set", ")", "-", "set", "(", "separate", ")", ")", ")", "nmeta", "=", "nstates", "-", "1", "# check if we can proceed", "if", "active_nonseparate", ".", "size", "<", "nmeta", ":", "raise", "NotImplementedError", "(", "'Trying to initialize '", "+", "str", "(", "nmeta", ")", "+", "'-state HMM from smaller '", "+", "str", "(", "active_nonseparate", ".", "size", ")", "+", "'-state MSM.'", ")", "# MICROSTATE TRANSITION MATRIX (MSM).", "C_active", "=", "C_full", "[", "np", ".", "ix_", "(", "active_set", ",", "active_set", ")", "]", "if", "P", "is", "None", ":", "# This matrix may be disconnected and have transient states", "P_active", "=", "_tmatrix_disconnected", ".", "estimate_P", "(", "C_active", ",", "reversible", "=", "reversible", ",", "maxiter", "=", "10000", ")", "# short iteration", "else", ":", "P_active", "=", "P", "# MICROSTATE EQUILIBRIUM DISTRIBUTION", "pi_active", "=", "_tmatrix_disconnected", ".", "stationary_distribution", "(", "P_active", ",", "C", "=", "C_active", ")", "pi_full", "=", "np", ".", "zeros", "(", "nfull", ")", "pi_full", "[", "active_set", "]", "=", "pi_active", "# NONSEPARATE TRANSITION MATRIX FOR PCCA+", "C_active_nonseparate", "=", "C_full", "[", "np", ".", "ix_", "(", "active_nonseparate", ",", "active_nonseparate", ")", "]", "if", "reversible", "and", "separate", "is", "None", ":", "# in this case we already have a reversible estimate with the right size", "P_active_nonseparate", "=", "P_active", "else", ":", "# not yet reversible. re-estimate", "P_active_nonseparate", "=", "_tmatrix_disconnected", ".", "estimate_P", "(", "C_active_nonseparate", ",", "reversible", "=", "True", ")", "# COARSE-GRAINING WITH PCCA+", "if", "active_nonseparate", ".", "size", ">", "nmeta", ":", "from", "msmtools", ".", "analysis", ".", "dense", ".", "pcca", "import", "PCCA", "pcca_obj", "=", "PCCA", "(", "P_active_nonseparate", ",", "nmeta", ")", "M_active_nonseparate", "=", "pcca_obj", ".", "memberships", "# memberships", "B_active_nonseparate", "=", "pcca_obj", ".", "output_probabilities", "# output probabilities", "else", ":", "# equal size", "M_active_nonseparate", "=", "np", ".", "eye", "(", "nmeta", ")", "B_active_nonseparate", "=", "np", ".", "eye", "(", "nmeta", ")", "# ADD SEPARATE STATE IF NEEDED", "if", "separate", "is", "None", ":", "M_active", "=", "M_active_nonseparate", "else", ":", "M_full", "=", "np", ".", "zeros", "(", "(", "nfull", ",", "nstates", ")", ")", "M_full", "[", "active_nonseparate", ",", ":", "nmeta", "]", "=", "M_active_nonseparate", "M_full", "[", "separate", ",", "-", "1", "]", "=", "1", "M_active", "=", "M_full", "[", "active_set", "]", "# COARSE-GRAINED TRANSITION MATRIX", "P_hmm", "=", "coarse_grain_transition_matrix", "(", "P_active", ",", "M_active", ")", "if", "reversible", ":", "P_hmm", "=", "_tmatrix_disconnected", ".", "enforce_reversible_on_closed", "(", "P_hmm", ")", "C_hmm", "=", "M_active", ".", "T", ".", "dot", "(", "C_active", ")", ".", "dot", "(", "M_active", ")", "pi_hmm", "=", "_tmatrix_disconnected", ".", "stationary_distribution", "(", "P_hmm", ",", "C", "=", "C_hmm", ")", "# need C_hmm in case if A is disconnected", "# COARSE-GRAINED OUTPUT DISTRIBUTION", "B_hmm", "=", "np", ".", "zeros", "(", "(", "nstates", ",", "nfull", ")", ")", "B_hmm", "[", ":", "nmeta", ",", "active_nonseparate", "]", "=", "B_active_nonseparate", "if", "separate", "is", "not", "None", ":", "# add separate states", "B_hmm", "[", "-", "1", ",", "separate", "]", "=", "pi_full", "[", "separate", "]", "# REGULARIZE SOLUTION", "pi_hmm", ",", "P_hmm", "=", "regularize_hidden", "(", "pi_hmm", ",", "P_hmm", ",", "reversible", "=", "reversible", ",", "stationary", "=", "stationary", ",", "C", "=", "C_hmm", ",", "eps", "=", "eps_A", ")", "B_hmm", "=", "regularize_pobs", "(", "B_hmm", ",", "nonempty", "=", "nonempty", ",", "separate", "=", "separate", ",", "eps", "=", "eps_B", ")", "# print 'cg pi: ', pi_hmm", "# print 'cg A:\\n ', P_hmm", "# print 'cg B:\\n ', B_hmm", "logger", "(", ")", ".", "info", "(", "'Initial model: '", ")", "logger", "(", ")", ".", "info", "(", "'initial distribution = \\n'", "+", "str", "(", "pi_hmm", ")", ")", "logger", "(", ")", ".", "info", "(", "'transition matrix = \\n'", "+", "str", "(", "P_hmm", ")", ")", "logger", "(", ")", ".", "info", "(", "'output matrix = \\n'", "+", "str", "(", "B_hmm", ".", "T", ")", ")", "return", "pi_hmm", ",", "P_hmm", ",", "B_hmm" ]
Initializes discrete HMM using spectral clustering of observation counts Initializes HMM as described in [1]_. First estimates a Markov state model on the given observations, then uses PCCA+ to coarse-grain the transition matrix [2]_ which initializes the HMM transition matrix. The HMM output probabilities are given by Bayesian inversion from the PCCA+ memberships [1]_. The regularization parameters eps_A and eps_B are used to guarantee that the hidden transition matrix and output probability matrix have no zeros. HMM estimation algorithms such as the EM algorithm and the Bayesian sampling algorithm cannot recover from zero entries, i.e. once they are zero, they will stay zero. Parameters ---------- C_full : ndarray(N, N) Transition count matrix on the full observable state space nstates : int The number of hidden states. reversible : bool Estimate reversible HMM transition matrix. stationary : bool p0 is the stationary distribution of P. In this case, will not active_set : ndarray(n, dtype=int) or None Index area. Will estimate kinetics only on the given subset of C P : ndarray(n, n) Transition matrix estimated from C (with option reversible). Use this option if P has already been estimated to avoid estimating it twice. eps_A : float or None Minimum transition probability. Default: 0.01 / nstates eps_B : float or None Minimum output probability. Default: 0.01 / nfull separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. Returns ------- p0 : ndarray(n) Hidden state initial distribution A : ndarray(n, n) Hidden state transition matrix B : ndarray(n, N) Hidden-to-observable state output probabilities Raises ------ ValueError If the given active set is illegal. NotImplementedError If the number of hidden states exceeds the number of observed states. Examples -------- Generate initial model for a discrete output model. >>> import numpy as np >>> C = np.array([[0.5, 0.5, 0.0], [0.4, 0.5, 0.1], [0.0, 0.1, 0.9]]) >>> initial_model = init_discrete_hmm_spectral(C, 2) References ---------- .. [1] F. Noe, H. Wu, J.-H. Prinz and N. Plattner: Projected and hidden Markov models for calculating kinetics and metastable states of complex molecules. J. Chem. Phys. 139, 184114 (2013) .. [2] S. Kube and M. Weber: A coarse graining method for the identification of transition rates between molecular conformations. J. Chem. Phys. 126, 024103 (2007)
[ "Initializes", "discrete", "HMM", "using", "spectral", "clustering", "of", "observation", "counts" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/discrete.py#L167-L338
bhmm/bhmm
bhmm/init/discrete.py
init_discrete_hmm_ml
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 discrete HMM using maximum likelihood of observation counts""" raise NotImplementedError('ML-initialization not yet implemented')
python
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 discrete HMM using maximum likelihood of observation counts""" raise NotImplementedError('ML-initialization not yet implemented')
[ "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", ")", ":", "raise", "NotImplementedError", "(", "'ML-initialization not yet implemented'", ")" ]
Initializes discrete HMM using maximum likelihood of observation counts
[ "Initializes", "discrete", "HMM", "using", "maximum", "likelihood", "of", "observation", "counts" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/discrete.py#L342-L345
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.update
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 unexpected number of states ' # reset spectral decomposition self._spectral_decomp_available = False # check initial distribution assert np.all(Pi >= 0), 'Given initial distribution contains negative elements.' assert np.any(Pi > 0), 'Given initial distribution is zero' self._Pi = np.array(Pi) / np.sum(Pi)
python
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 unexpected number of states ' # reset spectral decomposition self._spectral_decomp_available = False # check initial distribution assert np.all(Pi >= 0), 'Given initial distribution contains negative elements.' assert np.any(Pi > 0), 'Given initial distribution is zero' self._Pi = np.array(Pi) / np.sum(Pi)
[ "def", "update", "(", "self", ",", "Pi", ",", "Tij", ")", ":", "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 unexpected number of states '", "# reset spectral decomposition", "self", ".", "_spectral_decomp_available", "=", "False", "# check initial distribution", "assert", "np", ".", "all", "(", "Pi", ">=", "0", ")", ",", "'Given initial distribution contains negative elements.'", "assert", "np", ".", "any", "(", "Pi", ">", "0", ")", ",", "'Given initial distribution is zero'", "self", ".", "_Pi", "=", "np", ".", "array", "(", "Pi", ")", "/", "np", ".", "sum", "(", "Pi", ")" ]
r""" Updates the transition matrix and recomputes all derived quantities
[ "r", "Updates", "the", "transition", "matrix", "and", "recomputes", "all", "derived", "quantities" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L79-L93
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.is_stationary
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)
python
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)
[ "def", "is_stationary", "(", "self", ")", ":", "# 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", ")" ]
r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution of the hidden transition matrix.
[ "r", "Whether", "the", "MSM", "is", "stationary", "i", ".", "e", ".", "whether", "the", "initial", "distribution", "is", "the", "stationary", "distribution", "of", "the", "hidden", "transition", "matrix", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L167-L172
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.stationary_distribution
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)
python
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)
[ "def", "stationary_distribution", "(", "self", ")", ":", "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", ")" ]
r""" Compute stationary distribution of hidden states if possible. Raises ------ ValueError if the HMM is not stationary
[ "r", "Compute", "stationary", "distribution", "of", "hidden", "states", "if", "possible", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L185-L196
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.timescales
def timescales(self): r""" Relaxation timescales of the hidden transition matrix Returns ------- ts : ndarray(m) relaxation timescales in units of the input trajectory time step, defined by :math:`-tau / ln | \lambda_i |, i = 2,...,nstates`, where :math:`\lambda_i` are the hidden transition matrix eigenvalues. """ 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:]
python
def timescales(self): r""" Relaxation timescales of the hidden transition matrix Returns ------- ts : ndarray(m) relaxation timescales in units of the input trajectory time step, defined by :math:`-tau / ln | \lambda_i |, i = 2,...,nstates`, where :math:`\lambda_i` are the hidden transition matrix eigenvalues. """ 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:]
[ "def", "timescales", "(", "self", ")", ":", "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", ":", "]" ]
r""" Relaxation timescales of the hidden transition matrix Returns ------- ts : ndarray(m) relaxation timescales in units of the input trajectory time step, defined by :math:`-tau / ln | \lambda_i |, i = 2,...,nstates`, where :math:`\lambda_i` are the hidden transition matrix eigenvalues.
[ "r", "Relaxation", "timescales", "of", "the", "hidden", "transition", "matrix" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L243-L258
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.lifetimes
def lifetimes(self): r""" Lifetimes of states of the hidden transition matrix Returns ------- l : ndarray(nstates) state lifetimes in units of the input trajectory time step, defined by :math:`-tau / ln | p_{ii} |, i = 1,...,nstates`, where :math:`p_{ii}` are the diagonal entries of the hidden transition matrix. """ return -self._lag / np.log(np.diag(self.transition_matrix))
python
def lifetimes(self): r""" Lifetimes of states of the hidden transition matrix Returns ------- l : ndarray(nstates) state lifetimes in units of the input trajectory time step, defined by :math:`-tau / ln | p_{ii} |, i = 1,...,nstates`, where :math:`p_{ii}` are the diagonal entries of the hidden transition matrix. """ return -self._lag / np.log(np.diag(self.transition_matrix))
[ "def", "lifetimes", "(", "self", ")", ":", "return", "-", "self", ".", "_lag", "/", "np", ".", "log", "(", "np", ".", "diag", "(", "self", ".", "transition_matrix", ")", ")" ]
r""" Lifetimes of states of the hidden transition matrix Returns ------- l : ndarray(nstates) state lifetimes in units of the input trajectory time step, defined by :math:`-tau / ln | p_{ii} |, i = 1,...,nstates`, where :math:`p_{ii}` are the diagonal entries of the hidden transition matrix.
[ "r", "Lifetimes", "of", "states", "of", "the", "hidden", "transition", "matrix" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L261-L272
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.sub_hmm
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 transition matrix cannot be normalized on this subset """ # 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 request: transition matrix cannot be normalized on ' + str(states) P_sub /= P_sub.sum(axis=1)[:, None] # restrict output model out_sub = self.output_model.sub_output_model(states) return HMM(pi_sub, P_sub, out_sub, lag=self.lag)
python
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 transition matrix cannot be normalized on this subset """ # 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 request: transition matrix cannot be normalized on ' + str(states) P_sub /= P_sub.sum(axis=1)[:, None] # restrict output model out_sub = self.output_model.sub_output_model(states) return HMM(pi_sub, P_sub, out_sub, lag=self.lag)
[ "def", "sub_hmm", "(", "self", ",", "states", ")", ":", "# 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 request: transition matrix cannot be normalized on '", "+", "str", "(", "states", ")", "P_sub", "/=", "P_sub", ".", "sum", "(", "axis", "=", "1", ")", "[", ":", ",", "None", "]", "# restrict output model", "out_sub", "=", "self", ".", "output_model", ".", "sub_output_model", "(", "states", ")", "return", "HMM", "(", "pi_sub", ",", "P_sub", ",", "out_sub", ",", "lag", "=", "self", ".", "lag", ")" ]
r""" Returns HMM on a subset of states Returns the HMM restricted to the selected subset of states. Will raise exception if the hidden transition matrix cannot be normalized on this subset
[ "r", "Returns", "HMM", "on", "a", "subset", "of", "states" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L274-L295
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.count_matrix
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 from hidden state trajectory. Returns ------- C : numpy.array with shape (nstates,nstates) C[i,j] is the number of transitions observed from state i to state j Raises ------ RuntimeError A RuntimeError is raised if the HMM model does not yet have a hidden state trajectory associated with it. Examples -------- """ 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()
python
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 from hidden state trajectory. Returns ------- C : numpy.array with shape (nstates,nstates) C[i,j] is the number of transitions observed from state i to state j Raises ------ RuntimeError A RuntimeError is raised if the HMM model does not yet have a hidden state trajectory associated with it. Examples -------- """ 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()
[ "def", "count_matrix", "(", "self", ")", ":", "# TODO: does this belong here or to the BHMM sampler, or in a subclass containing HMM with data?", "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", "(", ")" ]
Compute the transition count matrix from hidden state trajectory. Returns ------- C : numpy.array with shape (nstates,nstates) C[i,j] is the number of transitions observed from state i to state j Raises ------ RuntimeError A RuntimeError is raised if the HMM model does not yet have a hidden state trajectory associated with it. Examples --------
[ "Compute", "the", "transition", "count", "matrix", "from", "hidden", "state", "trajectory", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L297-L319
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.count_init
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)
python
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)
[ "def", "count_init", "(", "self", ")", ":", "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", ")" ]
Compute the counts at the first time step Returns ------- n : ndarray(nstates) n[i] is the number of trajectories starting in state i
[ "Compute", "the", "counts", "at", "the", "first", "time", "step" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L321-L334
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.collect_observations_in_state
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 belonging to a specified hidden state. Parameters ---------- observations : list of numpy.array List of observed trajectories. state_index : int The index of the hidden state for which corresponding observations are to be retrieved. dtype : numpy.dtype, optional, default=numpy.float64 The numpy dtype to use to store the collected observations. Returns ------- collected_observations : numpy.array with shape (nsamples,) The collected vector of observations belonging to the specified hidden state. Raises ------ RuntimeError A RuntimeError is raised if the HMM model does not yet have a hidden state trajectory associated with it. """ 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): indices = np.where(s_t == state_index)[0] collected_observations = np.append(collected_observations, o_t[indices]) return collected_observations
python
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 belonging to a specified hidden state. Parameters ---------- observations : list of numpy.array List of observed trajectories. state_index : int The index of the hidden state for which corresponding observations are to be retrieved. dtype : numpy.dtype, optional, default=numpy.float64 The numpy dtype to use to store the collected observations. Returns ------- collected_observations : numpy.array with shape (nsamples,) The collected vector of observations belonging to the specified hidden state. Raises ------ RuntimeError A RuntimeError is raised if the HMM model does not yet have a hidden state trajectory associated with it. """ 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): indices = np.where(s_t == state_index)[0] collected_observations = np.append(collected_observations, o_t[indices]) return collected_observations
[ "def", "collect_observations_in_state", "(", "self", ",", "observations", ",", "state_index", ")", ":", "# TODO: this would work well in a subclass with data", "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", ")", ":", "indices", "=", "np", ".", "where", "(", "s_t", "==", "state_index", ")", "[", "0", "]", "collected_observations", "=", "np", ".", "append", "(", "collected_observations", ",", "o_t", "[", "indices", "]", ")", "return", "collected_observations" ]
Collect a vector of all observations belonging to a specified hidden state. Parameters ---------- observations : list of numpy.array List of observed trajectories. state_index : int The index of the hidden state for which corresponding observations are to be retrieved. dtype : numpy.dtype, optional, default=numpy.float64 The numpy dtype to use to store the collected observations. Returns ------- collected_observations : numpy.array with shape (nsamples,) The collected vector of observations belonging to the specified hidden state. Raises ------ RuntimeError A RuntimeError is raised if the HMM model does not yet have a hidden state trajectory associated with it.
[ "Collect", "a", "vector", "of", "all", "observations", "belonging", "to", "a", "specified", "hidden", "state", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L398-L431
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.generate_synthetic_state_trajectory
def generate_synthetic_state_trajectory(self, nsteps, initial_Pi=None, start=None, stop=None, dtype=np.int32): """Generate a synthetic state trajectory. Parameters ---------- nsteps : int Number of steps in the synthetic state trajectory to be generated. initial_Pi : np.array of shape (nstates,), optional, default=None The initial probability distribution, if samples are not to be taken from the intrinsic initial distribution. start : int starting state. Exclusive with initial_Pi stop : int stopping state. Trajectory will terminate when reaching the stopping state before length number of steps. dtype : numpy.dtype, optional, default=numpy.int32 The numpy dtype to use to store the synthetic trajectory. Returns ------- states : np.array of shape (nstates,) of dtype=np.int32 The trajectory of hidden states, with each element in range(0,nstates). Examples -------- Generate a synthetic state trajectory of a specified length. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> states = model.generate_synthetic_state_trajectory(nsteps=100) """ # 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.random.choice(range(self._nstates), size=1, p=initial_Pi) else: start = np.random.choice(range(self._nstates), size=1, p=self._Pi) # Generate and return trajectory from msmtools import generation as msmgen traj = msmgen.generate_traj(self.transition_matrix, nsteps, start=start, stop=stop, dt=1) return traj.astype(dtype)
python
def generate_synthetic_state_trajectory(self, nsteps, initial_Pi=None, start=None, stop=None, dtype=np.int32): """Generate a synthetic state trajectory. Parameters ---------- nsteps : int Number of steps in the synthetic state trajectory to be generated. initial_Pi : np.array of shape (nstates,), optional, default=None The initial probability distribution, if samples are not to be taken from the intrinsic initial distribution. start : int starting state. Exclusive with initial_Pi stop : int stopping state. Trajectory will terminate when reaching the stopping state before length number of steps. dtype : numpy.dtype, optional, default=numpy.int32 The numpy dtype to use to store the synthetic trajectory. Returns ------- states : np.array of shape (nstates,) of dtype=np.int32 The trajectory of hidden states, with each element in range(0,nstates). Examples -------- Generate a synthetic state trajectory of a specified length. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> states = model.generate_synthetic_state_trajectory(nsteps=100) """ # 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.random.choice(range(self._nstates), size=1, p=initial_Pi) else: start = np.random.choice(range(self._nstates), size=1, p=self._Pi) # Generate and return trajectory from msmtools import generation as msmgen traj = msmgen.generate_traj(self.transition_matrix, nsteps, start=start, stop=stop, dt=1) return traj.astype(dtype)
[ "def", "generate_synthetic_state_trajectory", "(", "self", ",", "nsteps", ",", "initial_Pi", "=", "None", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "dtype", "=", "np", ".", "int32", ")", ":", "# 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", ".", "random", ".", "choice", "(", "range", "(", "self", ".", "_nstates", ")", ",", "size", "=", "1", ",", "p", "=", "initial_Pi", ")", "else", ":", "start", "=", "np", ".", "random", ".", "choice", "(", "range", "(", "self", ".", "_nstates", ")", ",", "size", "=", "1", ",", "p", "=", "self", ".", "_Pi", ")", "# Generate and return trajectory", "from", "msmtools", "import", "generation", "as", "msmgen", "traj", "=", "msmgen", ".", "generate_traj", "(", "self", ".", "transition_matrix", ",", "nsteps", ",", "start", "=", "start", ",", "stop", "=", "stop", ",", "dt", "=", "1", ")", "return", "traj", ".", "astype", "(", "dtype", ")" ]
Generate a synthetic state trajectory. Parameters ---------- nsteps : int Number of steps in the synthetic state trajectory to be generated. initial_Pi : np.array of shape (nstates,), optional, default=None The initial probability distribution, if samples are not to be taken from the intrinsic initial distribution. start : int starting state. Exclusive with initial_Pi stop : int stopping state. Trajectory will terminate when reaching the stopping state before length number of steps. dtype : numpy.dtype, optional, default=numpy.int32 The numpy dtype to use to store the synthetic trajectory. Returns ------- states : np.array of shape (nstates,) of dtype=np.int32 The trajectory of hidden states, with each element in range(0,nstates). Examples -------- Generate a synthetic state trajectory of a specified length. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> states = model.generate_synthetic_state_trajectory(nsteps=100)
[ "Generate", "a", "synthetic", "state", "trajectory", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L433-L479
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.generate_synthetic_observation_trajectory
def generate_synthetic_observation_trajectory(self, length, initial_Pi=None): """Generate a synthetic realization of observables. Parameters ---------- length : int Length of synthetic state trajectory to be generated. initial_Pi : np.array of shape (nstates,), optional, default=None The initial probability distribution, if samples are not to be taken from equilibrium. Returns ------- o_t : np.array of shape (nstates,) of dtype=np.float32 The trajectory of observations. s_t : np.array of shape (nstates,) of dtype=np.int32 The trajectory of hidden states, with each element in range(0,nstates). Examples -------- Generate a synthetic observation trajectory for an equilibrium realization. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> [o_t, s_t] = model.generate_synthetic_observation_trajectory(length=100) Use an initial nonequilibrium distribution. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> [o_t, s_t] = model.generate_synthetic_observation_trajectory(length=100, initial_Pi=np.array([1,0,0])) """ # 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]
python
def generate_synthetic_observation_trajectory(self, length, initial_Pi=None): """Generate a synthetic realization of observables. Parameters ---------- length : int Length of synthetic state trajectory to be generated. initial_Pi : np.array of shape (nstates,), optional, default=None The initial probability distribution, if samples are not to be taken from equilibrium. Returns ------- o_t : np.array of shape (nstates,) of dtype=np.float32 The trajectory of observations. s_t : np.array of shape (nstates,) of dtype=np.int32 The trajectory of hidden states, with each element in range(0,nstates). Examples -------- Generate a synthetic observation trajectory for an equilibrium realization. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> [o_t, s_t] = model.generate_synthetic_observation_trajectory(length=100) Use an initial nonequilibrium distribution. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> [o_t, s_t] = model.generate_synthetic_observation_trajectory(length=100, initial_Pi=np.array([1,0,0])) """ # 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]
[ "def", "generate_synthetic_observation_trajectory", "(", "self", ",", "length", ",", "initial_Pi", "=", "None", ")", ":", "# 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", "]" ]
Generate a synthetic realization of observables. Parameters ---------- length : int Length of synthetic state trajectory to be generated. initial_Pi : np.array of shape (nstates,), optional, default=None The initial probability distribution, if samples are not to be taken from equilibrium. Returns ------- o_t : np.array of shape (nstates,) of dtype=np.float32 The trajectory of observations. s_t : np.array of shape (nstates,) of dtype=np.int32 The trajectory of hidden states, with each element in range(0,nstates). Examples -------- Generate a synthetic observation trajectory for an equilibrium realization. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> [o_t, s_t] = model.generate_synthetic_observation_trajectory(length=100) Use an initial nonequilibrium distribution. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> [o_t, s_t] = model.generate_synthetic_observation_trajectory(length=100, initial_Pi=np.array([1,0,0]))
[ "Generate", "a", "synthetic", "realization", "of", "observables", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L506-L545
bhmm/bhmm
bhmm/hmm/generic_hmm.py
HMM.generate_synthetic_observation_trajectories
def generate_synthetic_observation_trajectories(self, ntrajectories, length, initial_Pi=None): """Generate a number of synthetic realization of observables from this model. Parameters ---------- ntrajectories : int The number of trajectories to be generated. length : int Length of synthetic state trajectory to be generated. initial_Pi : np.array of shape (nstates,), optional, default=None The initial probability distribution, if samples are not to be taken from equilibrium. Returns ------- O : list of np.array of shape (nstates,) of dtype=np.float32 The trajectories of observations S : list of np.array of shape (nstates,) of dtype=np.int32 The trajectories of hidden states Examples -------- Generate a number of synthetic trajectories. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> O, S = model.generate_synthetic_observation_trajectories(ntrajectories=10, length=100) Use an initial nonequilibrium distribution. >>> from bhmm import testsystems >>> model = testsystems.dalton_model(nstates=3) >>> O, S = model.generate_synthetic_observation_trajectories(ntrajectories=10, length=100, initial_Pi=np.array([1,0,0])) """ 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
python
def generate_synthetic_observation_trajectories(self, ntrajectories, length, initial_Pi=None): """Generate a number of synthetic realization of observables from this model. Parameters ---------- ntrajectories : int The number of trajectories to be generated. length : int Length of synthetic state trajectory to be generated. initial_Pi : np.array of shape (nstates,), optional, default=None The initial probability distribution, if samples are not to be taken from equilibrium. Returns ------- O : list of np.array of shape (nstates,) of dtype=np.float32 The trajectories of observations S : list of np.array of shape (nstates,) of dtype=np.int32 The trajectories of hidden states Examples -------- Generate a number of synthetic trajectories. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> O, S = model.generate_synthetic_observation_trajectories(ntrajectories=10, length=100) Use an initial nonequilibrium distribution. >>> from bhmm import testsystems >>> model = testsystems.dalton_model(nstates=3) >>> O, S = model.generate_synthetic_observation_trajectories(ntrajectories=10, length=100, initial_Pi=np.array([1,0,0])) """ 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
[ "def", "generate_synthetic_observation_trajectories", "(", "self", ",", "ntrajectories", ",", "length", ",", "initial_Pi", "=", "None", ")", ":", "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" ]
Generate a number of synthetic realization of observables from this model. Parameters ---------- ntrajectories : int The number of trajectories to be generated. length : int Length of synthetic state trajectory to be generated. initial_Pi : np.array of shape (nstates,), optional, default=None The initial probability distribution, if samples are not to be taken from equilibrium. Returns ------- O : list of np.array of shape (nstates,) of dtype=np.float32 The trajectories of observations S : list of np.array of shape (nstates,) of dtype=np.int32 The trajectories of hidden states Examples -------- Generate a number of synthetic trajectories. >>> from bhmm import testsystems >>> model = testsystems.dalton_model() >>> O, S = model.generate_synthetic_observation_trajectories(ntrajectories=10, length=100) Use an initial nonequilibrium distribution. >>> from bhmm import testsystems >>> model = testsystems.dalton_model(nstates=3) >>> O, S = model.generate_synthetic_observation_trajectories(ntrajectories=10, length=100, initial_Pi=np.array([1,0,0]))
[ "Generate", "a", "number", "of", "synthetic", "realization", "of", "observables", "from", "this", "model", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L547-L589
bhmm/bhmm
docs/sphinxext/notebook_sphinxext.py
nb_to_python
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
python
def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
[ "def", "nb_to_python", "(", "nb_path", ")", ":", "exporter", "=", "python", ".", "PythonExporter", "(", ")", "output", ",", "resources", "=", "exporter", ".", "from_filename", "(", "nb_path", ")", "return", "output" ]
convert notebook to python script
[ "convert", "notebook", "to", "python", "script" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/docs/sphinxext/notebook_sphinxext.py#L107-L111
bhmm/bhmm
docs/sphinxext/notebook_sphinxext.py
nb_to_html
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 scoped="scoped"') header = header.replace('body {\n overflow: visible;\n padding: 8px;\n}\n', '') # Filter out styles that conflict with the sphinx theme. filter_strings = [ 'navbar', 'body{', 'alert{', 'uneditable-input{', 'collapse{', ] filter_strings.extend(['h%s{' % (i+1) for i in range(6)]) header_lines = filter( lambda x: not any([s in x for s in filter_strings]), header.split('\n')) header = '\n'.join(header_lines) # concatenate raw html lines lines = ['<div class="ipynotebook">'] lines.append(header) lines.append(body) lines.append('</div>') return '\n'.join(lines)
python
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 scoped="scoped"') header = header.replace('body {\n overflow: visible;\n padding: 8px;\n}\n', '') # Filter out styles that conflict with the sphinx theme. filter_strings = [ 'navbar', 'body{', 'alert{', 'uneditable-input{', 'collapse{', ] filter_strings.extend(['h%s{' % (i+1) for i in range(6)]) header_lines = filter( lambda x: not any([s in x for s in filter_strings]), header.split('\n')) header = '\n'.join(header_lines) # concatenate raw html lines lines = ['<div class="ipynotebook">'] lines.append(header) lines.append(body) lines.append('</div>') return '\n'.join(lines)
[ "def", "nb_to_html", "(", "nb_path", ")", ":", "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 scoped=\"scoped\"'", ")", "header", "=", "header", ".", "replace", "(", "'body {\\n overflow: visible;\\n padding: 8px;\\n}\\n'", ",", "''", ")", "# Filter out styles that conflict with the sphinx theme.", "filter_strings", "=", "[", "'navbar'", ",", "'body{'", ",", "'alert{'", ",", "'uneditable-input{'", ",", "'collapse{'", ",", "]", "filter_strings", ".", "extend", "(", "[", "'h%s{'", "%", "(", "i", "+", "1", ")", "for", "i", "in", "range", "(", "6", ")", "]", ")", "header_lines", "=", "filter", "(", "lambda", "x", ":", "not", "any", "(", "[", "s", "in", "x", "for", "s", "in", "filter_strings", "]", ")", ",", "header", ".", "split", "(", "'\\n'", ")", ")", "header", "=", "'\\n'", ".", "join", "(", "header_lines", ")", "# concatenate raw html lines", "lines", "=", "[", "'<div class=\"ipynotebook\">'", "]", "lines", ".", "append", "(", "header", ")", "lines", ".", "append", "(", "body", ")", "lines", ".", "append", "(", "'</div>'", ")", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
convert notebook to html
[ "convert", "notebook", "to", "html" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/docs/sphinxext/notebook_sphinxext.py#L113-L143
bhmm/bhmm
bhmm/output_models/discrete.py
DiscreteOutputModel.p_obs
def p_obs(self, obs, out=None): """ Returns the output probabilities for an entire trajectory and all hidden states Parameters ---------- obs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the probability of generating the symbol at time point t from any of the N hidden states """ if out is None: out = self._output_probabilities[:, obs].T # out /= np.sum(out, axis=1)[:,None] return self._handle_outliers(out) else: if obs.shape[0] == out.shape[0]: np.copyto(out, self._output_probabilities[:, obs].T) elif obs.shape[0] < out.shape[0]: out[:obs.shape[0], :] = self._output_probabilities[:, obs].T else: raise ValueError('output array out is too small: '+str(out.shape[0])+' < '+str(obs.shape[0])) # out /= np.sum(out, axis=1)[:,None] return self._handle_outliers(out)
python
def p_obs(self, obs, out=None): """ Returns the output probabilities for an entire trajectory and all hidden states Parameters ---------- obs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the probability of generating the symbol at time point t from any of the N hidden states """ if out is None: out = self._output_probabilities[:, obs].T # out /= np.sum(out, axis=1)[:,None] return self._handle_outliers(out) else: if obs.shape[0] == out.shape[0]: np.copyto(out, self._output_probabilities[:, obs].T) elif obs.shape[0] < out.shape[0]: out[:obs.shape[0], :] = self._output_probabilities[:, obs].T else: raise ValueError('output array out is too small: '+str(out.shape[0])+' < '+str(obs.shape[0])) # out /= np.sum(out, axis=1)[:,None] return self._handle_outliers(out)
[ "def", "p_obs", "(", "self", ",", "obs", ",", "out", "=", "None", ")", ":", "if", "out", "is", "None", ":", "out", "=", "self", ".", "_output_probabilities", "[", ":", ",", "obs", "]", ".", "T", "# out /= np.sum(out, axis=1)[:,None]", "return", "self", ".", "_handle_outliers", "(", "out", ")", "else", ":", "if", "obs", ".", "shape", "[", "0", "]", "==", "out", ".", "shape", "[", "0", "]", ":", "np", ".", "copyto", "(", "out", ",", "self", ".", "_output_probabilities", "[", ":", ",", "obs", "]", ".", "T", ")", "elif", "obs", ".", "shape", "[", "0", "]", "<", "out", ".", "shape", "[", "0", "]", ":", "out", "[", ":", "obs", ".", "shape", "[", "0", "]", ",", ":", "]", "=", "self", ".", "_output_probabilities", "[", ":", ",", "obs", "]", ".", "T", "else", ":", "raise", "ValueError", "(", "'output array out is too small: '", "+", "str", "(", "out", ".", "shape", "[", "0", "]", ")", "+", "' < '", "+", "str", "(", "obs", ".", "shape", "[", "0", "]", ")", ")", "# out /= np.sum(out, axis=1)[:,None]", "return", "self", ".", "_handle_outliers", "(", "out", ")" ]
Returns the output probabilities for an entire trajectory and all hidden states Parameters ---------- obs : ndarray((T), dtype=int) a discrete trajectory of length T Return ------ p_o : ndarray (T,N) the probability of generating the symbol at time point t from any of the N hidden states
[ "Returns", "the", "output", "probabilities", "for", "an", "entire", "trajectory", "and", "all", "hidden", "states" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L130-L157
bhmm/bhmm
bhmm/output_models/discrete.py
DiscreteOutputModel.estimate
def estimate(self, observations, weights): """ Maximum likelihood estimation of output model given the observations and weights Parameters ---------- observations : [ ndarray(T_k) ] with K elements A list of K observation trajectories, each having length T_k weights : [ ndarray(T_k, N) ] with K elements A list of K weight matrices, each having length T_k and containing the probability of any of the states in the given time step Examples -------- Generate an observation model and samples from each state. >>> import numpy as np >>> ntrajectories = 3 >>> nobs = 1000 >>> B = np.array([[0.5,0.5],[0.1,0.9]]) >>> output_model = DiscreteOutputModel(B) >>> from scipy import stats >>> nobs = 1000 >>> obs = np.empty(nobs, dtype = object) >>> weights = np.empty(nobs, dtype = object) >>> gens = [stats.rv_discrete(values=(range(len(B[i])), B[i])) for i in range(B.shape[0])] >>> obs = [gens[i].rvs(size=nobs) for i in range(B.shape[0])] >>> weights = [np.zeros((nobs, B.shape[1])) for i in range(B.shape[0])] >>> for i in range(B.shape[0]): weights[i][:, i] = 1.0 Update the observation model parameters my a maximum-likelihood fit. >>> output_model.estimate(obs, weights) """ # 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 range(K): dc.update_pout(observations[k], weights[k], self._output_probabilities, dtype=config.dtype) elif self.__impl__ == self.__IMPL_PYTHON__: for k in range(K): for o in range(M): times = np.where(observations[k] == o)[0] self._output_probabilities[:, o] += np.sum(weights[k][times, :], axis=0) else: raise RuntimeError('Implementation '+str(self.__impl__)+' not available') # normalize self._output_probabilities /= np.sum(self._output_probabilities, axis=1)[:, None]
python
def estimate(self, observations, weights): """ Maximum likelihood estimation of output model given the observations and weights Parameters ---------- observations : [ ndarray(T_k) ] with K elements A list of K observation trajectories, each having length T_k weights : [ ndarray(T_k, N) ] with K elements A list of K weight matrices, each having length T_k and containing the probability of any of the states in the given time step Examples -------- Generate an observation model and samples from each state. >>> import numpy as np >>> ntrajectories = 3 >>> nobs = 1000 >>> B = np.array([[0.5,0.5],[0.1,0.9]]) >>> output_model = DiscreteOutputModel(B) >>> from scipy import stats >>> nobs = 1000 >>> obs = np.empty(nobs, dtype = object) >>> weights = np.empty(nobs, dtype = object) >>> gens = [stats.rv_discrete(values=(range(len(B[i])), B[i])) for i in range(B.shape[0])] >>> obs = [gens[i].rvs(size=nobs) for i in range(B.shape[0])] >>> weights = [np.zeros((nobs, B.shape[1])) for i in range(B.shape[0])] >>> for i in range(B.shape[0]): weights[i][:, i] = 1.0 Update the observation model parameters my a maximum-likelihood fit. >>> output_model.estimate(obs, weights) """ # 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 range(K): dc.update_pout(observations[k], weights[k], self._output_probabilities, dtype=config.dtype) elif self.__impl__ == self.__IMPL_PYTHON__: for k in range(K): for o in range(M): times = np.where(observations[k] == o)[0] self._output_probabilities[:, o] += np.sum(weights[k][times, :], axis=0) else: raise RuntimeError('Implementation '+str(self.__impl__)+' not available') # normalize self._output_probabilities /= np.sum(self._output_probabilities, axis=1)[:, None]
[ "def", "estimate", "(", "self", ",", "observations", ",", "weights", ")", ":", "# 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", "range", "(", "K", ")", ":", "dc", ".", "update_pout", "(", "observations", "[", "k", "]", ",", "weights", "[", "k", "]", ",", "self", ".", "_output_probabilities", ",", "dtype", "=", "config", ".", "dtype", ")", "elif", "self", ".", "__impl__", "==", "self", ".", "__IMPL_PYTHON__", ":", "for", "k", "in", "range", "(", "K", ")", ":", "for", "o", "in", "range", "(", "M", ")", ":", "times", "=", "np", ".", "where", "(", "observations", "[", "k", "]", "==", "o", ")", "[", "0", "]", "self", ".", "_output_probabilities", "[", ":", ",", "o", "]", "+=", "np", ".", "sum", "(", "weights", "[", "k", "]", "[", "times", ",", ":", "]", ",", "axis", "=", "0", ")", "else", ":", "raise", "RuntimeError", "(", "'Implementation '", "+", "str", "(", "self", ".", "__impl__", ")", "+", "' not available'", ")", "# normalize", "self", ".", "_output_probabilities", "/=", "np", ".", "sum", "(", "self", ".", "_output_probabilities", ",", "axis", "=", "1", ")", "[", ":", ",", "None", "]" ]
Maximum likelihood estimation of output model given the observations and weights Parameters ---------- observations : [ ndarray(T_k) ] with K elements A list of K observation trajectories, each having length T_k weights : [ ndarray(T_k, N) ] with K elements A list of K weight matrices, each having length T_k and containing the probability of any of the states in the given time step Examples -------- Generate an observation model and samples from each state. >>> import numpy as np >>> ntrajectories = 3 >>> nobs = 1000 >>> B = np.array([[0.5,0.5],[0.1,0.9]]) >>> output_model = DiscreteOutputModel(B) >>> from scipy import stats >>> nobs = 1000 >>> obs = np.empty(nobs, dtype = object) >>> weights = np.empty(nobs, dtype = object) >>> gens = [stats.rv_discrete(values=(range(len(B[i])), B[i])) for i in range(B.shape[0])] >>> obs = [gens[i].rvs(size=nobs) for i in range(B.shape[0])] >>> weights = [np.zeros((nobs, B.shape[1])) for i in range(B.shape[0])] >>> for i in range(B.shape[0]): weights[i][:, i] = 1.0 Update the observation model parameters my a maximum-likelihood fit. >>> output_model.estimate(obs, weights)
[ "Maximum", "likelihood", "estimation", "of", "output", "model", "given", "the", "observations", "and", "weights" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L159-L215
bhmm/bhmm
bhmm/output_models/discrete.py
DiscreteOutputModel.sample
def sample(self, observations_by_state): """ Sample a new set of distribution parameters given a sample of observations from the given state. The internal parameters are updated. Parameters ---------- observations : [ numpy.array with shape (N_k,) ] with nstates elements observations[k] are all observations associated with hidden state k Examples -------- initialize output model >>> B = np.array([[0.5, 0.5], [0.1, 0.9]]) >>> output_model = DiscreteOutputModel(B) sample given observation >>> obs = [[0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1]] >>> output_model.sample(obs) """ from numpy.random import dirichlet N, M = self._output_probabilities.shape # nstates, nsymbols for i, obs_by_state in enumerate(observations_by_state): # count symbols found in data count = np.bincount(obs_by_state, minlength=M).astype(float) # sample dirichlet distribution count += self.prior[i] positive = count > 0 # if counts at all: can't sample, so leave output probabilities as they are. self._output_probabilities[i, positive] = dirichlet(count[positive])
python
def sample(self, observations_by_state): """ Sample a new set of distribution parameters given a sample of observations from the given state. The internal parameters are updated. Parameters ---------- observations : [ numpy.array with shape (N_k,) ] with nstates elements observations[k] are all observations associated with hidden state k Examples -------- initialize output model >>> B = np.array([[0.5, 0.5], [0.1, 0.9]]) >>> output_model = DiscreteOutputModel(B) sample given observation >>> obs = [[0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1]] >>> output_model.sample(obs) """ from numpy.random import dirichlet N, M = self._output_probabilities.shape # nstates, nsymbols for i, obs_by_state in enumerate(observations_by_state): # count symbols found in data count = np.bincount(obs_by_state, minlength=M).astype(float) # sample dirichlet distribution count += self.prior[i] positive = count > 0 # if counts at all: can't sample, so leave output probabilities as they are. self._output_probabilities[i, positive] = dirichlet(count[positive])
[ "def", "sample", "(", "self", ",", "observations_by_state", ")", ":", "from", "numpy", ".", "random", "import", "dirichlet", "N", ",", "M", "=", "self", ".", "_output_probabilities", ".", "shape", "# nstates, nsymbols", "for", "i", ",", "obs_by_state", "in", "enumerate", "(", "observations_by_state", ")", ":", "# count symbols found in data", "count", "=", "np", ".", "bincount", "(", "obs_by_state", ",", "minlength", "=", "M", ")", ".", "astype", "(", "float", ")", "# sample dirichlet distribution", "count", "+=", "self", ".", "prior", "[", "i", "]", "positive", "=", "count", ">", "0", "# if counts at all: can't sample, so leave output probabilities as they are.", "self", ".", "_output_probabilities", "[", "i", ",", "positive", "]", "=", "dirichlet", "(", "count", "[", "positive", "]", ")" ]
Sample a new set of distribution parameters given a sample of observations from the given state. The internal parameters are updated. Parameters ---------- observations : [ numpy.array with shape (N_k,) ] with nstates elements observations[k] are all observations associated with hidden state k Examples -------- initialize output model >>> B = np.array([[0.5, 0.5], [0.1, 0.9]]) >>> output_model = DiscreteOutputModel(B) sample given observation >>> obs = [[0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1]] >>> output_model.sample(obs)
[ "Sample", "a", "new", "set", "of", "distribution", "parameters", "given", "a", "sample", "of", "observations", "from", "the", "given", "state", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L217-L251
bhmm/bhmm
bhmm/output_models/discrete.py
DiscreteOutputModel.generate_observation_from_state
def generate_observation_from_state(self, state_index): """ Generate a single synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. Returns ------- observation : float A single observation from the given state. Examples -------- Generate an observation model. >>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]])) Generate sample from each state. >>> observation = output_model.generate_observation_from_state(0) """ # generate random generator (note that this is inefficient - better use one of the next functions import scipy.stats gen = scipy.stats.rv_discrete(values=(range(len(self._output_probabilities[state_index])), self._output_probabilities[state_index])) gen.rvs(size=1)
python
def generate_observation_from_state(self, state_index): """ Generate a single synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. Returns ------- observation : float A single observation from the given state. Examples -------- Generate an observation model. >>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]])) Generate sample from each state. >>> observation = output_model.generate_observation_from_state(0) """ # generate random generator (note that this is inefficient - better use one of the next functions import scipy.stats gen = scipy.stats.rv_discrete(values=(range(len(self._output_probabilities[state_index])), self._output_probabilities[state_index])) gen.rvs(size=1)
[ "def", "generate_observation_from_state", "(", "self", ",", "state_index", ")", ":", "# generate random generator (note that this is inefficient - better use one of the next functions", "import", "scipy", ".", "stats", "gen", "=", "scipy", ".", "stats", ".", "rv_discrete", "(", "values", "=", "(", "range", "(", "len", "(", "self", ".", "_output_probabilities", "[", "state_index", "]", ")", ")", ",", "self", ".", "_output_probabilities", "[", "state_index", "]", ")", ")", "gen", ".", "rvs", "(", "size", "=", "1", ")" ]
Generate a single synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. Returns ------- observation : float A single observation from the given state. Examples -------- Generate an observation model. >>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]])) Generate sample from each state. >>> observation = output_model.generate_observation_from_state(0)
[ "Generate", "a", "single", "synthetic", "observation", "data", "from", "a", "given", "state", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L253-L283
bhmm/bhmm
bhmm/output_models/discrete.py
DiscreteOutputModel.generate_observations_from_state
def generate_observations_from_state(self, state_index, nobs): """ Generate synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. nobs : int The number of observations to generate. Returns ------- observations : numpy.array of shape(nobs,) with type dtype A sample of `nobs` observations from the specified state. Examples -------- Generate an observation model. >>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]])) Generate sample from each state. >>> observations = [output_model.generate_observations_from_state(state_index, nobs=100) for state_index in range(output_model.nstates)] """ import scipy.stats gen = scipy.stats.rv_discrete(values=(range(self._nsymbols), self._output_probabilities[state_index])) gen.rvs(size=nobs)
python
def generate_observations_from_state(self, state_index, nobs): """ Generate synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. nobs : int The number of observations to generate. Returns ------- observations : numpy.array of shape(nobs,) with type dtype A sample of `nobs` observations from the specified state. Examples -------- Generate an observation model. >>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]])) Generate sample from each state. >>> observations = [output_model.generate_observations_from_state(state_index, nobs=100) for state_index in range(output_model.nstates)] """ import scipy.stats gen = scipy.stats.rv_discrete(values=(range(self._nsymbols), self._output_probabilities[state_index])) gen.rvs(size=nobs)
[ "def", "generate_observations_from_state", "(", "self", ",", "state_index", ",", "nobs", ")", ":", "import", "scipy", ".", "stats", "gen", "=", "scipy", ".", "stats", ".", "rv_discrete", "(", "values", "=", "(", "range", "(", "self", ".", "_nsymbols", ")", ",", "self", ".", "_output_probabilities", "[", "state_index", "]", ")", ")", "gen", ".", "rvs", "(", "size", "=", "nobs", ")" ]
Generate synthetic observation data from a given state. Parameters ---------- state_index : int Index of the state from which observations are to be generated. nobs : int The number of observations to generate. Returns ------- observations : numpy.array of shape(nobs,) with type dtype A sample of `nobs` observations from the specified state. Examples -------- Generate an observation model. >>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]])) Generate sample from each state. >>> observations = [output_model.generate_observations_from_state(state_index, nobs=100) for state_index in range(output_model.nstates)]
[ "Generate", "synthetic", "observation", "data", "from", "a", "given", "state", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L285-L315
bhmm/bhmm
bhmm/output_models/discrete.py
DiscreteOutputModel.generate_observation_trajectory
def generate_observation_trajectory(self, s_t, dtype=None): """ Generate synthetic observation data from a given state sequence. Parameters ---------- s_t : numpy.array with shape (T,) of int type s_t[t] is the hidden state sampled at time t Returns ------- o_t : numpy.array with shape (T,) of type dtype o_t[t] is the observation associated with state s_t[t] dtype : numpy.dtype, optional, default=None The datatype to return the resulting observations in. If None, will select int32. Examples -------- Generate an observation model and synthetic state trajectory. >>> nobs = 1000 >>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]])) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) Generate a synthetic trajectory >>> o_t = output_model.generate_observation_trajectory(s_t) """ if dtype is None: dtype = np.int32 # Determine number of samples to generate. T = s_t.shape[0] nsymbols = self._output_probabilities.shape[1] if (s_t.max() >= self.nstates) or (s_t.min() < 0): msg = '' msg += 's_t = %s\n' % s_t msg += 's_t.min() = %d, s_t.max() = %d\n' % (s_t.min(), s_t.max()) msg += 's_t.argmax = %d\n' % s_t.argmax() msg += 'self.nstates = %d\n' % self.nstates msg += 's_t is out of bounds.\n' raise Exception(msg) # generate random generators # import scipy.stats # gens = [scipy.stats.rv_discrete(values=(range(len(self.B[state_index])), self.B[state_index])) # for state_index in range(self.B.shape[0])] # o_t = np.zeros([T], dtype=dtype) # for t in range(T): # s = s_t[t] # o_t[t] = gens[s].rvs(size=1) # return o_t o_t = np.zeros([T], dtype=dtype) for t in range(T): s = s_t[t] o_t[t] = np.random.choice(nsymbols, p=self._output_probabilities[s, :]) return o_t
python
def generate_observation_trajectory(self, s_t, dtype=None): """ Generate synthetic observation data from a given state sequence. Parameters ---------- s_t : numpy.array with shape (T,) of int type s_t[t] is the hidden state sampled at time t Returns ------- o_t : numpy.array with shape (T,) of type dtype o_t[t] is the observation associated with state s_t[t] dtype : numpy.dtype, optional, default=None The datatype to return the resulting observations in. If None, will select int32. Examples -------- Generate an observation model and synthetic state trajectory. >>> nobs = 1000 >>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]])) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) Generate a synthetic trajectory >>> o_t = output_model.generate_observation_trajectory(s_t) """ if dtype is None: dtype = np.int32 # Determine number of samples to generate. T = s_t.shape[0] nsymbols = self._output_probabilities.shape[1] if (s_t.max() >= self.nstates) or (s_t.min() < 0): msg = '' msg += 's_t = %s\n' % s_t msg += 's_t.min() = %d, s_t.max() = %d\n' % (s_t.min(), s_t.max()) msg += 's_t.argmax = %d\n' % s_t.argmax() msg += 'self.nstates = %d\n' % self.nstates msg += 's_t is out of bounds.\n' raise Exception(msg) # generate random generators # import scipy.stats # gens = [scipy.stats.rv_discrete(values=(range(len(self.B[state_index])), self.B[state_index])) # for state_index in range(self.B.shape[0])] # o_t = np.zeros([T], dtype=dtype) # for t in range(T): # s = s_t[t] # o_t[t] = gens[s].rvs(size=1) # return o_t o_t = np.zeros([T], dtype=dtype) for t in range(T): s = s_t[t] o_t[t] = np.random.choice(nsymbols, p=self._output_probabilities[s, :]) return o_t
[ "def", "generate_observation_trajectory", "(", "self", ",", "s_t", ",", "dtype", "=", "None", ")", ":", "if", "dtype", "is", "None", ":", "dtype", "=", "np", ".", "int32", "# Determine number of samples to generate.", "T", "=", "s_t", ".", "shape", "[", "0", "]", "nsymbols", "=", "self", ".", "_output_probabilities", ".", "shape", "[", "1", "]", "if", "(", "s_t", ".", "max", "(", ")", ">=", "self", ".", "nstates", ")", "or", "(", "s_t", ".", "min", "(", ")", "<", "0", ")", ":", "msg", "=", "''", "msg", "+=", "'s_t = %s\\n'", "%", "s_t", "msg", "+=", "'s_t.min() = %d, s_t.max() = %d\\n'", "%", "(", "s_t", ".", "min", "(", ")", ",", "s_t", ".", "max", "(", ")", ")", "msg", "+=", "'s_t.argmax = %d\\n'", "%", "s_t", ".", "argmax", "(", ")", "msg", "+=", "'self.nstates = %d\\n'", "%", "self", ".", "nstates", "msg", "+=", "'s_t is out of bounds.\\n'", "raise", "Exception", "(", "msg", ")", "# generate random generators", "# import scipy.stats", "# gens = [scipy.stats.rv_discrete(values=(range(len(self.B[state_index])), self.B[state_index]))", "# for state_index in range(self.B.shape[0])]", "# o_t = np.zeros([T], dtype=dtype)", "# for t in range(T):", "# s = s_t[t]", "# o_t[t] = gens[s].rvs(size=1)", "# return o_t", "o_t", "=", "np", ".", "zeros", "(", "[", "T", "]", ",", "dtype", "=", "dtype", ")", "for", "t", "in", "range", "(", "T", ")", ":", "s", "=", "s_t", "[", "t", "]", "o_t", "[", "t", "]", "=", "np", ".", "random", ".", "choice", "(", "nsymbols", ",", "p", "=", "self", ".", "_output_probabilities", "[", "s", ",", ":", "]", ")", "return", "o_t" ]
Generate synthetic observation data from a given state sequence. Parameters ---------- s_t : numpy.array with shape (T,) of int type s_t[t] is the hidden state sampled at time t Returns ------- o_t : numpy.array with shape (T,) of type dtype o_t[t] is the observation associated with state s_t[t] dtype : numpy.dtype, optional, default=None The datatype to return the resulting observations in. If None, will select int32. Examples -------- Generate an observation model and synthetic state trajectory. >>> nobs = 1000 >>> output_model = DiscreteOutputModel(np.array([[0.5,0.5],[0.1,0.9]])) >>> s_t = np.random.randint(0, output_model.nstates, size=[nobs]) Generate a synthetic trajectory >>> o_t = output_model.generate_observation_trajectory(s_t)
[ "Generate", "synthetic", "observation", "data", "from", "a", "given", "state", "sequence", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L317-L378
bhmm/bhmm
bhmm/hidden/api.py
set_implementation
def set_implementation(impl): """ Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"] """ global __impl__ if impl.lower() == 'python': __impl__ = __IMPL_PYTHON__ elif impl.lower() == 'c': __impl__ = __IMPL_C__ else: import warnings warnings.warn('Implementation '+impl+' is not known. Using the fallback python implementation.') __impl__ = __IMPL_PYTHON__
python
def set_implementation(impl): """ Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"] """ global __impl__ if impl.lower() == 'python': __impl__ = __IMPL_PYTHON__ elif impl.lower() == 'c': __impl__ = __IMPL_C__ else: import warnings warnings.warn('Implementation '+impl+' is not known. Using the fallback python implementation.') __impl__ = __IMPL_PYTHON__
[ "def", "set_implementation", "(", "impl", ")", ":", "global", "__impl__", "if", "impl", ".", "lower", "(", ")", "==", "'python'", ":", "__impl__", "=", "__IMPL_PYTHON__", "elif", "impl", ".", "lower", "(", ")", "==", "'c'", ":", "__impl__", "=", "__IMPL_C__", "else", ":", "import", "warnings", "warnings", ".", "warn", "(", "'Implementation '", "+", "impl", "+", "' is not known. Using the fallback python implementation.'", ")", "__impl__", "=", "__IMPL_PYTHON__" ]
Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"]
[ "Sets", "the", "implementation", "of", "this", "module" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L44-L62
bhmm/bhmm
bhmm/hidden/api.py
forward
def forward(A, pobs, pi, T=None, alpha_out=None): """Compute P( obs | A, B, pi ) and all forward coefficients. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states T : int, optional, default = None trajectory length. If not given, T = pobs.shape[0] will be used. alpha_out : ndarray((T,N), dtype = float), optional, default = None containter for the alpha result variables. If None, a new container will be created. Returns ------- logprob : float The probability to observe the sequence `ob` with the model given by `A`, `B` and `pi`. alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. These can be used in many different algorithms related to HMMs. """ if __impl__ == __IMPL_PYTHON__: return ip.forward(A, pobs, pi, T=T, alpha_out=alpha_out, dtype=config.dtype) elif __impl__ == __IMPL_C__: return ic.forward(A, pobs, pi, T=T, alpha_out=alpha_out, dtype=config.dtype) else: raise RuntimeError('Nonexisting implementation selected: '+str(__impl__))
python
def forward(A, pobs, pi, T=None, alpha_out=None): """Compute P( obs | A, B, pi ) and all forward coefficients. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states T : int, optional, default = None trajectory length. If not given, T = pobs.shape[0] will be used. alpha_out : ndarray((T,N), dtype = float), optional, default = None containter for the alpha result variables. If None, a new container will be created. Returns ------- logprob : float The probability to observe the sequence `ob` with the model given by `A`, `B` and `pi`. alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. These can be used in many different algorithms related to HMMs. """ if __impl__ == __IMPL_PYTHON__: return ip.forward(A, pobs, pi, T=T, alpha_out=alpha_out, dtype=config.dtype) elif __impl__ == __IMPL_C__: return ic.forward(A, pobs, pi, T=T, alpha_out=alpha_out, dtype=config.dtype) else: raise RuntimeError('Nonexisting implementation selected: '+str(__impl__))
[ "def", "forward", "(", "A", ",", "pobs", ",", "pi", ",", "T", "=", "None", ",", "alpha_out", "=", "None", ")", ":", "if", "__impl__", "==", "__IMPL_PYTHON__", ":", "return", "ip", ".", "forward", "(", "A", ",", "pobs", ",", "pi", ",", "T", "=", "T", ",", "alpha_out", "=", "alpha_out", ",", "dtype", "=", "config", ".", "dtype", ")", "elif", "__impl__", "==", "__IMPL_C__", ":", "return", "ic", ".", "forward", "(", "A", ",", "pobs", ",", "pi", ",", "T", "=", "T", ",", "alpha_out", "=", "alpha_out", ",", "dtype", "=", "config", ".", "dtype", ")", "else", ":", "raise", "RuntimeError", "(", "'Nonexisting implementation selected: '", "+", "str", "(", "__impl__", ")", ")" ]
Compute P( obs | A, B, pi ) and all forward coefficients. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states T : int, optional, default = None trajectory length. If not given, T = pobs.shape[0] will be used. alpha_out : ndarray((T,N), dtype = float), optional, default = None containter for the alpha result variables. If None, a new container will be created. Returns ------- logprob : float The probability to observe the sequence `ob` with the model given by `A`, `B` and `pi`. alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. These can be used in many different algorithms related to HMMs.
[ "Compute", "P", "(", "obs", "|", "A", "B", "pi", ")", "and", "all", "forward", "coefficients", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L65-L96
bhmm/bhmm
bhmm/hidden/api.py
backward
def backward(A, pobs, T=None, beta_out=None): """Compute all backward coefficients. With scaling! Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int, optional, default = None trajectory length. If not given, T = pobs.shape[0] will be used. beta_out : ndarray((T,N), dtype = float), optional, default = None containter for the beta result variables. If None, a new container will be created. Returns ------- beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith backward coefficient of time t. These can be used in many different algorithms related to HMMs. """ if __impl__ == __IMPL_PYTHON__: return ip.backward(A, pobs, T=T, beta_out=beta_out, dtype=config.dtype) elif __impl__ == __IMPL_C__: return ic.backward(A, pobs, T=T, beta_out=beta_out, dtype=config.dtype) else: raise RuntimeError('Nonexisting implementation selected: '+str(__impl__))
python
def backward(A, pobs, T=None, beta_out=None): """Compute all backward coefficients. With scaling! Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int, optional, default = None trajectory length. If not given, T = pobs.shape[0] will be used. beta_out : ndarray((T,N), dtype = float), optional, default = None containter for the beta result variables. If None, a new container will be created. Returns ------- beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith backward coefficient of time t. These can be used in many different algorithms related to HMMs. """ if __impl__ == __IMPL_PYTHON__: return ip.backward(A, pobs, T=T, beta_out=beta_out, dtype=config.dtype) elif __impl__ == __IMPL_C__: return ic.backward(A, pobs, T=T, beta_out=beta_out, dtype=config.dtype) else: raise RuntimeError('Nonexisting implementation selected: '+str(__impl__))
[ "def", "backward", "(", "A", ",", "pobs", ",", "T", "=", "None", ",", "beta_out", "=", "None", ")", ":", "if", "__impl__", "==", "__IMPL_PYTHON__", ":", "return", "ip", ".", "backward", "(", "A", ",", "pobs", ",", "T", "=", "T", ",", "beta_out", "=", "beta_out", ",", "dtype", "=", "config", ".", "dtype", ")", "elif", "__impl__", "==", "__IMPL_C__", ":", "return", "ic", ".", "backward", "(", "A", ",", "pobs", ",", "T", "=", "T", ",", "beta_out", "=", "beta_out", ",", "dtype", "=", "config", ".", "dtype", ")", "else", ":", "raise", "RuntimeError", "(", "'Nonexisting implementation selected: '", "+", "str", "(", "__impl__", ")", ")" ]
Compute all backward coefficients. With scaling! Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int, optional, default = None trajectory length. If not given, T = pobs.shape[0] will be used. beta_out : ndarray((T,N), dtype = float), optional, default = None containter for the beta result variables. If None, a new container will be created. Returns ------- beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith backward coefficient of time t. These can be used in many different algorithms related to HMMs.
[ "Compute", "all", "backward", "coefficients", ".", "With", "scaling!" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L99-L125
bhmm/bhmm
bhmm/hidden/api.py
state_probabilities
def state_probabilities(alpha, beta, T=None, gamma_out=None): """ Calculate the (T,N)-probabilty matrix for being in state i at time t. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. T : int, optional, default = None trajectory length. If not given, gamma_out.shape[0] will be used. If gamma_out is neither given, T = alpha.shape[0] will be used. gamma_out : ndarray((T,N), dtype = float), optional, default = None containter for the gamma result variables. If None, a new container will be created. Returns ------- gamma : ndarray((T,N), dtype = float), optional, default = None gamma[t,i] is the probabilty at time t to be in state i ! See Also -------- forward : to calculate `alpha` backward : to calculate `beta` """ # get summation helper - we use matrix multiplication with 1's because it's faster than the np.sum function (yes!) global ones_size if ones_size != alpha.shape[1]: global ones ones = np.ones(alpha.shape[1])[:, None] ones_size = alpha.shape[1] # if alpha.shape[0] != beta.shape[0]: raise ValueError('Inconsistent sizes of alpha and beta.') # determine T to use if T is None: if gamma_out is None: T = alpha.shape[0] else: T = gamma_out.shape[0] # compute if gamma_out is None: gamma_out = alpha * beta if T < gamma_out.shape[0]: gamma_out = gamma_out[:T] else: if gamma_out.shape[0] < alpha.shape[0]: np.multiply(alpha[:T], beta[:T], gamma_out) else: np.multiply(alpha, beta, gamma_out) # normalize np.divide(gamma_out, np.dot(gamma_out, ones), out=gamma_out) # done return gamma_out
python
def state_probabilities(alpha, beta, T=None, gamma_out=None): """ Calculate the (T,N)-probabilty matrix for being in state i at time t. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. T : int, optional, default = None trajectory length. If not given, gamma_out.shape[0] will be used. If gamma_out is neither given, T = alpha.shape[0] will be used. gamma_out : ndarray((T,N), dtype = float), optional, default = None containter for the gamma result variables. If None, a new container will be created. Returns ------- gamma : ndarray((T,N), dtype = float), optional, default = None gamma[t,i] is the probabilty at time t to be in state i ! See Also -------- forward : to calculate `alpha` backward : to calculate `beta` """ # get summation helper - we use matrix multiplication with 1's because it's faster than the np.sum function (yes!) global ones_size if ones_size != alpha.shape[1]: global ones ones = np.ones(alpha.shape[1])[:, None] ones_size = alpha.shape[1] # if alpha.shape[0] != beta.shape[0]: raise ValueError('Inconsistent sizes of alpha and beta.') # determine T to use if T is None: if gamma_out is None: T = alpha.shape[0] else: T = gamma_out.shape[0] # compute if gamma_out is None: gamma_out = alpha * beta if T < gamma_out.shape[0]: gamma_out = gamma_out[:T] else: if gamma_out.shape[0] < alpha.shape[0]: np.multiply(alpha[:T], beta[:T], gamma_out) else: np.multiply(alpha, beta, gamma_out) # normalize np.divide(gamma_out, np.dot(gamma_out, ones), out=gamma_out) # done return gamma_out
[ "def", "state_probabilities", "(", "alpha", ",", "beta", ",", "T", "=", "None", ",", "gamma_out", "=", "None", ")", ":", "# get summation helper - we use matrix multiplication with 1's because it's faster than the np.sum function (yes!)", "global", "ones_size", "if", "ones_size", "!=", "alpha", ".", "shape", "[", "1", "]", ":", "global", "ones", "ones", "=", "np", ".", "ones", "(", "alpha", ".", "shape", "[", "1", "]", ")", "[", ":", ",", "None", "]", "ones_size", "=", "alpha", ".", "shape", "[", "1", "]", "#", "if", "alpha", ".", "shape", "[", "0", "]", "!=", "beta", ".", "shape", "[", "0", "]", ":", "raise", "ValueError", "(", "'Inconsistent sizes of alpha and beta.'", ")", "# determine T to use", "if", "T", "is", "None", ":", "if", "gamma_out", "is", "None", ":", "T", "=", "alpha", ".", "shape", "[", "0", "]", "else", ":", "T", "=", "gamma_out", ".", "shape", "[", "0", "]", "# compute", "if", "gamma_out", "is", "None", ":", "gamma_out", "=", "alpha", "*", "beta", "if", "T", "<", "gamma_out", ".", "shape", "[", "0", "]", ":", "gamma_out", "=", "gamma_out", "[", ":", "T", "]", "else", ":", "if", "gamma_out", ".", "shape", "[", "0", "]", "<", "alpha", ".", "shape", "[", "0", "]", ":", "np", ".", "multiply", "(", "alpha", "[", ":", "T", "]", ",", "beta", "[", ":", "T", "]", ",", "gamma_out", ")", "else", ":", "np", ".", "multiply", "(", "alpha", ",", "beta", ",", "gamma_out", ")", "# normalize", "np", ".", "divide", "(", "gamma_out", ",", "np", ".", "dot", "(", "gamma_out", ",", "ones", ")", ",", "out", "=", "gamma_out", ")", "# done", "return", "gamma_out" ]
Calculate the (T,N)-probabilty matrix for being in state i at time t. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. T : int, optional, default = None trajectory length. If not given, gamma_out.shape[0] will be used. If gamma_out is neither given, T = alpha.shape[0] will be used. gamma_out : ndarray((T,N), dtype = float), optional, default = None containter for the gamma result variables. If None, a new container will be created. Returns ------- gamma : ndarray((T,N), dtype = float), optional, default = None gamma[t,i] is the probabilty at time t to be in state i ! See Also -------- forward : to calculate `alpha` backward : to calculate `beta`
[ "Calculate", "the", "(", "T", "N", ")", "-", "probabilty", "matrix", "for", "being", "in", "state", "i", "at", "time", "t", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L133-L188
bhmm/bhmm
bhmm/hidden/api.py
state_counts
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 = None gamma[t,i] is the probabilty at time t to be in state i ! T : int number of time steps Returns ------- count : numpy.array shape (N) count[i] is the summed probabilty to be in state i ! See Also -------- state_probabilities : to calculate `gamma` """ return np.sum(gamma[0:T], axis=0, out=out)
python
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 = None gamma[t,i] is the probabilty at time t to be in state i ! T : int number of time steps Returns ------- count : numpy.array shape (N) count[i] is the summed probabilty to be in state i ! See Also -------- state_probabilities : to calculate `gamma` """ return np.sum(gamma[0:T], axis=0, out=out)
[ "def", "state_counts", "(", "gamma", ",", "T", ",", "out", "=", "None", ")", ":", "return", "np", ".", "sum", "(", "gamma", "[", "0", ":", "T", "]", ",", "axis", "=", "0", ",", "out", "=", "out", ")" ]
Sum the probabilities of being in state i to time t Parameters ---------- gamma : ndarray((T,N), dtype = float), optional, default = None gamma[t,i] is the probabilty at time t to be in state i ! T : int number of time steps Returns ------- count : numpy.array shape (N) count[i] is the summed probabilty to be in state i ! See Also -------- state_probabilities : to calculate `gamma`
[ "Sum", "the", "probabilities", "of", "being", "in", "state", "i", "to", "time", "t" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L191-L211
bhmm/bhmm
bhmm/hidden/api.py
transition_counts
def transition_counts(alpha, beta, A, pobs, T=None, out=None): """ Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int number of time steps out : ndarray((N,N), dtype = float), optional, default = None containter for the resulting count matrix. If None, a new matrix will be created. Returns ------- counts : numpy.array shape (N, N) counts[i, j] is the summed probability to transition from i to j in time [0,T) See Also -------- forward : calculate forward coefficients `alpha` backward : calculate backward coefficients `beta` """ if __impl__ == __IMPL_PYTHON__: return ip.transition_counts(alpha, beta, A, pobs, T=T, out=out, dtype=config.dtype) elif __impl__ == __IMPL_C__: return ic.transition_counts(alpha, beta, A, pobs, T=T, out=out, dtype=config.dtype) else: raise RuntimeError('Nonexisting implementation selected: '+str(__impl__))
python
def transition_counts(alpha, beta, A, pobs, T=None, out=None): """ Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int number of time steps out : ndarray((N,N), dtype = float), optional, default = None containter for the resulting count matrix. If None, a new matrix will be created. Returns ------- counts : numpy.array shape (N, N) counts[i, j] is the summed probability to transition from i to j in time [0,T) See Also -------- forward : calculate forward coefficients `alpha` backward : calculate backward coefficients `beta` """ if __impl__ == __IMPL_PYTHON__: return ip.transition_counts(alpha, beta, A, pobs, T=T, out=out, dtype=config.dtype) elif __impl__ == __IMPL_C__: return ic.transition_counts(alpha, beta, A, pobs, T=T, out=out, dtype=config.dtype) else: raise RuntimeError('Nonexisting implementation selected: '+str(__impl__))
[ "def", "transition_counts", "(", "alpha", ",", "beta", ",", "A", ",", "pobs", ",", "T", "=", "None", ",", "out", "=", "None", ")", ":", "if", "__impl__", "==", "__IMPL_PYTHON__", ":", "return", "ip", ".", "transition_counts", "(", "alpha", ",", "beta", ",", "A", ",", "pobs", ",", "T", "=", "T", ",", "out", "=", "out", ",", "dtype", "=", "config", ".", "dtype", ")", "elif", "__impl__", "==", "__IMPL_C__", ":", "return", "ic", ".", "transition_counts", "(", "alpha", ",", "beta", ",", "A", ",", "pobs", ",", "T", "=", "T", ",", "out", "=", "out", ",", "dtype", "=", "config", ".", "dtype", ")", "else", ":", "raise", "RuntimeError", "(", "'Nonexisting implementation selected: '", "+", "str", "(", "__impl__", ")", ")" ]
Sum for all t the probability to transition from state i to state j. Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. beta : ndarray((T,N), dtype = float), optional, default = None beta[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int number of time steps out : ndarray((N,N), dtype = float), optional, default = None containter for the resulting count matrix. If None, a new matrix will be created. Returns ------- counts : numpy.array shape (N, N) counts[i, j] is the summed probability to transition from i to j in time [0,T) See Also -------- forward : calculate forward coefficients `alpha` backward : calculate backward coefficients `beta`
[ "Sum", "for", "all", "t", "the", "probability", "to", "transition", "from", "state", "i", "to", "state", "j", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L214-L248
bhmm/bhmm
bhmm/hidden/api.py
viterbi
def viterbi(A, pobs, pi): """ Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states Returns ------- q : numpy.array shape (T) maximum likelihood hidden path """ if __impl__ == __IMPL_PYTHON__: return ip.viterbi(A, pobs, pi, dtype=config.dtype) elif __impl__ == __IMPL_C__: return ic.viterbi(A, pobs, pi, dtype=config.dtype) else: raise RuntimeError('Nonexisting implementation selected: '+str(__impl__))
python
def viterbi(A, pobs, pi): """ Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states Returns ------- q : numpy.array shape (T) maximum likelihood hidden path """ if __impl__ == __IMPL_PYTHON__: return ip.viterbi(A, pobs, pi, dtype=config.dtype) elif __impl__ == __IMPL_C__: return ic.viterbi(A, pobs, pi, dtype=config.dtype) else: raise RuntimeError('Nonexisting implementation selected: '+str(__impl__))
[ "def", "viterbi", "(", "A", ",", "pobs", ",", "pi", ")", ":", "if", "__impl__", "==", "__IMPL_PYTHON__", ":", "return", "ip", ".", "viterbi", "(", "A", ",", "pobs", ",", "pi", ",", "dtype", "=", "config", ".", "dtype", ")", "elif", "__impl__", "==", "__IMPL_C__", ":", "return", "ic", ".", "viterbi", "(", "A", ",", "pobs", ",", "pi", ",", "dtype", "=", "config", ".", "dtype", ")", "else", ":", "raise", "RuntimeError", "(", "'Nonexisting implementation selected: '", "+", "str", "(", "__impl__", ")", ")" ]
Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm. Parameters ---------- A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i pi : ndarray((N), dtype = float) initial distribution of hidden states Returns ------- q : numpy.array shape (T) maximum likelihood hidden path
[ "Estimate", "the", "hidden", "pathway", "of", "maximum", "likelihood", "using", "the", "Viterbi", "algorithm", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L251-L274
bhmm/bhmm
bhmm/hidden/api.py
sample_path
def sample_path(alpha, A, pobs, T=None): """ Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations ) Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int number of time steps Returns ------- S : numpy.array shape (T) maximum likelihood hidden path """ if __impl__ == __IMPL_PYTHON__: return ip.sample_path(alpha, A, pobs, T=T, dtype=config.dtype) elif __impl__ == __IMPL_C__: return ic.sample_path(alpha, A, pobs, T=T, dtype=config.dtype) else: raise RuntimeError('Nonexisting implementation selected: '+str(__impl__))
python
def sample_path(alpha, A, pobs, T=None): """ Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations ) Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int number of time steps Returns ------- S : numpy.array shape (T) maximum likelihood hidden path """ if __impl__ == __IMPL_PYTHON__: return ip.sample_path(alpha, A, pobs, T=T, dtype=config.dtype) elif __impl__ == __IMPL_C__: return ic.sample_path(alpha, A, pobs, T=T, dtype=config.dtype) else: raise RuntimeError('Nonexisting implementation selected: '+str(__impl__))
[ "def", "sample_path", "(", "alpha", ",", "A", ",", "pobs", ",", "T", "=", "None", ")", ":", "if", "__impl__", "==", "__IMPL_PYTHON__", ":", "return", "ip", ".", "sample_path", "(", "alpha", ",", "A", ",", "pobs", ",", "T", "=", "T", ",", "dtype", "=", "config", ".", "dtype", ")", "elif", "__impl__", "==", "__IMPL_C__", ":", "return", "ic", ".", "sample_path", "(", "alpha", ",", "A", ",", "pobs", ",", "T", "=", "T", ",", "dtype", "=", "config", ".", "dtype", ")", "else", ":", "raise", "RuntimeError", "(", "'Nonexisting implementation selected: '", "+", "str", "(", "__impl__", ")", ")" ]
Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations ) Parameters ---------- alpha : ndarray((T,N), dtype = float), optional, default = None alpha[t,i] is the ith forward coefficient of time t. A : ndarray((N,N), dtype = float) transition matrix of the hidden states pobs : ndarray((T,N), dtype = float) pobs[t,i] is the observation probability for observation at time t given hidden state i T : int number of time steps Returns ------- S : numpy.array shape (T) maximum likelihood hidden path
[ "Sample", "the", "hidden", "pathway", "S", "from", "the", "conditional", "distribution", "P", "(", "S", "|", "Parameters", "Observations", ")" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L277-L302
bhmm/bhmm
bhmm/util/logger.py
logger
def logger(name='BHMM', pattern='%(asctime)s %(levelname)s %(name)s: %(message)s', date_format='%H:%M:%S', handler=logging.StreamHandler(sys.stdout)): """ Retrieves the logger instance associated to the given name. :param name: The name of the logger instance. :type name: str :param pattern: The associated pattern. :type pattern: str :param date_format: The date format to be used in the pattern. :type date_format: str :param handler: The logging handler, by default console output. :type handler: FileHandler or StreamHandler or NullHandler :return: The logger. :rtype: Logger """ _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 = False return _logger
python
def logger(name='BHMM', pattern='%(asctime)s %(levelname)s %(name)s: %(message)s', date_format='%H:%M:%S', handler=logging.StreamHandler(sys.stdout)): """ Retrieves the logger instance associated to the given name. :param name: The name of the logger instance. :type name: str :param pattern: The associated pattern. :type pattern: str :param date_format: The date format to be used in the pattern. :type date_format: str :param handler: The logging handler, by default console output. :type handler: FileHandler or StreamHandler or NullHandler :return: The logger. :rtype: Logger """ _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 = False return _logger
[ "def", "logger", "(", "name", "=", "'BHMM'", ",", "pattern", "=", "'%(asctime)s %(levelname)s %(name)s: %(message)s'", ",", "date_format", "=", "'%H:%M:%S'", ",", "handler", "=", "logging", ".", "StreamHandler", "(", "sys", ".", "stdout", ")", ")", ":", "_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", "=", "False", "return", "_logger" ]
Retrieves the logger instance associated to the given name. :param name: The name of the logger instance. :type name: str :param pattern: The associated pattern. :type pattern: str :param date_format: The date format to be used in the pattern. :type date_format: str :param handler: The logging handler, by default console output. :type handler: FileHandler or StreamHandler or NullHandler :return: The logger. :rtype: Logger
[ "Retrieves", "the", "logger", "instance", "associated", "to", "the", "given", "name", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/logger.py#L25-L50
bhmm/bhmm
bhmm/estimators/bayesian_sampling.py
BayesianHMMSampler.sample
def sample(self, nsamples, nburn=0, nthin=1, save_hidden_state_trajectory=False, call_back=None): """Sample from the BHMM posterior. Parameters ---------- nsamples : int The number of samples to generate. nburn : int, optional, default=0 The number of samples to discard to burn-in, following which `nsamples` will be generated. nthin : int, optional, default=1 The number of Gibbs sampling updates used to generate each returned sample. save_hidden_state_trajectory : bool, optional, default=False If True, the hidden state trajectory for each sample will be saved as well. call_back : function, optional, default=None a call back function with no arguments, which if given is being called after each computed sample. This is useful for implementing progress bars. Returns ------- models : list of bhmm.HMM The sampled HMM models from the Bayesian posterior. Examples -------- >>> from bhmm import testsystems >>> [model, observations, states, sampled_model] = testsystems.generate_random_bhmm(ntrajectories=5, length=1000) >>> nburn = 5 # run the sampler a bit before recording samples >>> nsamples = 10 # generate 10 samples >>> nthin = 2 # discard one sample in between each recorded sample >>> samples = sampled_model.sample(nsamples, nburn=nburn, nthin=nthin) """ # 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, nsamples)) # Run a number of Gibbs sampling updates to generate each sample. for thin in range(nthin): self._update() # Save a copy of the current model. model_copy = copy.deepcopy(self.model) # print "Sampled: \n",repr(model_copy) if not save_hidden_state_trajectory: model_copy.hidden_state_trajectory = None models.append(model_copy) if call_back is not None: call_back() # Return the list of models saved. return models
python
def sample(self, nsamples, nburn=0, nthin=1, save_hidden_state_trajectory=False, call_back=None): """Sample from the BHMM posterior. Parameters ---------- nsamples : int The number of samples to generate. nburn : int, optional, default=0 The number of samples to discard to burn-in, following which `nsamples` will be generated. nthin : int, optional, default=1 The number of Gibbs sampling updates used to generate each returned sample. save_hidden_state_trajectory : bool, optional, default=False If True, the hidden state trajectory for each sample will be saved as well. call_back : function, optional, default=None a call back function with no arguments, which if given is being called after each computed sample. This is useful for implementing progress bars. Returns ------- models : list of bhmm.HMM The sampled HMM models from the Bayesian posterior. Examples -------- >>> from bhmm import testsystems >>> [model, observations, states, sampled_model] = testsystems.generate_random_bhmm(ntrajectories=5, length=1000) >>> nburn = 5 # run the sampler a bit before recording samples >>> nsamples = 10 # generate 10 samples >>> nthin = 2 # discard one sample in between each recorded sample >>> samples = sampled_model.sample(nsamples, nburn=nburn, nthin=nthin) """ # 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, nsamples)) # Run a number of Gibbs sampling updates to generate each sample. for thin in range(nthin): self._update() # Save a copy of the current model. model_copy = copy.deepcopy(self.model) # print "Sampled: \n",repr(model_copy) if not save_hidden_state_trajectory: model_copy.hidden_state_trajectory = None models.append(model_copy) if call_back is not None: call_back() # Return the list of models saved. return models
[ "def", "sample", "(", "self", ",", "nsamples", ",", "nburn", "=", "0", ",", "nthin", "=", "1", ",", "save_hidden_state_trajectory", "=", "False", ",", "call_back", "=", "None", ")", ":", "# 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", ",", "nsamples", ")", ")", "# Run a number of Gibbs sampling updates to generate each sample.", "for", "thin", "in", "range", "(", "nthin", ")", ":", "self", ".", "_update", "(", ")", "# Save a copy of the current model.", "model_copy", "=", "copy", ".", "deepcopy", "(", "self", ".", "model", ")", "# print \"Sampled: \\n\",repr(model_copy)", "if", "not", "save_hidden_state_trajectory", ":", "model_copy", ".", "hidden_state_trajectory", "=", "None", "models", ".", "append", "(", "model_copy", ")", "if", "call_back", "is", "not", "None", ":", "call_back", "(", ")", "# Return the list of models saved.", "return", "models" ]
Sample from the BHMM posterior. Parameters ---------- nsamples : int The number of samples to generate. nburn : int, optional, default=0 The number of samples to discard to burn-in, following which `nsamples` will be generated. nthin : int, optional, default=1 The number of Gibbs sampling updates used to generate each returned sample. save_hidden_state_trajectory : bool, optional, default=False If True, the hidden state trajectory for each sample will be saved as well. call_back : function, optional, default=None a call back function with no arguments, which if given is being called after each computed sample. This is useful for implementing progress bars. Returns ------- models : list of bhmm.HMM The sampled HMM models from the Bayesian posterior. Examples -------- >>> from bhmm import testsystems >>> [model, observations, states, sampled_model] = testsystems.generate_random_bhmm(ntrajectories=5, length=1000) >>> nburn = 5 # run the sampler a bit before recording samples >>> nsamples = 10 # generate 10 samples >>> nthin = 2 # discard one sample in between each recorded sample >>> samples = sampled_model.sample(nsamples, nburn=nburn, nthin=nthin)
[ "Sample", "from", "the", "BHMM", "posterior", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L206-L263
bhmm/bhmm
bhmm/estimators/bayesian_sampling.py
BayesianHMMSampler._update
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_time)
python
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_time)
[ "def", "_update", "(", "self", ")", ":", "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_time", ")" ]
Update the current model using one round of Gibbs sampling.
[ "Update", "the", "current", "model", "using", "one", "round", "of", "Gibbs", "sampling", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L265-L277
bhmm/bhmm
bhmm/estimators/bayesian_sampling.py
BayesianHMMSampler._updateHiddenStateTrajectories
def _updateHiddenStateTrajectories(self): """Sample a new set of state trajectories from the conditional distribution P(S | T, E, O) """ self.model.hidden_state_trajectories = list() for trajectory_index in range(self.nobs): hidden_state_trajectory = self._sampleHiddenStateTrajectory(self.observations[trajectory_index]) self.model.hidden_state_trajectories.append(hidden_state_trajectory) return
python
def _updateHiddenStateTrajectories(self): """Sample a new set of state trajectories from the conditional distribution P(S | T, E, O) """ self.model.hidden_state_trajectories = list() for trajectory_index in range(self.nobs): hidden_state_trajectory = self._sampleHiddenStateTrajectory(self.observations[trajectory_index]) self.model.hidden_state_trajectories.append(hidden_state_trajectory) return
[ "def", "_updateHiddenStateTrajectories", "(", "self", ")", ":", "self", ".", "model", ".", "hidden_state_trajectories", "=", "list", "(", ")", "for", "trajectory_index", "in", "range", "(", "self", ".", "nobs", ")", ":", "hidden_state_trajectory", "=", "self", ".", "_sampleHiddenStateTrajectory", "(", "self", ".", "observations", "[", "trajectory_index", "]", ")", "self", ".", "model", ".", "hidden_state_trajectories", ".", "append", "(", "hidden_state_trajectory", ")", "return" ]
Sample a new set of state trajectories from the conditional distribution P(S | T, E, O)
[ "Sample", "a", "new", "set", "of", "state", "trajectories", "from", "the", "conditional", "distribution", "P", "(", "S", "|", "T", "E", "O", ")" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L279-L287
bhmm/bhmm
bhmm/estimators/bayesian_sampling.py
BayesianHMMSampler._sampleHiddenStateTrajectory
def _sampleHiddenStateTrajectory(self, obs, dtype=np.int32): """Sample a hidden state trajectory from the conditional distribution P(s | T, E, o) Parameters ---------- o_t : numpy.array with dimensions (T,) observation[n] is the nth observation dtype : numpy.dtype, optional, default=numpy.int32 The dtype to to use for returned state trajectory. Returns ------- s_t : numpy.array with dimensions (T,) of type `dtype` Hidden state trajectory, with s_t[t] the hidden state corresponding to observation o_t[t] Examples -------- >>> import bhmm >>> [model, observations, states, sampled_model] = bhmm.testsystems.generate_random_bhmm(ntrajectories=5, length=1000) >>> o_t = observations[0] >>> s_t = sampled_model._sampleHiddenStateTrajectory(o_t) """ # Determine observation trajectory length T = obs.shape[0] # Convenience access. A = self.model.transition_matrix pi = self.model.initial_distribution # compute output probability matrix self.model.output_model.p_obs(obs, out=self.pobs) # compute forward variables logprob = hidden.forward(A, self.pobs, pi, T=T, alpha_out=self.alpha)[0] # sample path S = hidden.sample_path(self.alpha, A, self.pobs, T=T) return S
python
def _sampleHiddenStateTrajectory(self, obs, dtype=np.int32): """Sample a hidden state trajectory from the conditional distribution P(s | T, E, o) Parameters ---------- o_t : numpy.array with dimensions (T,) observation[n] is the nth observation dtype : numpy.dtype, optional, default=numpy.int32 The dtype to to use for returned state trajectory. Returns ------- s_t : numpy.array with dimensions (T,) of type `dtype` Hidden state trajectory, with s_t[t] the hidden state corresponding to observation o_t[t] Examples -------- >>> import bhmm >>> [model, observations, states, sampled_model] = bhmm.testsystems.generate_random_bhmm(ntrajectories=5, length=1000) >>> o_t = observations[0] >>> s_t = sampled_model._sampleHiddenStateTrajectory(o_t) """ # Determine observation trajectory length T = obs.shape[0] # Convenience access. A = self.model.transition_matrix pi = self.model.initial_distribution # compute output probability matrix self.model.output_model.p_obs(obs, out=self.pobs) # compute forward variables logprob = hidden.forward(A, self.pobs, pi, T=T, alpha_out=self.alpha)[0] # sample path S = hidden.sample_path(self.alpha, A, self.pobs, T=T) return S
[ "def", "_sampleHiddenStateTrajectory", "(", "self", ",", "obs", ",", "dtype", "=", "np", ".", "int32", ")", ":", "# Determine observation trajectory length", "T", "=", "obs", ".", "shape", "[", "0", "]", "# Convenience access.", "A", "=", "self", ".", "model", ".", "transition_matrix", "pi", "=", "self", ".", "model", ".", "initial_distribution", "# compute output probability matrix", "self", ".", "model", ".", "output_model", ".", "p_obs", "(", "obs", ",", "out", "=", "self", ".", "pobs", ")", "# compute forward variables", "logprob", "=", "hidden", ".", "forward", "(", "A", ",", "self", ".", "pobs", ",", "pi", ",", "T", "=", "T", ",", "alpha_out", "=", "self", ".", "alpha", ")", "[", "0", "]", "# sample path", "S", "=", "hidden", ".", "sample_path", "(", "self", ".", "alpha", ",", "A", ",", "self", ".", "pobs", ",", "T", "=", "T", ")", "return", "S" ]
Sample a hidden state trajectory from the conditional distribution P(s | T, E, o) Parameters ---------- o_t : numpy.array with dimensions (T,) observation[n] is the nth observation dtype : numpy.dtype, optional, default=numpy.int32 The dtype to to use for returned state trajectory. Returns ------- s_t : numpy.array with dimensions (T,) of type `dtype` Hidden state trajectory, with s_t[t] the hidden state corresponding to observation o_t[t] Examples -------- >>> import bhmm >>> [model, observations, states, sampled_model] = bhmm.testsystems.generate_random_bhmm(ntrajectories=5, length=1000) >>> o_t = observations[0] >>> s_t = sampled_model._sampleHiddenStateTrajectory(o_t)
[ "Sample", "a", "hidden", "state", "trajectory", "from", "the", "conditional", "distribution", "P", "(", "s", "|", "T", "E", "o", ")" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L289-L327
bhmm/bhmm
bhmm/estimators/bayesian_sampling.py
BayesianHMMSampler._updateEmissionProbabilities
def _updateEmissionProbabilities(self): """Sample a new set of emission probabilites from the conditional distribution P(E | S, O) """ observations_by_state = [self.model.collect_observations_in_state(self.observations, state) for state in range(self.model.nstates)] self.model.output_model.sample(observations_by_state)
python
def _updateEmissionProbabilities(self): """Sample a new set of emission probabilites from the conditional distribution P(E | S, O) """ observations_by_state = [self.model.collect_observations_in_state(self.observations, state) for state in range(self.model.nstates)] self.model.output_model.sample(observations_by_state)
[ "def", "_updateEmissionProbabilities", "(", "self", ")", ":", "observations_by_state", "=", "[", "self", ".", "model", ".", "collect_observations_in_state", "(", "self", ".", "observations", ",", "state", ")", "for", "state", "in", "range", "(", "self", ".", "model", ".", "nstates", ")", "]", "self", ".", "model", ".", "output_model", ".", "sample", "(", "observations_by_state", ")" ]
Sample a new set of emission probabilites from the conditional distribution P(E | S, O)
[ "Sample", "a", "new", "set", "of", "emission", "probabilites", "from", "the", "conditional", "distribution", "P", "(", "E", "|", "S", "O", ")" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L329-L335
bhmm/bhmm
bhmm/estimators/bayesian_sampling.py
BayesianHMMSampler._updateTransitionMatrix
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 with sampling option reversible:\n ' + str(C) + '\nUse prior to ensure connectivity or use reversible=False.') # ensure consistent sparsity pattern (P0 might have additional zeros because of underflows) # TODO: these steps work around a bug in msmtools. Should be fixed there P0 = msmest.transition_matrix(C, reversible=self.reversible, maxiter=10000, warn_not_converged=False) zeros = np.where(P0 + P0.T == 0) C[zeros] = 0 # run sampler Tij = msmest.sample_tmatrix(C, nsample=1, nsteps=self.transition_matrix_sampling_steps, reversible=self.reversible) # INITIAL DISTRIBUTION if self.stationary: # p0 is consistent with P p0 = _tmatrix_disconnected.stationary_distribution(Tij, C=C) else: n0 = self.model.count_init().astype(float) first_timestep_counts_with_prior = n0 + self.prior_n0 positive = first_timestep_counts_with_prior > 0 p0 = np.zeros_like(n0) p0[positive] = np.random.dirichlet(first_timestep_counts_with_prior[positive]) # sample p0 from posterior # update HMM with new sample self.model.update(p0, Tij)
python
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 with sampling option reversible:\n ' + str(C) + '\nUse prior to ensure connectivity or use reversible=False.') # ensure consistent sparsity pattern (P0 might have additional zeros because of underflows) # TODO: these steps work around a bug in msmtools. Should be fixed there P0 = msmest.transition_matrix(C, reversible=self.reversible, maxiter=10000, warn_not_converged=False) zeros = np.where(P0 + P0.T == 0) C[zeros] = 0 # run sampler Tij = msmest.sample_tmatrix(C, nsample=1, nsteps=self.transition_matrix_sampling_steps, reversible=self.reversible) # INITIAL DISTRIBUTION if self.stationary: # p0 is consistent with P p0 = _tmatrix_disconnected.stationary_distribution(Tij, C=C) else: n0 = self.model.count_init().astype(float) first_timestep_counts_with_prior = n0 + self.prior_n0 positive = first_timestep_counts_with_prior > 0 p0 = np.zeros_like(n0) p0[positive] = np.random.dirichlet(first_timestep_counts_with_prior[positive]) # sample p0 from posterior # update HMM with new sample self.model.update(p0, Tij)
[ "def", "_updateTransitionMatrix", "(", "self", ")", ":", "# 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 with sampling option reversible:\\n '", "+", "str", "(", "C", ")", "+", "'\\nUse prior to ensure connectivity or use reversible=False.'", ")", "# ensure consistent sparsity pattern (P0 might have additional zeros because of underflows)", "# TODO: these steps work around a bug in msmtools. Should be fixed there", "P0", "=", "msmest", ".", "transition_matrix", "(", "C", ",", "reversible", "=", "self", ".", "reversible", ",", "maxiter", "=", "10000", ",", "warn_not_converged", "=", "False", ")", "zeros", "=", "np", ".", "where", "(", "P0", "+", "P0", ".", "T", "==", "0", ")", "C", "[", "zeros", "]", "=", "0", "# run sampler", "Tij", "=", "msmest", ".", "sample_tmatrix", "(", "C", ",", "nsample", "=", "1", ",", "nsteps", "=", "self", ".", "transition_matrix_sampling_steps", ",", "reversible", "=", "self", ".", "reversible", ")", "# INITIAL DISTRIBUTION", "if", "self", ".", "stationary", ":", "# p0 is consistent with P", "p0", "=", "_tmatrix_disconnected", ".", "stationary_distribution", "(", "Tij", ",", "C", "=", "C", ")", "else", ":", "n0", "=", "self", ".", "model", ".", "count_init", "(", ")", ".", "astype", "(", "float", ")", "first_timestep_counts_with_prior", "=", "n0", "+", "self", ".", "prior_n0", "positive", "=", "first_timestep_counts_with_prior", ">", "0", "p0", "=", "np", ".", "zeros_like", "(", "n0", ")", "p0", "[", "positive", "]", "=", "np", ".", "random", ".", "dirichlet", "(", "first_timestep_counts_with_prior", "[", "positive", "]", ")", "# sample p0 from posterior", "# update HMM with new sample", "self", ".", "model", ".", "update", "(", "p0", ",", "Tij", ")" ]
Updates the hidden-state transition matrix and the initial distribution
[ "Updates", "the", "hidden", "-", "state", "transition", "matrix", "and", "the", "initial", "distribution" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L337-L369
bhmm/bhmm
bhmm/estimators/bayesian_sampling.py
BayesianHMMSampler._generateInitialModel
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_model_type) model = mlhmm.fit() return model
python
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_model_type) model = mlhmm.fit() return model
[ "def", "_generateInitialModel", "(", "self", ",", "output_model_type", ")", ":", "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_model_type", ")", "model", "=", "mlhmm", ".", "fit", "(", ")", "return", "model" ]
Initialize using an MLHMM.
[ "Initialize", "using", "an", "MLHMM", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L371-L380
bhmm/bhmm
bhmm/util/types.py
ensure_dtraj
def ensure_dtraj(dtraj): r"""Makes sure that dtraj is a discrete trajectory (array of int) """ if is_int_vector(dtraj): return dtraj elif is_list_of_int(dtraj): return np.array(dtraj, dtype=int) else: raise TypeError('Argument dtraj is not a discrete trajectory - only list of integers or int-ndarrays are allowed. Check type.')
python
def ensure_dtraj(dtraj): r"""Makes sure that dtraj is a discrete trajectory (array of int) """ if is_int_vector(dtraj): return dtraj elif is_list_of_int(dtraj): return np.array(dtraj, dtype=int) else: raise TypeError('Argument dtraj is not a discrete trajectory - only list of integers or int-ndarrays are allowed. Check type.')
[ "def", "ensure_dtraj", "(", "dtraj", ")", ":", "if", "is_int_vector", "(", "dtraj", ")", ":", "return", "dtraj", "elif", "is_list_of_int", "(", "dtraj", ")", ":", "return", "np", ".", "array", "(", "dtraj", ",", "dtype", "=", "int", ")", "else", ":", "raise", "TypeError", "(", "'Argument dtraj is not a discrete trajectory - only list of integers or int-ndarrays are allowed. Check type.'", ")" ]
r"""Makes sure that dtraj is a discrete trajectory (array of int)
[ "r", "Makes", "sure", "that", "dtraj", "is", "a", "discrete", "trajectory", "(", "array", "of", "int", ")" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/types.py#L160-L169
bhmm/bhmm
bhmm/util/types.py
ensure_dtraj_list
def ensure_dtraj_list(dtrajs): r"""Makes sure that dtrajs is a list of discrete trajectories (array of int) """ if isinstance(dtrajs, list): # elements are ints? then wrap into a list if is_list_of_int(dtrajs): return [np.array(dtrajs, dtype=int)] else: for i in range(len(dtrajs)): dtrajs[i] = ensure_dtraj(dtrajs[i]) return dtrajs else: return [ensure_dtraj(dtrajs)]
python
def ensure_dtraj_list(dtrajs): r"""Makes sure that dtrajs is a list of discrete trajectories (array of int) """ if isinstance(dtrajs, list): # elements are ints? then wrap into a list if is_list_of_int(dtrajs): return [np.array(dtrajs, dtype=int)] else: for i in range(len(dtrajs)): dtrajs[i] = ensure_dtraj(dtrajs[i]) return dtrajs else: return [ensure_dtraj(dtrajs)]
[ "def", "ensure_dtraj_list", "(", "dtrajs", ")", ":", "if", "isinstance", "(", "dtrajs", ",", "list", ")", ":", "# elements are ints? then wrap into a list", "if", "is_list_of_int", "(", "dtrajs", ")", ":", "return", "[", "np", ".", "array", "(", "dtrajs", ",", "dtype", "=", "int", ")", "]", "else", ":", "for", "i", "in", "range", "(", "len", "(", "dtrajs", ")", ")", ":", "dtrajs", "[", "i", "]", "=", "ensure_dtraj", "(", "dtrajs", "[", "i", "]", ")", "return", "dtrajs", "else", ":", "return", "[", "ensure_dtraj", "(", "dtrajs", ")", "]" ]
r"""Makes sure that dtrajs is a list of discrete trajectories (array of int)
[ "r", "Makes", "sure", "that", "dtrajs", "is", "a", "list", "of", "discrete", "trajectories", "(", "array", "of", "int", ")" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/types.py#L172-L185
bhmm/bhmm
bhmm/estimators/_tmatrix_disconnected.py
connected_sets
def connected_sets(C, mincount_connectivity=0, strong=True): """ Computes the connected sets of C. C : count matrix mincount_connectivity : float Minimum count which counts as a connection. strong : boolean True: Seek strongly connected sets. False: Seek weakly connected sets. """ 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
python
def connected_sets(C, mincount_connectivity=0, strong=True): """ Computes the connected sets of C. C : count matrix mincount_connectivity : float Minimum count which counts as a connection. strong : boolean True: Seek strongly connected sets. False: Seek weakly connected sets. """ 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
[ "def", "connected_sets", "(", "C", ",", "mincount_connectivity", "=", "0", ",", "strong", "=", "True", ")", ":", "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" ]
Computes the connected sets of C. C : count matrix mincount_connectivity : float Minimum count which counts as a connection. strong : boolean True: Seek strongly connected sets. False: Seek weakly connected sets.
[ "Computes", "the", "connected", "sets", "of", "C", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L28-L43
bhmm/bhmm
bhmm/estimators/_tmatrix_disconnected.py
closed_sets
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
python
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
[ "def", "closed_sets", "(", "C", ",", "mincount_connectivity", "=", "0", ")", ":", "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" ]
Computes the strongly connected closed sets of C
[ "Computes", "the", "strongly", "connected", "closed", "sets", "of", "C" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L46-L56
bhmm/bhmm
bhmm/estimators/_tmatrix_disconnected.py
nonempty_set
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]
python
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]
[ "def", "nonempty_set", "(", "C", ",", "mincount_connectivity", "=", "0", ")", ":", "# 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", "]" ]
Returns the set of states that have at least one incoming or outgoing count
[ "Returns", "the", "set", "of", "states", "that", "have", "at", "least", "one", "incoming", "or", "outgoing", "count" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L59-L65
bhmm/bhmm
bhmm/estimators/_tmatrix_disconnected.py
estimate_P
def estimate_P(C, reversible=True, fixed_statdist=None, maxiter=1000000, maxerr=1e-8, mincount_connectivity=0): """ Estimates full transition matrix for general connectivity structure Parameters ---------- C : ndarray count matrix reversible : bool estimate reversible? fixed_statdist : ndarray or None estimate with given stationary distribution maxiter : int Maximum number of reversible iterations. maxerr : float Stopping criterion for reversible iteration: Will stop when infinity norm of difference vector of two subsequent equilibrium distributions is below maxerr. mincount_connectivity : float Minimum count which counts as a connection. """ 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 to unknown eq. dist. - use strongly connected sets. S = connected_sets(C, mincount_connectivity=mincount_connectivity, strong=True) for s in S: mask = np.zeros(n, dtype=bool) mask[s] = True if C[np.ix_(mask, ~mask)].sum() > np.finfo(C.dtype).eps: # outgoing transitions - use partial rev algo. transition_matrix_partial_rev(C, P, mask, maxiter=maxiter, maxerr=maxerr) else: # closed set - use standard estimator I = np.ix_(mask, mask) if s.size > 1: # leave diagonal 1 if single closed state. P[I] = msmest.transition_matrix(C[I], reversible=True, warn_not_converged=False, maxiter=maxiter, maxerr=maxerr) else: # nonreversible or given equilibrium distribution - weakly connected sets S = connected_sets(C, mincount_connectivity=mincount_connectivity, strong=False) for s in S: I = np.ix_(s, s) if not reversible: Csub = C[I] # any zero rows? must set Cii = 1 to avoid dividing by zero zero_rows = np.where(Csub.sum(axis=1) == 0)[0] Csub[zero_rows, zero_rows] = 1.0 P[I] = msmest.transition_matrix(Csub, reversible=False) elif reversible and fixed_statdist is not None: P[I] = msmest.transition_matrix(C[I], reversible=True, fixed_statdist=fixed_statdist, maxiter=maxiter, maxerr=maxerr) else: # unknown case raise NotImplementedError('Transition estimation for the case reversible=' + str(reversible) + ' fixed_statdist=' + str(fixed_statdist is not None) + ' not implemented.') # done return P
python
def estimate_P(C, reversible=True, fixed_statdist=None, maxiter=1000000, maxerr=1e-8, mincount_connectivity=0): """ Estimates full transition matrix for general connectivity structure Parameters ---------- C : ndarray count matrix reversible : bool estimate reversible? fixed_statdist : ndarray or None estimate with given stationary distribution maxiter : int Maximum number of reversible iterations. maxerr : float Stopping criterion for reversible iteration: Will stop when infinity norm of difference vector of two subsequent equilibrium distributions is below maxerr. mincount_connectivity : float Minimum count which counts as a connection. """ 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 to unknown eq. dist. - use strongly connected sets. S = connected_sets(C, mincount_connectivity=mincount_connectivity, strong=True) for s in S: mask = np.zeros(n, dtype=bool) mask[s] = True if C[np.ix_(mask, ~mask)].sum() > np.finfo(C.dtype).eps: # outgoing transitions - use partial rev algo. transition_matrix_partial_rev(C, P, mask, maxiter=maxiter, maxerr=maxerr) else: # closed set - use standard estimator I = np.ix_(mask, mask) if s.size > 1: # leave diagonal 1 if single closed state. P[I] = msmest.transition_matrix(C[I], reversible=True, warn_not_converged=False, maxiter=maxiter, maxerr=maxerr) else: # nonreversible or given equilibrium distribution - weakly connected sets S = connected_sets(C, mincount_connectivity=mincount_connectivity, strong=False) for s in S: I = np.ix_(s, s) if not reversible: Csub = C[I] # any zero rows? must set Cii = 1 to avoid dividing by zero zero_rows = np.where(Csub.sum(axis=1) == 0)[0] Csub[zero_rows, zero_rows] = 1.0 P[I] = msmest.transition_matrix(Csub, reversible=False) elif reversible and fixed_statdist is not None: P[I] = msmest.transition_matrix(C[I], reversible=True, fixed_statdist=fixed_statdist, maxiter=maxiter, maxerr=maxerr) else: # unknown case raise NotImplementedError('Transition estimation for the case reversible=' + str(reversible) + ' fixed_statdist=' + str(fixed_statdist is not None) + ' not implemented.') # done return P
[ "def", "estimate_P", "(", "C", ",", "reversible", "=", "True", ",", "fixed_statdist", "=", "None", ",", "maxiter", "=", "1000000", ",", "maxerr", "=", "1e-8", ",", "mincount_connectivity", "=", "0", ")", ":", "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 to unknown eq. dist. - use strongly connected sets.", "S", "=", "connected_sets", "(", "C", ",", "mincount_connectivity", "=", "mincount_connectivity", ",", "strong", "=", "True", ")", "for", "s", "in", "S", ":", "mask", "=", "np", ".", "zeros", "(", "n", ",", "dtype", "=", "bool", ")", "mask", "[", "s", "]", "=", "True", "if", "C", "[", "np", ".", "ix_", "(", "mask", ",", "~", "mask", ")", "]", ".", "sum", "(", ")", ">", "np", ".", "finfo", "(", "C", ".", "dtype", ")", ".", "eps", ":", "# outgoing transitions - use partial rev algo.", "transition_matrix_partial_rev", "(", "C", ",", "P", ",", "mask", ",", "maxiter", "=", "maxiter", ",", "maxerr", "=", "maxerr", ")", "else", ":", "# closed set - use standard estimator", "I", "=", "np", ".", "ix_", "(", "mask", ",", "mask", ")", "if", "s", ".", "size", ">", "1", ":", "# leave diagonal 1 if single closed state.", "P", "[", "I", "]", "=", "msmest", ".", "transition_matrix", "(", "C", "[", "I", "]", ",", "reversible", "=", "True", ",", "warn_not_converged", "=", "False", ",", "maxiter", "=", "maxiter", ",", "maxerr", "=", "maxerr", ")", "else", ":", "# nonreversible or given equilibrium distribution - weakly connected sets", "S", "=", "connected_sets", "(", "C", ",", "mincount_connectivity", "=", "mincount_connectivity", ",", "strong", "=", "False", ")", "for", "s", "in", "S", ":", "I", "=", "np", ".", "ix_", "(", "s", ",", "s", ")", "if", "not", "reversible", ":", "Csub", "=", "C", "[", "I", "]", "# any zero rows? must set Cii = 1 to avoid dividing by zero", "zero_rows", "=", "np", ".", "where", "(", "Csub", ".", "sum", "(", "axis", "=", "1", ")", "==", "0", ")", "[", "0", "]", "Csub", "[", "zero_rows", ",", "zero_rows", "]", "=", "1.0", "P", "[", "I", "]", "=", "msmest", ".", "transition_matrix", "(", "Csub", ",", "reversible", "=", "False", ")", "elif", "reversible", "and", "fixed_statdist", "is", "not", "None", ":", "P", "[", "I", "]", "=", "msmest", ".", "transition_matrix", "(", "C", "[", "I", "]", ",", "reversible", "=", "True", ",", "fixed_statdist", "=", "fixed_statdist", ",", "maxiter", "=", "maxiter", ",", "maxerr", "=", "maxerr", ")", "else", ":", "# unknown case", "raise", "NotImplementedError", "(", "'Transition estimation for the case reversible='", "+", "str", "(", "reversible", ")", "+", "' fixed_statdist='", "+", "str", "(", "fixed_statdist", "is", "not", "None", ")", "+", "' not implemented.'", ")", "# done", "return", "P" ]
Estimates full transition matrix for general connectivity structure Parameters ---------- C : ndarray count matrix reversible : bool estimate reversible? fixed_statdist : ndarray or None estimate with given stationary distribution maxiter : int Maximum number of reversible iterations. maxerr : float Stopping criterion for reversible iteration: Will stop when infinity norm of difference vector of two subsequent equilibrium distributions is below maxerr. mincount_connectivity : float Minimum count which counts as a connection.
[ "Estimates", "full", "transition", "matrix", "for", "general", "connectivity", "structure" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L68-L123
bhmm/bhmm
bhmm/estimators/_tmatrix_disconnected.py
transition_matrix_partial_rev
def transition_matrix_partial_rev(C, P, S, maxiter=1000000, maxerr=1e-8): """Maximum likelihood estimation of transition matrix which is reversible on parts Partially-reversible estimation of transition matrix. Maximizes the likelihood: .. math: P_S &=& arg max prod_{S, :} (p_ij)^c_ij \\ \Pi_S P_{S,S} &=& \Pi_S P_{S,S} where the product runs over all elements of the rows S, and detailed balance only acts on the block with rows and columns S. :math:`\Pi_S` is the diagonal matrix of equilibrium probabilities restricted to set S. Note that this formulation Parameters ---------- C : ndarray full count matrix P : ndarray full transition matrix to write to. Will overwrite P[S] S : ndarray, bool boolean selection of reversible set with outgoing transitions maxerr : float maximum difference in matrix sums between iterations (infinity norm) in order to stop. """ # 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 # rowsums rowsums = X.sum(axis=1) + Y.sum(axis=1) err = 1.0 it = 0 while err > maxerr and it < maxiter: # update d = countsums / rowsums X = ATA / (d[:, None] + d) Y = B / d[:, None] # normalize X, Y totalsum = X.sum() + Y.sum() X /= totalsum Y /= totalsum # update sums rowsums_new = X.sum(axis=1) + Y.sum(axis=1) # compute error err = np.max(np.abs(rowsums_new - rowsums)) # update rowsums = rowsums_new it += 1 # write to P P[np.ix_(S, S)] = X P[np.ix_(S, ~S)] = Y P[S] /= P[S].sum(axis=1)[:, None]
python
def transition_matrix_partial_rev(C, P, S, maxiter=1000000, maxerr=1e-8): """Maximum likelihood estimation of transition matrix which is reversible on parts Partially-reversible estimation of transition matrix. Maximizes the likelihood: .. math: P_S &=& arg max prod_{S, :} (p_ij)^c_ij \\ \Pi_S P_{S,S} &=& \Pi_S P_{S,S} where the product runs over all elements of the rows S, and detailed balance only acts on the block with rows and columns S. :math:`\Pi_S` is the diagonal matrix of equilibrium probabilities restricted to set S. Note that this formulation Parameters ---------- C : ndarray full count matrix P : ndarray full transition matrix to write to. Will overwrite P[S] S : ndarray, bool boolean selection of reversible set with outgoing transitions maxerr : float maximum difference in matrix sums between iterations (infinity norm) in order to stop. """ # 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 # rowsums rowsums = X.sum(axis=1) + Y.sum(axis=1) err = 1.0 it = 0 while err > maxerr and it < maxiter: # update d = countsums / rowsums X = ATA / (d[:, None] + d) Y = B / d[:, None] # normalize X, Y totalsum = X.sum() + Y.sum() X /= totalsum Y /= totalsum # update sums rowsums_new = X.sum(axis=1) + Y.sum(axis=1) # compute error err = np.max(np.abs(rowsums_new - rowsums)) # update rowsums = rowsums_new it += 1 # write to P P[np.ix_(S, S)] = X P[np.ix_(S, ~S)] = Y P[S] /= P[S].sum(axis=1)[:, None]
[ "def", "transition_matrix_partial_rev", "(", "C", ",", "P", ",", "S", ",", "maxiter", "=", "1000000", ",", "maxerr", "=", "1e-8", ")", ":", "# 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", "# rowsums", "rowsums", "=", "X", ".", "sum", "(", "axis", "=", "1", ")", "+", "Y", ".", "sum", "(", "axis", "=", "1", ")", "err", "=", "1.0", "it", "=", "0", "while", "err", ">", "maxerr", "and", "it", "<", "maxiter", ":", "# update", "d", "=", "countsums", "/", "rowsums", "X", "=", "ATA", "/", "(", "d", "[", ":", ",", "None", "]", "+", "d", ")", "Y", "=", "B", "/", "d", "[", ":", ",", "None", "]", "# normalize X, Y", "totalsum", "=", "X", ".", "sum", "(", ")", "+", "Y", ".", "sum", "(", ")", "X", "/=", "totalsum", "Y", "/=", "totalsum", "# update sums", "rowsums_new", "=", "X", ".", "sum", "(", "axis", "=", "1", ")", "+", "Y", ".", "sum", "(", "axis", "=", "1", ")", "# compute error", "err", "=", "np", ".", "max", "(", "np", ".", "abs", "(", "rowsums_new", "-", "rowsums", ")", ")", "# update", "rowsums", "=", "rowsums_new", "it", "+=", "1", "# write to P", "P", "[", "np", ".", "ix_", "(", "S", ",", "S", ")", "]", "=", "X", "P", "[", "np", ".", "ix_", "(", "S", ",", "~", "S", ")", "]", "=", "Y", "P", "[", "S", "]", "/=", "P", "[", "S", "]", ".", "sum", "(", "axis", "=", "1", ")", "[", ":", ",", "None", "]" ]
Maximum likelihood estimation of transition matrix which is reversible on parts Partially-reversible estimation of transition matrix. Maximizes the likelihood: .. math: P_S &=& arg max prod_{S, :} (p_ij)^c_ij \\ \Pi_S P_{S,S} &=& \Pi_S P_{S,S} where the product runs over all elements of the rows S, and detailed balance only acts on the block with rows and columns S. :math:`\Pi_S` is the diagonal matrix of equilibrium probabilities restricted to set S. Note that this formulation Parameters ---------- C : ndarray full count matrix P : ndarray full transition matrix to write to. Will overwrite P[S] S : ndarray, bool boolean selection of reversible set with outgoing transitions maxerr : float maximum difference in matrix sums between iterations (infinity norm) in order to stop.
[ "Maximum", "likelihood", "estimation", "of", "transition", "matrix", "which", "is", "reversible", "on", "parts" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L126-L190
bhmm/bhmm
bhmm/estimators/_tmatrix_disconnected.py
enforce_reversible_on_closed
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 X_s = pi_s[:, None] * P[I] X_s = 0.5 * (X_s + X_s.T) # normalize Prev[I] = X_s / X_s.sum(axis=1)[:, None] return Prev
python
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 X_s = pi_s[:, None] * P[I] X_s = 0.5 * (X_s + X_s.T) # normalize Prev[I] = X_s / X_s.sum(axis=1)[:, None] return Prev
[ "def", "enforce_reversible_on_closed", "(", "P", ")", ":", "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", "X_s", "=", "pi_s", "[", ":", ",", "None", "]", "*", "P", "[", "I", "]", "X_s", "=", "0.5", "*", "(", "X_s", "+", "X_s", ".", "T", ")", "# normalize", "Prev", "[", "I", "]", "=", "X_s", "/", "X_s", ".", "sum", "(", "axis", "=", "1", ")", "[", ":", ",", "None", "]", "return", "Prev" ]
Enforces transition matrix P to be reversible on its closed sets.
[ "Enforces", "transition", "matrix", "P", "to", "be", "reversible", "on", "its", "closed", "sets", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L193-L209
bhmm/bhmm
bhmm/estimators/_tmatrix_disconnected.py
is_reversible
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_distribution(Ps) X = pi[:, None] * Ps if not np.allclose(X, X.T): return False # survived. return True
python
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_distribution(Ps) X = pi[:, None] * Ps if not np.allclose(X, X.T): return False # survived. return True
[ "def", "is_reversible", "(", "P", ")", ":", "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_distribution", "(", "Ps", ")", "X", "=", "pi", "[", ":", ",", "None", "]", "*", "Ps", "if", "not", "np", ".", "allclose", "(", "X", ",", "X", ".", "T", ")", ":", "return", "False", "# survived.", "return", "True" ]
Returns if P is reversible on its weakly connected sets
[ "Returns", "if", "P", "is", "reversible", "on", "its", "weakly", "connected", "sets" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L212-L226
bhmm/bhmm
bhmm/estimators/_tmatrix_disconnected.py
stationary_distribution
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 ValueError('Computing stationary distribution for disconnected matrix. Need count matrix.') # disconnected sets n = np.shape(C)[0] ctot = np.sum(C) pi = np.zeros(n) # treat each weakly connected set separately sets = connected_sets(C, mincount_connectivity=mincount_connectivity, strong=False) for s in sets: # compute weight w = np.sum(C[s, :]) / ctot pi[s] = w * msmstatdist(P[s, :][:, s]) # reinforce normalization pi /= np.sum(pi) return pi
python
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 ValueError('Computing stationary distribution for disconnected matrix. Need count matrix.') # disconnected sets n = np.shape(C)[0] ctot = np.sum(C) pi = np.zeros(n) # treat each weakly connected set separately sets = connected_sets(C, mincount_connectivity=mincount_connectivity, strong=False) for s in sets: # compute weight w = np.sum(C[s, :]) / ctot pi[s] = w * msmstatdist(P[s, :][:, s]) # reinforce normalization pi /= np.sum(pi) return pi
[ "def", "stationary_distribution", "(", "P", ",", "C", "=", "None", ",", "mincount_connectivity", "=", "0", ")", ":", "# 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", "ValueError", "(", "'Computing stationary distribution for disconnected matrix. Need count matrix.'", ")", "# disconnected sets", "n", "=", "np", ".", "shape", "(", "C", ")", "[", "0", "]", "ctot", "=", "np", ".", "sum", "(", "C", ")", "pi", "=", "np", ".", "zeros", "(", "n", ")", "# treat each weakly connected set separately", "sets", "=", "connected_sets", "(", "C", ",", "mincount_connectivity", "=", "mincount_connectivity", ",", "strong", "=", "False", ")", "for", "s", "in", "sets", ":", "# compute weight", "w", "=", "np", ".", "sum", "(", "C", "[", "s", ",", ":", "]", ")", "/", "ctot", "pi", "[", "s", "]", "=", "w", "*", "msmstatdist", "(", "P", "[", "s", ",", ":", "]", "[", ":", ",", "s", "]", ")", "# reinforce normalization", "pi", "/=", "np", ".", "sum", "(", "pi", ")", "return", "pi" ]
Simple estimator for stationary distribution for multiple strongly connected sets
[ "Simple", "estimator", "for", "stationary", "distribution", "for", "multiple", "strongly", "connected", "sets" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L229-L251
bhmm/bhmm
bhmm/hmm/gaussian_hmm.py
SampledGaussianHMM.means_samples
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
python
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
[ "def", "means_samples", "(", "self", ")", ":", "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" ]
r""" Samples of the Gaussian distribution means
[ "r", "Samples", "of", "the", "Gaussian", "distribution", "means" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/gaussian_hmm.py#L67-L73
bhmm/bhmm
bhmm/hmm/gaussian_hmm.py
SampledGaussianHMM.sigmas_samples
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
python
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
[ "def", "sigmas_samples", "(", "self", ")", ":", "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" ]
r""" Samples of the Gaussian distribution standard deviations
[ "r", "Samples", "of", "the", "Gaussian", "distribution", "standard", "deviations" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/gaussian_hmm.py#L91-L97
bhmm/bhmm
bhmm/api.py
_guess_output_type
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 sense based on observation data. If observations consist of arrays/lists of integer numbers (irrespective of whether the python type is int or float), our guess is 'discrete'. If observations consist of arrays/lists of 1D-floats, our guess is 'discrete'. In any other case, a TypeError is raised because we are not supporting that data type yet. Parameters ---------- observations : list of lists or arrays observation trajectories Returns ------- output_type : str One of {'discrete', 'gaussian'} """ 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.round(o1)): isintegral = True for i in range(1, len(observations)): if not _np.allclose(observations[i], _np.round(observations[i])): isintegral = False break if isintegral: return 'discrete' # CASE: vector of double? Then we want a gaussian if _types.is_float_vector(o1): return 'gaussian' # None of the above? Then we currently do not support this format! raise TypeError('Observations is neither sequences of integers nor 1D-sequences of floats. The current version' 'does not support your input.')
python
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 sense based on observation data. If observations consist of arrays/lists of integer numbers (irrespective of whether the python type is int or float), our guess is 'discrete'. If observations consist of arrays/lists of 1D-floats, our guess is 'discrete'. In any other case, a TypeError is raised because we are not supporting that data type yet. Parameters ---------- observations : list of lists or arrays observation trajectories Returns ------- output_type : str One of {'discrete', 'gaussian'} """ 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.round(o1)): isintegral = True for i in range(1, len(observations)): if not _np.allclose(observations[i], _np.round(observations[i])): isintegral = False break if isintegral: return 'discrete' # CASE: vector of double? Then we want a gaussian if _types.is_float_vector(o1): return 'gaussian' # None of the above? Then we currently do not support this format! raise TypeError('Observations is neither sequences of integers nor 1D-sequences of floats. The current version' 'does not support your input.')
[ "def", "_guess_output_type", "(", "observations", ")", ":", "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", ".", "round", "(", "o1", ")", ")", ":", "isintegral", "=", "True", "for", "i", "in", "range", "(", "1", ",", "len", "(", "observations", ")", ")", ":", "if", "not", "_np", ".", "allclose", "(", "observations", "[", "i", "]", ",", "_np", ".", "round", "(", "observations", "[", "i", "]", ")", ")", ":", "isintegral", "=", "False", "break", "if", "isintegral", ":", "return", "'discrete'", "# CASE: vector of double? Then we want a gaussian", "if", "_types", ".", "is_float_vector", "(", "o1", ")", ":", "return", "'gaussian'", "# None of the above? Then we currently do not support this format!", "raise", "TypeError", "(", "'Observations is neither sequences of integers nor 1D-sequences of floats. The current version'", "'does not support your input.'", ")" ]
Suggests a HMM model type based on the observation data Uses simple rules in order to decide which HMM model type makes sense based on observation data. If observations consist of arrays/lists of integer numbers (irrespective of whether the python type is int or float), our guess is 'discrete'. If observations consist of arrays/lists of 1D-floats, our guess is 'discrete'. In any other case, a TypeError is raised because we are not supporting that data type yet. Parameters ---------- observations : list of lists or arrays observation trajectories Returns ------- output_type : str One of {'discrete', 'gaussian'}
[ "Suggests", "a", "HMM", "model", "type", "based", "on", "the", "observation", "data" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L23-L67
bhmm/bhmm
bhmm/api.py
lag_observations
def lag_observations(observations, lag, stride=1): r""" Create new trajectories that are subsampled at lag but shifted Given a trajectory (s0, s1, s2, s3, s4, ...) and lag 3, this function will generate 3 trajectories (s0, s3, s6, ...), (s1, s4, s7, ...) and (s2, s5, s8, ...). Use this function in order to parametrize a MLE at lag times larger than 1 without discarding data. Do not use this function for Bayesian estimators, where data must be given such that subsequent transitions are uncorrelated. Parameters ---------- observations : list of int arrays observation trajectories lag : int lag time stride : int, default=1 will return only one trajectory for every stride. Use this for Bayesian analysis. """ 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
python
def lag_observations(observations, lag, stride=1): r""" Create new trajectories that are subsampled at lag but shifted Given a trajectory (s0, s1, s2, s3, s4, ...) and lag 3, this function will generate 3 trajectories (s0, s3, s6, ...), (s1, s4, s7, ...) and (s2, s5, s8, ...). Use this function in order to parametrize a MLE at lag times larger than 1 without discarding data. Do not use this function for Bayesian estimators, where data must be given such that subsequent transitions are uncorrelated. Parameters ---------- observations : list of int arrays observation trajectories lag : int lag time stride : int, default=1 will return only one trajectory for every stride. Use this for Bayesian analysis. """ 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
[ "def", "lag_observations", "(", "observations", ",", "lag", ",", "stride", "=", "1", ")", ":", "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" ]
r""" Create new trajectories that are subsampled at lag but shifted Given a trajectory (s0, s1, s2, s3, s4, ...) and lag 3, this function will generate 3 trajectories (s0, s3, s6, ...), (s1, s4, s7, ...) and (s2, s5, s8, ...). Use this function in order to parametrize a MLE at lag times larger than 1 without discarding data. Do not use this function for Bayesian estimators, where data must be given such that subsequent transitions are uncorrelated. Parameters ---------- observations : list of int arrays observation trajectories lag : int lag time stride : int, default=1 will return only one trajectory for every stride. Use this for Bayesian analysis.
[ "r", "Create", "new", "trajectories", "that", "are", "subsampled", "at", "lag", "but", "shifted" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L70-L94
bhmm/bhmm
bhmm/api.py
gaussian_hmm
def gaussian_hmm(pi, P, means, sigmas): """ Initializes a 1D-Gaussian HMM Parameters ---------- pi : ndarray(nstates, ) Initial distribution. P : ndarray(nstates,nstates) Hidden transition matrix means : ndarray(nstates, ) Means of Gaussian output distributions sigmas : ndarray(nstates, ) Standard deviations of Gaussian output distributions stationary : bool, optional, default=True If True: initial distribution is equal to stationary distribution of transition matrix reversible : bool, optional, default=True If True: transition matrix will fulfill detailed balance constraints. """ 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_hmm import HMM as _HMM ghmm = _HMM(pi, P, output_model) # turn it into a Gaussian HMM ghmm = GaussianHMM(ghmm) return ghmm
python
def gaussian_hmm(pi, P, means, sigmas): """ Initializes a 1D-Gaussian HMM Parameters ---------- pi : ndarray(nstates, ) Initial distribution. P : ndarray(nstates,nstates) Hidden transition matrix means : ndarray(nstates, ) Means of Gaussian output distributions sigmas : ndarray(nstates, ) Standard deviations of Gaussian output distributions stationary : bool, optional, default=True If True: initial distribution is equal to stationary distribution of transition matrix reversible : bool, optional, default=True If True: transition matrix will fulfill detailed balance constraints. """ 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_hmm import HMM as _HMM ghmm = _HMM(pi, P, output_model) # turn it into a Gaussian HMM ghmm = GaussianHMM(ghmm) return ghmm
[ "def", "gaussian_hmm", "(", "pi", ",", "P", ",", "means", ",", "sigmas", ")", ":", "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_hmm", "import", "HMM", "as", "_HMM", "ghmm", "=", "_HMM", "(", "pi", ",", "P", ",", "output_model", ")", "# turn it into a Gaussian HMM", "ghmm", "=", "GaussianHMM", "(", "ghmm", ")", "return", "ghmm" ]
Initializes a 1D-Gaussian HMM Parameters ---------- pi : ndarray(nstates, ) Initial distribution. P : ndarray(nstates,nstates) Hidden transition matrix means : ndarray(nstates, ) Means of Gaussian output distributions sigmas : ndarray(nstates, ) Standard deviations of Gaussian output distributions stationary : bool, optional, default=True If True: initial distribution is equal to stationary distribution of transition matrix reversible : bool, optional, default=True If True: transition matrix will fulfill detailed balance constraints.
[ "Initializes", "a", "1D", "-", "Gaussian", "HMM" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L97-L127
bhmm/bhmm
bhmm/api.py
discrete_hmm
def discrete_hmm(pi, P, pout): """ Initializes a discrete HMM Parameters ---------- pi : ndarray(nstates, ) Initial distribution. P : ndarray(nstates,nstates) Hidden transition matrix pout : ndarray(nstates,nsymbols) Output matrix from hidden states to observable symbols pi : ndarray(nstates, ) Fixed initial (if stationary=False) or fixed stationary distribution (if stationary=True). stationary : bool, optional, default=True If True: initial distribution is equal to stationary distribution of transition matrix reversible : bool, optional, default=True If True: transition matrix will fulfill detailed balance constraints. """ 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 into a Gaussian HMM dhmm = DiscreteHMM(dhmm) return dhmm
python
def discrete_hmm(pi, P, pout): """ Initializes a discrete HMM Parameters ---------- pi : ndarray(nstates, ) Initial distribution. P : ndarray(nstates,nstates) Hidden transition matrix pout : ndarray(nstates,nsymbols) Output matrix from hidden states to observable symbols pi : ndarray(nstates, ) Fixed initial (if stationary=False) or fixed stationary distribution (if stationary=True). stationary : bool, optional, default=True If True: initial distribution is equal to stationary distribution of transition matrix reversible : bool, optional, default=True If True: transition matrix will fulfill detailed balance constraints. """ 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 into a Gaussian HMM dhmm = DiscreteHMM(dhmm) return dhmm
[ "def", "discrete_hmm", "(", "pi", ",", "P", ",", "pout", ")", ":", "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 into a Gaussian HMM", "dhmm", "=", "DiscreteHMM", "(", "dhmm", ")", "return", "dhmm" ]
Initializes a discrete HMM Parameters ---------- pi : ndarray(nstates, ) Initial distribution. P : ndarray(nstates,nstates) Hidden transition matrix pout : ndarray(nstates,nsymbols) Output matrix from hidden states to observable symbols pi : ndarray(nstates, ) Fixed initial (if stationary=False) or fixed stationary distribution (if stationary=True). stationary : bool, optional, default=True If True: initial distribution is equal to stationary distribution of transition matrix reversible : bool, optional, default=True If True: transition matrix will fulfill detailed balance constraints.
[ "Initializes", "a", "discrete", "HMM" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L130-L158
bhmm/bhmm
bhmm/api.py
init_hmm
def init_hmm(observations, nstates, lag=1, output=None, reversible=True): """Use a heuristic scheme to generate an initial model. Parameters ---------- observations : list of ndarray((T_i)) list of arrays of length T_i with observation data nstates : int The number of states. output : str, optional, default=None Output model type from [None, 'gaussian', 'discrete']. If None, will automatically select an output model type based on the format of observations. Examples -------- Generate initial model for a gaussian output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_hmm(observations, model.nstates, output='gaussian') Generate initial model for a discrete output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='discrete') >>> initial_model = init_hmm(observations, model.nstates, output='discrete') """ # select output model type if output is None: output = _guess_output_type(observations) if output == 'discrete': return init_discrete_hmm(observations, nstates, lag=lag, reversible=reversible) elif output == 'gaussian': return init_gaussian_hmm(observations, nstates, lag=lag, reversible=reversible) else: raise NotImplementedError('output model type '+str(output)+' not yet implemented.')
python
def init_hmm(observations, nstates, lag=1, output=None, reversible=True): """Use a heuristic scheme to generate an initial model. Parameters ---------- observations : list of ndarray((T_i)) list of arrays of length T_i with observation data nstates : int The number of states. output : str, optional, default=None Output model type from [None, 'gaussian', 'discrete']. If None, will automatically select an output model type based on the format of observations. Examples -------- Generate initial model for a gaussian output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_hmm(observations, model.nstates, output='gaussian') Generate initial model for a discrete output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='discrete') >>> initial_model = init_hmm(observations, model.nstates, output='discrete') """ # select output model type if output is None: output = _guess_output_type(observations) if output == 'discrete': return init_discrete_hmm(observations, nstates, lag=lag, reversible=reversible) elif output == 'gaussian': return init_gaussian_hmm(observations, nstates, lag=lag, reversible=reversible) else: raise NotImplementedError('output model type '+str(output)+' not yet implemented.')
[ "def", "init_hmm", "(", "observations", ",", "nstates", ",", "lag", "=", "1", ",", "output", "=", "None", ",", "reversible", "=", "True", ")", ":", "# select output model type", "if", "output", "is", "None", ":", "output", "=", "_guess_output_type", "(", "observations", ")", "if", "output", "==", "'discrete'", ":", "return", "init_discrete_hmm", "(", "observations", ",", "nstates", ",", "lag", "=", "lag", ",", "reversible", "=", "reversible", ")", "elif", "output", "==", "'gaussian'", ":", "return", "init_gaussian_hmm", "(", "observations", ",", "nstates", ",", "lag", "=", "lag", ",", "reversible", "=", "reversible", ")", "else", ":", "raise", "NotImplementedError", "(", "'output model type '", "+", "str", "(", "output", ")", "+", "' not yet implemented.'", ")" ]
Use a heuristic scheme to generate an initial model. Parameters ---------- observations : list of ndarray((T_i)) list of arrays of length T_i with observation data nstates : int The number of states. output : str, optional, default=None Output model type from [None, 'gaussian', 'discrete']. If None, will automatically select an output model type based on the format of observations. Examples -------- Generate initial model for a gaussian output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_hmm(observations, model.nstates, output='gaussian') Generate initial model for a discrete output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='discrete') >>> initial_model = init_hmm(observations, model.nstates, output='discrete')
[ "Use", "a", "heuristic", "scheme", "to", "generate", "an", "initial", "model", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L161-L199
bhmm/bhmm
bhmm/api.py
init_gaussian_hmm
def init_gaussian_hmm(observations, nstates, lag=1, reversible=True): """ Use a heuristic scheme to generate an initial model. Parameters ---------- observations : list of ndarray((T_i)) list of arrays of length T_i with observation data nstates : int The number of states. Examples -------- Generate initial model for a gaussian output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_gaussian_hmm(observations, model.nstates) """ from bhmm.init import gaussian if lag > 1: observations = lag_observations(observations, lag) hmm0 = gaussian.init_model_gaussian1d(observations, nstates, reversible=reversible) hmm0._lag = lag return hmm0
python
def init_gaussian_hmm(observations, nstates, lag=1, reversible=True): """ Use a heuristic scheme to generate an initial model. Parameters ---------- observations : list of ndarray((T_i)) list of arrays of length T_i with observation data nstates : int The number of states. Examples -------- Generate initial model for a gaussian output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_gaussian_hmm(observations, model.nstates) """ from bhmm.init import gaussian if lag > 1: observations = lag_observations(observations, lag) hmm0 = gaussian.init_model_gaussian1d(observations, nstates, reversible=reversible) hmm0._lag = lag return hmm0
[ "def", "init_gaussian_hmm", "(", "observations", ",", "nstates", ",", "lag", "=", "1", ",", "reversible", "=", "True", ")", ":", "from", "bhmm", ".", "init", "import", "gaussian", "if", "lag", ">", "1", ":", "observations", "=", "lag_observations", "(", "observations", ",", "lag", ")", "hmm0", "=", "gaussian", ".", "init_model_gaussian1d", "(", "observations", ",", "nstates", ",", "reversible", "=", "reversible", ")", "hmm0", ".", "_lag", "=", "lag", "return", "hmm0" ]
Use a heuristic scheme to generate an initial model. Parameters ---------- observations : list of ndarray((T_i)) list of arrays of length T_i with observation data nstates : int The number of states. Examples -------- Generate initial model for a gaussian output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='gaussian') >>> initial_model = init_gaussian_hmm(observations, model.nstates)
[ "Use", "a", "heuristic", "scheme", "to", "generate", "an", "initial", "model", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L202-L227
bhmm/bhmm
bhmm/api.py
init_discrete_hmm
def init_discrete_hmm(observations, nstates, lag=1, reversible=True, stationary=True, regularize=True, method='connect-spectral', separate=None): """Use a heuristic scheme to generate an initial model. Parameters ---------- observations : list of ndarray((T_i)) list of arrays of length T_i with observation data nstates : int The number of states. lag : int Lag time at which the observations should be counted. reversible : bool Estimate reversible HMM transition matrix. stationary : bool p0 is the stationary distribution of P. Currently only reversible=True is implemented regularize : bool Regularize HMM probabilities to avoid 0's. method : str * 'lcs-spectral' : Does spectral clustering on the largest connected set of observed states. * 'connect-spectral' : Uses a weak regularization to connect the weakly connected sets and then initializes HMM using spectral clustering on the nonempty set. * 'spectral' : Uses spectral clustering on the nonempty subsets. Separated observed states will end up in separate hidden states. This option is only recommended for small observation spaces. Use connect-spectral for large observation spaces. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. Examples -------- Generate initial model for a discrete output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='discrete') >>> initial_model = init_discrete_hmm(observations, model.nstates) """ import msmtools.estimation as msmest from bhmm.init.discrete import init_discrete_hmm_spectral C = msmest.count_matrix(observations, lag).toarray() # regularization if regularize: eps_A = None eps_B = None else: eps_A = 0 eps_B = 0 if not stationary: raise NotImplementedError('Discrete-HMM initialization with stationary=False is not yet implemented.') if method=='lcs-spectral': lcs = msmest.largest_connected_set(C) p0, P, B = init_discrete_hmm_spectral(C, nstates, reversible=reversible, stationary=stationary, active_set=lcs, separate=separate, eps_A=eps_A, eps_B=eps_B) elif method=='connect-spectral': # make sure we're strongly connected C += msmest.prior_neighbor(C, 0.001) nonempty = _np.where(C.sum(axis=0) + C.sum(axis=1) > 0)[0] C[nonempty, nonempty] = _np.maximum(C[nonempty, nonempty], 0.001) p0, P, B = init_discrete_hmm_spectral(C, nstates, reversible=reversible, stationary=stationary, active_set=nonempty, separate=separate, eps_A=eps_A, eps_B=eps_B) elif method=='spectral': p0, P, B = init_discrete_hmm_spectral(C, nstates, reversible=reversible, stationary=stationary, active_set=None, separate=separate, eps_A=eps_A, eps_B=eps_B) else: raise NotImplementedError('Unknown discrete-HMM initialization method ' + str(method)) hmm0 = discrete_hmm(p0, P, B) hmm0._lag = lag return hmm0
python
def init_discrete_hmm(observations, nstates, lag=1, reversible=True, stationary=True, regularize=True, method='connect-spectral', separate=None): """Use a heuristic scheme to generate an initial model. Parameters ---------- observations : list of ndarray((T_i)) list of arrays of length T_i with observation data nstates : int The number of states. lag : int Lag time at which the observations should be counted. reversible : bool Estimate reversible HMM transition matrix. stationary : bool p0 is the stationary distribution of P. Currently only reversible=True is implemented regularize : bool Regularize HMM probabilities to avoid 0's. method : str * 'lcs-spectral' : Does spectral clustering on the largest connected set of observed states. * 'connect-spectral' : Uses a weak regularization to connect the weakly connected sets and then initializes HMM using spectral clustering on the nonempty set. * 'spectral' : Uses spectral clustering on the nonempty subsets. Separated observed states will end up in separate hidden states. This option is only recommended for small observation spaces. Use connect-spectral for large observation spaces. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. Examples -------- Generate initial model for a discrete output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='discrete') >>> initial_model = init_discrete_hmm(observations, model.nstates) """ import msmtools.estimation as msmest from bhmm.init.discrete import init_discrete_hmm_spectral C = msmest.count_matrix(observations, lag).toarray() # regularization if regularize: eps_A = None eps_B = None else: eps_A = 0 eps_B = 0 if not stationary: raise NotImplementedError('Discrete-HMM initialization with stationary=False is not yet implemented.') if method=='lcs-spectral': lcs = msmest.largest_connected_set(C) p0, P, B = init_discrete_hmm_spectral(C, nstates, reversible=reversible, stationary=stationary, active_set=lcs, separate=separate, eps_A=eps_A, eps_B=eps_B) elif method=='connect-spectral': # make sure we're strongly connected C += msmest.prior_neighbor(C, 0.001) nonempty = _np.where(C.sum(axis=0) + C.sum(axis=1) > 0)[0] C[nonempty, nonempty] = _np.maximum(C[nonempty, nonempty], 0.001) p0, P, B = init_discrete_hmm_spectral(C, nstates, reversible=reversible, stationary=stationary, active_set=nonempty, separate=separate, eps_A=eps_A, eps_B=eps_B) elif method=='spectral': p0, P, B = init_discrete_hmm_spectral(C, nstates, reversible=reversible, stationary=stationary, active_set=None, separate=separate, eps_A=eps_A, eps_B=eps_B) else: raise NotImplementedError('Unknown discrete-HMM initialization method ' + str(method)) hmm0 = discrete_hmm(p0, P, B) hmm0._lag = lag return hmm0
[ "def", "init_discrete_hmm", "(", "observations", ",", "nstates", ",", "lag", "=", "1", ",", "reversible", "=", "True", ",", "stationary", "=", "True", ",", "regularize", "=", "True", ",", "method", "=", "'connect-spectral'", ",", "separate", "=", "None", ")", ":", "import", "msmtools", ".", "estimation", "as", "msmest", "from", "bhmm", ".", "init", ".", "discrete", "import", "init_discrete_hmm_spectral", "C", "=", "msmest", ".", "count_matrix", "(", "observations", ",", "lag", ")", ".", "toarray", "(", ")", "# regularization", "if", "regularize", ":", "eps_A", "=", "None", "eps_B", "=", "None", "else", ":", "eps_A", "=", "0", "eps_B", "=", "0", "if", "not", "stationary", ":", "raise", "NotImplementedError", "(", "'Discrete-HMM initialization with stationary=False is not yet implemented.'", ")", "if", "method", "==", "'lcs-spectral'", ":", "lcs", "=", "msmest", ".", "largest_connected_set", "(", "C", ")", "p0", ",", "P", ",", "B", "=", "init_discrete_hmm_spectral", "(", "C", ",", "nstates", ",", "reversible", "=", "reversible", ",", "stationary", "=", "stationary", ",", "active_set", "=", "lcs", ",", "separate", "=", "separate", ",", "eps_A", "=", "eps_A", ",", "eps_B", "=", "eps_B", ")", "elif", "method", "==", "'connect-spectral'", ":", "# make sure we're strongly connected", "C", "+=", "msmest", ".", "prior_neighbor", "(", "C", ",", "0.001", ")", "nonempty", "=", "_np", ".", "where", "(", "C", ".", "sum", "(", "axis", "=", "0", ")", "+", "C", ".", "sum", "(", "axis", "=", "1", ")", ">", "0", ")", "[", "0", "]", "C", "[", "nonempty", ",", "nonempty", "]", "=", "_np", ".", "maximum", "(", "C", "[", "nonempty", ",", "nonempty", "]", ",", "0.001", ")", "p0", ",", "P", ",", "B", "=", "init_discrete_hmm_spectral", "(", "C", ",", "nstates", ",", "reversible", "=", "reversible", ",", "stationary", "=", "stationary", ",", "active_set", "=", "nonempty", ",", "separate", "=", "separate", ",", "eps_A", "=", "eps_A", ",", "eps_B", "=", "eps_B", ")", "elif", "method", "==", "'spectral'", ":", "p0", ",", "P", ",", "B", "=", "init_discrete_hmm_spectral", "(", "C", ",", "nstates", ",", "reversible", "=", "reversible", ",", "stationary", "=", "stationary", ",", "active_set", "=", "None", ",", "separate", "=", "separate", ",", "eps_A", "=", "eps_A", ",", "eps_B", "=", "eps_B", ")", "else", ":", "raise", "NotImplementedError", "(", "'Unknown discrete-HMM initialization method '", "+", "str", "(", "method", ")", ")", "hmm0", "=", "discrete_hmm", "(", "p0", ",", "P", ",", "B", ")", "hmm0", ".", "_lag", "=", "lag", "return", "hmm0" ]
Use a heuristic scheme to generate an initial model. Parameters ---------- observations : list of ndarray((T_i)) list of arrays of length T_i with observation data nstates : int The number of states. lag : int Lag time at which the observations should be counted. reversible : bool Estimate reversible HMM transition matrix. stationary : bool p0 is the stationary distribution of P. Currently only reversible=True is implemented regularize : bool Regularize HMM probabilities to avoid 0's. method : str * 'lcs-spectral' : Does spectral clustering on the largest connected set of observed states. * 'connect-spectral' : Uses a weak regularization to connect the weakly connected sets and then initializes HMM using spectral clustering on the nonempty set. * 'spectral' : Uses spectral clustering on the nonempty subsets. Separated observed states will end up in separate hidden states. This option is only recommended for small observation spaces. Use connect-spectral for large observation spaces. separate : None or iterable of int Force the given set of observed states to stay in a separate hidden state. The remaining nstates-1 states will be assigned by a metastable decomposition. Examples -------- Generate initial model for a discrete output model. >>> import bhmm >>> [model, observations, states] = bhmm.testsystems.generate_synthetic_observations(output='discrete') >>> initial_model = init_discrete_hmm(observations, model.nstates)
[ "Use", "a", "heuristic", "scheme", "to", "generate", "an", "initial", "model", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L231-L305
bhmm/bhmm
bhmm/api.py
estimate_hmm
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=100000, mincount_connectivity=1e-2): r""" Estimate maximum-likelihood HMM Generic maximum-likelihood estimation of HMMs Parameters ---------- observations : list of numpy arrays representing temporal data `observations[i]` is a 1d numpy array corresponding to the observed trajectory index `i` nstates : int The number of states in the model. lag : int the lag time at which observations should be read initial_model : HMM, optional, default=None If specified, the given initial model will be used to initialize the BHMM. Otherwise, a heuristic scheme is used to generate an initial guess. output : str, optional, default=None Output model type from [None, 'gaussian', 'discrete']. If None, will automatically select an output model type based on the format of observations. reversible : bool, optional, default=True If True, a prior that enforces reversible transition matrices (detailed balance) is used; otherwise, a standard non-reversible prior is used. stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. p : ndarray (nstates), optional, default=None Initial or fixed stationary distribution. If given and stationary=True, transition matrices will be estimated with the constraint that they have p as their stationary distribution. If given and stationary=False, p is the fixed initial distribution of hidden states. accuracy : float convergence threshold for EM iteration. When two the likelihood does not increase by more than accuracy, the iteration is stopped successfully. maxit : int stopping criterion for EM iteration. When so many iterations are performed without reaching the requested accuracy, the iteration is stopped without convergence (a warning is given) Return ------ hmm : :class:`HMM <bhmm.hmm.generic_hmm.HMM>` """ # 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 est = _MaximumLikelihoodEstimator(observations, nstates, initial_model=initial_model, output=output, reversible=reversible, stationary=stationary, p=p, accuracy=accuracy, maxit=maxit, maxit_P=maxit_P) # run est.fit() # set lag time est.hmm._lag = lag # return model # TODO: package into specific class (DiscreteHMM, GaussianHMM) return est.hmm
python
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=100000, mincount_connectivity=1e-2): r""" Estimate maximum-likelihood HMM Generic maximum-likelihood estimation of HMMs Parameters ---------- observations : list of numpy arrays representing temporal data `observations[i]` is a 1d numpy array corresponding to the observed trajectory index `i` nstates : int The number of states in the model. lag : int the lag time at which observations should be read initial_model : HMM, optional, default=None If specified, the given initial model will be used to initialize the BHMM. Otherwise, a heuristic scheme is used to generate an initial guess. output : str, optional, default=None Output model type from [None, 'gaussian', 'discrete']. If None, will automatically select an output model type based on the format of observations. reversible : bool, optional, default=True If True, a prior that enforces reversible transition matrices (detailed balance) is used; otherwise, a standard non-reversible prior is used. stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. p : ndarray (nstates), optional, default=None Initial or fixed stationary distribution. If given and stationary=True, transition matrices will be estimated with the constraint that they have p as their stationary distribution. If given and stationary=False, p is the fixed initial distribution of hidden states. accuracy : float convergence threshold for EM iteration. When two the likelihood does not increase by more than accuracy, the iteration is stopped successfully. maxit : int stopping criterion for EM iteration. When so many iterations are performed without reaching the requested accuracy, the iteration is stopped without convergence (a warning is given) Return ------ hmm : :class:`HMM <bhmm.hmm.generic_hmm.HMM>` """ # 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 est = _MaximumLikelihoodEstimator(observations, nstates, initial_model=initial_model, output=output, reversible=reversible, stationary=stationary, p=p, accuracy=accuracy, maxit=maxit, maxit_P=maxit_P) # run est.fit() # set lag time est.hmm._lag = lag # return model # TODO: package into specific class (DiscreteHMM, GaussianHMM) return est.hmm
[ "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", "=", "100000", ",", "mincount_connectivity", "=", "1e-2", ")", ":", "# 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", "est", "=", "_MaximumLikelihoodEstimator", "(", "observations", ",", "nstates", ",", "initial_model", "=", "initial_model", ",", "output", "=", "output", ",", "reversible", "=", "reversible", ",", "stationary", "=", "stationary", ",", "p", "=", "p", ",", "accuracy", "=", "accuracy", ",", "maxit", "=", "maxit", ",", "maxit_P", "=", "maxit_P", ")", "# run", "est", ".", "fit", "(", ")", "# set lag time", "est", ".", "hmm", ".", "_lag", "=", "lag", "# return model", "# TODO: package into specific class (DiscreteHMM, GaussianHMM)", "return", "est", ".", "hmm" ]
r""" Estimate maximum-likelihood HMM Generic maximum-likelihood estimation of HMMs Parameters ---------- observations : list of numpy arrays representing temporal data `observations[i]` is a 1d numpy array corresponding to the observed trajectory index `i` nstates : int The number of states in the model. lag : int the lag time at which observations should be read initial_model : HMM, optional, default=None If specified, the given initial model will be used to initialize the BHMM. Otherwise, a heuristic scheme is used to generate an initial guess. output : str, optional, default=None Output model type from [None, 'gaussian', 'discrete']. If None, will automatically select an output model type based on the format of observations. reversible : bool, optional, default=True If True, a prior that enforces reversible transition matrices (detailed balance) is used; otherwise, a standard non-reversible prior is used. stationary : bool, optional, default=False If True, the initial distribution of hidden states is self-consistently computed as the stationary distribution of the transition matrix. If False, it will be estimated from the starting states. Only set this to true if you're sure that the observation trajectories are initiated from a global equilibrium distribution. p : ndarray (nstates), optional, default=None Initial or fixed stationary distribution. If given and stationary=True, transition matrices will be estimated with the constraint that they have p as their stationary distribution. If given and stationary=False, p is the fixed initial distribution of hidden states. accuracy : float convergence threshold for EM iteration. When two the likelihood does not increase by more than accuracy, the iteration is stopped successfully. maxit : int stopping criterion for EM iteration. When so many iterations are performed without reaching the requested accuracy, the iteration is stopped without convergence (a warning is given) Return ------ hmm : :class:`HMM <bhmm.hmm.generic_hmm.HMM>`
[ "r", "Estimate", "maximum", "-", "likelihood", "HMM" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L309-L372
bhmm/bhmm
bhmm/api.py
bayesian_hmm
def bayesian_hmm(observations, estimated_hmm, nsample=100, reversible=True, stationary=False, p0_prior='mixed', transition_matrix_prior='mixed', store_hidden=False, call_back=None): r""" Bayesian HMM based on sampling the posterior Generic maximum-likelihood estimation of HMMs Parameters ---------- observations : list of numpy arrays representing temporal data `observations[i]` is a 1d numpy array corresponding to the observed trajectory index `i` estimated_hmm : HMM HMM estimated from estimate_hmm or initialize_hmm reversible : bool, optional, default=True If True, a prior that enforces reversible transition matrices (detailed balance) is used; otherwise, a standard non-reversible prior is used. stationary : bool, optional, default=False If True, the stationary distribution of the transition matrix will be used as initial distribution. Only use True if you are confident that the observation trajectories are started from a global equilibrium. If False, the initial distribution will be estimated as usual from the first step of the hidden trajectories. nsample : int, optional, default=100 number of Gibbs sampling steps p0_prior : None, str, float or ndarray(n) Prior for the initial distribution of the HMM. Will only be active if stationary=False (stationary=True means that p0 is identical to the stationary distribution of the transition matrix). Currently implements different versions of the Dirichlet prior that is conjugate to the Dirichlet distribution of p0. p0 is sampled from: .. math: p0 \sim \prod_i (p0)_i^{a_i + n_i - 1} where :math:`n_i` are the number of times a hidden trajectory was in state :math:`i` at time step 0 and :math:`a_i` is the prior count. Following options are available: | 'mixed' (default), :math:`a_i = p_{0,init}`, where :math:`p_{0,init}` is the initial distribution of initial_model. | 'uniform', :math:`a_i = 1` | ndarray(n) or float, the given array will be used as A. | None, :math:`a_i = 0`. This option ensures coincidence between sample mean an MLE. Will sooner or later lead to sampling problems, because as soon as zero trajectories are drawn from a given state, the sampler cannot recover and that state will never serve as a starting state subsequently. Only recommended in the large data regime and when the probability to sample zero trajectories from any state is negligible. transition_matrix_prior : str or ndarray(n, n) Prior for the HMM transition matrix. Currently implements Dirichlet priors if reversible=False and reversible transition matrix priors as described in [1]_ if reversible=True. For the nonreversible case the posterior of transition matrix :math:`P` is: .. math: P \sim \prod_{i,j} p_{ij}^{b_{ij} + c_{ij} - 1} where :math:`c_{ij}` are the number of transitions found for hidden trajectories and :math:`b_{ij}` are prior counts. | 'mixed' (default), :math:`b_{ij} = p_{ij,init}`, where :math:`p_{ij,init}` is the transition matrix of initial_model. That means one prior count will be used per row. | 'uniform', :math:`b_{ij} = 1` | ndarray(n, n) or broadcastable, the given array will be used as B. | None, :math:`b_ij = 0`. This option ensures coincidence between sample mean an MLE. Will sooner or later lead to sampling problems, because as soon as a transition :math:`ij` will not occur in a sample, the sampler cannot recover and that transition will never be sampled again. This option is not recommended unless you have a small HMM and a lot of data. store_hidden : bool, optional, default=False store hidden trajectories in sampled HMMs call_back : function, optional, default=None a call back function with no arguments, which if given is being called after each computed sample. This is useful for implementing progress bars. Return ------ hmm : :class:`SampledHMM <bhmm.hmm.generic_sampled_hmm.SampledHMM>` References ---------- .. [1] Trendelkamp-Schroer, B., H. Wu, F. Paul and F. Noe: Estimation and uncertainty of reversible Markov models. J. Chem. Phys. 143, 174101 (2015). """ # 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_prior=p0_prior, transition_matrix_prior=transition_matrix_prior, output=estimated_hmm.output_model.model_type) # Sample models. sampled_hmms = sampler.sample(nsamples=nsample, save_hidden_state_trajectory=store_hidden, call_back=call_back) # return model from bhmm.hmm.generic_sampled_hmm import SampledHMM return SampledHMM(estimated_hmm, sampled_hmms)
python
def bayesian_hmm(observations, estimated_hmm, nsample=100, reversible=True, stationary=False, p0_prior='mixed', transition_matrix_prior='mixed', store_hidden=False, call_back=None): r""" Bayesian HMM based on sampling the posterior Generic maximum-likelihood estimation of HMMs Parameters ---------- observations : list of numpy arrays representing temporal data `observations[i]` is a 1d numpy array corresponding to the observed trajectory index `i` estimated_hmm : HMM HMM estimated from estimate_hmm or initialize_hmm reversible : bool, optional, default=True If True, a prior that enforces reversible transition matrices (detailed balance) is used; otherwise, a standard non-reversible prior is used. stationary : bool, optional, default=False If True, the stationary distribution of the transition matrix will be used as initial distribution. Only use True if you are confident that the observation trajectories are started from a global equilibrium. If False, the initial distribution will be estimated as usual from the first step of the hidden trajectories. nsample : int, optional, default=100 number of Gibbs sampling steps p0_prior : None, str, float or ndarray(n) Prior for the initial distribution of the HMM. Will only be active if stationary=False (stationary=True means that p0 is identical to the stationary distribution of the transition matrix). Currently implements different versions of the Dirichlet prior that is conjugate to the Dirichlet distribution of p0. p0 is sampled from: .. math: p0 \sim \prod_i (p0)_i^{a_i + n_i - 1} where :math:`n_i` are the number of times a hidden trajectory was in state :math:`i` at time step 0 and :math:`a_i` is the prior count. Following options are available: | 'mixed' (default), :math:`a_i = p_{0,init}`, where :math:`p_{0,init}` is the initial distribution of initial_model. | 'uniform', :math:`a_i = 1` | ndarray(n) or float, the given array will be used as A. | None, :math:`a_i = 0`. This option ensures coincidence between sample mean an MLE. Will sooner or later lead to sampling problems, because as soon as zero trajectories are drawn from a given state, the sampler cannot recover and that state will never serve as a starting state subsequently. Only recommended in the large data regime and when the probability to sample zero trajectories from any state is negligible. transition_matrix_prior : str or ndarray(n, n) Prior for the HMM transition matrix. Currently implements Dirichlet priors if reversible=False and reversible transition matrix priors as described in [1]_ if reversible=True. For the nonreversible case the posterior of transition matrix :math:`P` is: .. math: P \sim \prod_{i,j} p_{ij}^{b_{ij} + c_{ij} - 1} where :math:`c_{ij}` are the number of transitions found for hidden trajectories and :math:`b_{ij}` are prior counts. | 'mixed' (default), :math:`b_{ij} = p_{ij,init}`, where :math:`p_{ij,init}` is the transition matrix of initial_model. That means one prior count will be used per row. | 'uniform', :math:`b_{ij} = 1` | ndarray(n, n) or broadcastable, the given array will be used as B. | None, :math:`b_ij = 0`. This option ensures coincidence between sample mean an MLE. Will sooner or later lead to sampling problems, because as soon as a transition :math:`ij` will not occur in a sample, the sampler cannot recover and that transition will never be sampled again. This option is not recommended unless you have a small HMM and a lot of data. store_hidden : bool, optional, default=False store hidden trajectories in sampled HMMs call_back : function, optional, default=None a call back function with no arguments, which if given is being called after each computed sample. This is useful for implementing progress bars. Return ------ hmm : :class:`SampledHMM <bhmm.hmm.generic_sampled_hmm.SampledHMM>` References ---------- .. [1] Trendelkamp-Schroer, B., H. Wu, F. Paul and F. Noe: Estimation and uncertainty of reversible Markov models. J. Chem. Phys. 143, 174101 (2015). """ # 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_prior=p0_prior, transition_matrix_prior=transition_matrix_prior, output=estimated_hmm.output_model.model_type) # Sample models. sampled_hmms = sampler.sample(nsamples=nsample, save_hidden_state_trajectory=store_hidden, call_back=call_back) # return model from bhmm.hmm.generic_sampled_hmm import SampledHMM return SampledHMM(estimated_hmm, sampled_hmms)
[ "def", "bayesian_hmm", "(", "observations", ",", "estimated_hmm", ",", "nsample", "=", "100", ",", "reversible", "=", "True", ",", "stationary", "=", "False", ",", "p0_prior", "=", "'mixed'", ",", "transition_matrix_prior", "=", "'mixed'", ",", "store_hidden", "=", "False", ",", "call_back", "=", "None", ")", ":", "# 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_prior", "=", "p0_prior", ",", "transition_matrix_prior", "=", "transition_matrix_prior", ",", "output", "=", "estimated_hmm", ".", "output_model", ".", "model_type", ")", "# Sample models.", "sampled_hmms", "=", "sampler", ".", "sample", "(", "nsamples", "=", "nsample", ",", "save_hidden_state_trajectory", "=", "store_hidden", ",", "call_back", "=", "call_back", ")", "# return model", "from", "bhmm", ".", "hmm", ".", "generic_sampled_hmm", "import", "SampledHMM", "return", "SampledHMM", "(", "estimated_hmm", ",", "sampled_hmms", ")" ]
r""" Bayesian HMM based on sampling the posterior Generic maximum-likelihood estimation of HMMs Parameters ---------- observations : list of numpy arrays representing temporal data `observations[i]` is a 1d numpy array corresponding to the observed trajectory index `i` estimated_hmm : HMM HMM estimated from estimate_hmm or initialize_hmm reversible : bool, optional, default=True If True, a prior that enforces reversible transition matrices (detailed balance) is used; otherwise, a standard non-reversible prior is used. stationary : bool, optional, default=False If True, the stationary distribution of the transition matrix will be used as initial distribution. Only use True if you are confident that the observation trajectories are started from a global equilibrium. If False, the initial distribution will be estimated as usual from the first step of the hidden trajectories. nsample : int, optional, default=100 number of Gibbs sampling steps p0_prior : None, str, float or ndarray(n) Prior for the initial distribution of the HMM. Will only be active if stationary=False (stationary=True means that p0 is identical to the stationary distribution of the transition matrix). Currently implements different versions of the Dirichlet prior that is conjugate to the Dirichlet distribution of p0. p0 is sampled from: .. math: p0 \sim \prod_i (p0)_i^{a_i + n_i - 1} where :math:`n_i` are the number of times a hidden trajectory was in state :math:`i` at time step 0 and :math:`a_i` is the prior count. Following options are available: | 'mixed' (default), :math:`a_i = p_{0,init}`, where :math:`p_{0,init}` is the initial distribution of initial_model. | 'uniform', :math:`a_i = 1` | ndarray(n) or float, the given array will be used as A. | None, :math:`a_i = 0`. This option ensures coincidence between sample mean an MLE. Will sooner or later lead to sampling problems, because as soon as zero trajectories are drawn from a given state, the sampler cannot recover and that state will never serve as a starting state subsequently. Only recommended in the large data regime and when the probability to sample zero trajectories from any state is negligible. transition_matrix_prior : str or ndarray(n, n) Prior for the HMM transition matrix. Currently implements Dirichlet priors if reversible=False and reversible transition matrix priors as described in [1]_ if reversible=True. For the nonreversible case the posterior of transition matrix :math:`P` is: .. math: P \sim \prod_{i,j} p_{ij}^{b_{ij} + c_{ij} - 1} where :math:`c_{ij}` are the number of transitions found for hidden trajectories and :math:`b_{ij}` are prior counts. | 'mixed' (default), :math:`b_{ij} = p_{ij,init}`, where :math:`p_{ij,init}` is the transition matrix of initial_model. That means one prior count will be used per row. | 'uniform', :math:`b_{ij} = 1` | ndarray(n, n) or broadcastable, the given array will be used as B. | None, :math:`b_ij = 0`. This option ensures coincidence between sample mean an MLE. Will sooner or later lead to sampling problems, because as soon as a transition :math:`ij` will not occur in a sample, the sampler cannot recover and that transition will never be sampled again. This option is not recommended unless you have a small HMM and a lot of data. store_hidden : bool, optional, default=False store hidden trajectories in sampled HMMs call_back : function, optional, default=None a call back function with no arguments, which if given is being called after each computed sample. This is useful for implementing progress bars. Return ------ hmm : :class:`SampledHMM <bhmm.hmm.generic_sampled_hmm.SampledHMM>` References ---------- .. [1] Trendelkamp-Schroer, B., H. Wu, F. Paul and F. Noe: Estimation and uncertainty of reversible Markov models. J. Chem. Phys. 143, 174101 (2015).
[ "r", "Bayesian", "HMM", "based", "on", "sampling", "the", "posterior" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L375-L470
bhmm/bhmm
bhmm/_external/sklearn/utils.py
logsumexp
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/underflow. Examples -------- >>> import numpy as np >>> from sklearn.utils.extmath import logsumexp >>> a = np.arange(10) >>> np.log(np.sum(np.exp(a))) 9.4586297444267107 >>> logsumexp(a) 9.4586297444267107 """ 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
python
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/underflow. Examples -------- >>> import numpy as np >>> from sklearn.utils.extmath import logsumexp >>> a = np.arange(10) >>> np.log(np.sum(np.exp(a))) 9.4586297444267107 >>> logsumexp(a) 9.4586297444267107 """ 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
[ "def", "logsumexp", "(", "arr", ",", "axis", "=", "0", ")", ":", "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" ]
Computes the sum of arr assuming arr is in the log domain. Returns log(sum(exp(arr))) while minimizing the possibility of over/underflow. Examples -------- >>> import numpy as np >>> from sklearn.utils.extmath import logsumexp >>> a = np.arange(10) >>> np.log(np.sum(np.exp(a))) 9.4586297444267107 >>> logsumexp(a) 9.4586297444267107
[ "Computes", "the", "sum", "of", "arr", "assuming", "arr", "is", "in", "the", "log", "domain", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/utils.py#L112-L135
bhmm/bhmm
bhmm/_external/sklearn/utils.py
_ensure_sparse_format
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 of spmatrix and converts if necessary. Parameters ---------- spmatrix : scipy sparse matrix Input to validate and convert. accept_sparse : string, list of string or None (default=None) String[s] representing allowed sparse matrix formats ('csc', 'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). None means that sparse matrix input will raise an error. If the input is sparse but not in the allowed format, it will be converted to the first listed format. dtype : string, type or None (default=none) Data type of result. If None, the dtype of the input is preserved. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. Returns ------- spmatrix_converted : scipy sparse matrix. Matrix that is ensured to have an allowed type. """ 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_type in accept_sparse: # correct type if dtype == spmatrix.dtype: # correct dtype if copy: spmatrix = spmatrix.copy() else: # convert dtype spmatrix = spmatrix.astype(dtype) else: # create new spmatrix = spmatrix.asformat(accept_sparse[0]).astype(dtype) if force_all_finite: if not hasattr(spmatrix, "data"): warnings.warn("Can't check %s sparse matrix for nan or inf." % spmatrix.format) else: _assert_all_finite(spmatrix.data) if hasattr(spmatrix, "data"): spmatrix.data = np.array(spmatrix.data, copy=False, order=order) return spmatrix
python
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 of spmatrix and converts if necessary. Parameters ---------- spmatrix : scipy sparse matrix Input to validate and convert. accept_sparse : string, list of string or None (default=None) String[s] representing allowed sparse matrix formats ('csc', 'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). None means that sparse matrix input will raise an error. If the input is sparse but not in the allowed format, it will be converted to the first listed format. dtype : string, type or None (default=none) Data type of result. If None, the dtype of the input is preserved. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. Returns ------- spmatrix_converted : scipy sparse matrix. Matrix that is ensured to have an allowed type. """ 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_type in accept_sparse: # correct type if dtype == spmatrix.dtype: # correct dtype if copy: spmatrix = spmatrix.copy() else: # convert dtype spmatrix = spmatrix.astype(dtype) else: # create new spmatrix = spmatrix.asformat(accept_sparse[0]).astype(dtype) if force_all_finite: if not hasattr(spmatrix, "data"): warnings.warn("Can't check %s sparse matrix for nan or inf." % spmatrix.format) else: _assert_all_finite(spmatrix.data) if hasattr(spmatrix, "data"): spmatrix.data = np.array(spmatrix.data, copy=False, order=order) return spmatrix
[ "def", "_ensure_sparse_format", "(", "spmatrix", ",", "accept_sparse", ",", "dtype", ",", "order", ",", "copy", ",", "force_all_finite", ")", ":", "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_type", "in", "accept_sparse", ":", "# correct type", "if", "dtype", "==", "spmatrix", ".", "dtype", ":", "# correct dtype", "if", "copy", ":", "spmatrix", "=", "spmatrix", ".", "copy", "(", ")", "else", ":", "# convert dtype", "spmatrix", "=", "spmatrix", ".", "astype", "(", "dtype", ")", "else", ":", "# create new", "spmatrix", "=", "spmatrix", ".", "asformat", "(", "accept_sparse", "[", "0", "]", ")", ".", "astype", "(", "dtype", ")", "if", "force_all_finite", ":", "if", "not", "hasattr", "(", "spmatrix", ",", "\"data\"", ")", ":", "warnings", ".", "warn", "(", "\"Can't check %s sparse matrix for nan or inf.\"", "%", "spmatrix", ".", "format", ")", "else", ":", "_assert_all_finite", "(", "spmatrix", ".", "data", ")", "if", "hasattr", "(", "spmatrix", ",", "\"data\"", ")", ":", "spmatrix", ".", "data", "=", "np", ".", "array", "(", "spmatrix", ".", "data", ",", "copy", "=", "False", ",", "order", "=", "order", ")", "return", "spmatrix" ]
Convert a sparse matrix to a given format. Checks the sparse format of spmatrix and converts if necessary. Parameters ---------- spmatrix : scipy sparse matrix Input to validate and convert. accept_sparse : string, list of string or None (default=None) String[s] representing allowed sparse matrix formats ('csc', 'csr', 'coo', 'dok', 'bsr', 'lil', 'dia'). None means that sparse matrix input will raise an error. If the input is sparse but not in the allowed format, it will be converted to the first listed format. dtype : string, type or None (default=none) Data type of result. If None, the dtype of the input is preserved. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. Returns ------- spmatrix_converted : scipy sparse matrix. Matrix that is ensured to have an allowed type.
[ "Convert", "a", "sparse", "matrix", "to", "a", "given", "format", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/utils.py#L137-L199
bhmm/bhmm
bhmm/_external/sklearn/utils.py
check_array
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, ensure_min_features=1): """Input validation on an array, list, sparse matrix or similar. By default, the input is converted to an at least 2nd numpy array. If the dtype of the array is object, attempt converting to float, raising on failure. Parameters ---------- array : object Input object to check / convert. accept_sparse : string, list of string or None (default=None) String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. None means that sparse matrix input will raise an error. If the input is sparse but not in the allowed format, it will be converted to the first listed format. dtype : string, type or None (default="numeric") Data type of result. If None, the dtype of the input is preserved. If "numeric", dtype is preserved unless array.dtype is object. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. ensure_2d : boolean (default=True) Whether to make X at least 2d. allow_nd : boolean (default=False) Whether to allow X.ndim > 2. ensure_min_samples : int (default=1) Make sure that the array has a minimum number of samples in its first axis (rows for a 2D array). Setting to 0 disables this check. ensure_min_features : int (default=1) Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when the input data has effectively 2 dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0 disables this check. Returns ------- X_converted : object The converted and validated X. """ 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, order, copy, force_all_finite) else: if ensure_2d: array = np.atleast_2d(array) if dtype_numeric: if hasattr(array, "dtype") and getattr(array.dtype, "kind", None) == "O": # if input is object, convert to float. dtype = np.float64 else: dtype = None array = np.array(array, dtype=dtype, order=order, copy=copy) # make sure we actually converted to numeric: if dtype_numeric and array.dtype.kind == "O": array = array.astype(np.float64) if not allow_nd and array.ndim >= 3: raise ValueError("Found array with dim %d. Expected <= 2" % array.ndim) if force_all_finite: _assert_all_finite(array) shape_repr = _shape_repr(array.shape) if ensure_min_samples > 0: n_samples = _num_samples(array) if n_samples < ensure_min_samples: raise ValueError("Found array with %d sample(s) (shape=%s) while a" " minimum of %d is required." % (n_samples, shape_repr, ensure_min_samples)) if ensure_min_features > 0 and array.ndim == 2: n_features = array.shape[1] if n_features < ensure_min_features: raise ValueError("Found array with %d feature(s) (shape=%s) while" " a minimum of %d is required." % (n_features, shape_repr, ensure_min_features)) return array
python
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, ensure_min_features=1): """Input validation on an array, list, sparse matrix or similar. By default, the input is converted to an at least 2nd numpy array. If the dtype of the array is object, attempt converting to float, raising on failure. Parameters ---------- array : object Input object to check / convert. accept_sparse : string, list of string or None (default=None) String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. None means that sparse matrix input will raise an error. If the input is sparse but not in the allowed format, it will be converted to the first listed format. dtype : string, type or None (default="numeric") Data type of result. If None, the dtype of the input is preserved. If "numeric", dtype is preserved unless array.dtype is object. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. ensure_2d : boolean (default=True) Whether to make X at least 2d. allow_nd : boolean (default=False) Whether to allow X.ndim > 2. ensure_min_samples : int (default=1) Make sure that the array has a minimum number of samples in its first axis (rows for a 2D array). Setting to 0 disables this check. ensure_min_features : int (default=1) Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when the input data has effectively 2 dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0 disables this check. Returns ------- X_converted : object The converted and validated X. """ 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, order, copy, force_all_finite) else: if ensure_2d: array = np.atleast_2d(array) if dtype_numeric: if hasattr(array, "dtype") and getattr(array.dtype, "kind", None) == "O": # if input is object, convert to float. dtype = np.float64 else: dtype = None array = np.array(array, dtype=dtype, order=order, copy=copy) # make sure we actually converted to numeric: if dtype_numeric and array.dtype.kind == "O": array = array.astype(np.float64) if not allow_nd and array.ndim >= 3: raise ValueError("Found array with dim %d. Expected <= 2" % array.ndim) if force_all_finite: _assert_all_finite(array) shape_repr = _shape_repr(array.shape) if ensure_min_samples > 0: n_samples = _num_samples(array) if n_samples < ensure_min_samples: raise ValueError("Found array with %d sample(s) (shape=%s) while a" " minimum of %d is required." % (n_samples, shape_repr, ensure_min_samples)) if ensure_min_features > 0 and array.ndim == 2: n_features = array.shape[1] if n_features < ensure_min_features: raise ValueError("Found array with %d feature(s) (shape=%s) while" " a minimum of %d is required." % (n_features, shape_repr, ensure_min_features)) return array
[ "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", ",", "ensure_min_features", "=", "1", ")", ":", "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", ",", "order", ",", "copy", ",", "force_all_finite", ")", "else", ":", "if", "ensure_2d", ":", "array", "=", "np", ".", "atleast_2d", "(", "array", ")", "if", "dtype_numeric", ":", "if", "hasattr", "(", "array", ",", "\"dtype\"", ")", "and", "getattr", "(", "array", ".", "dtype", ",", "\"kind\"", ",", "None", ")", "==", "\"O\"", ":", "# if input is object, convert to float.", "dtype", "=", "np", ".", "float64", "else", ":", "dtype", "=", "None", "array", "=", "np", ".", "array", "(", "array", ",", "dtype", "=", "dtype", ",", "order", "=", "order", ",", "copy", "=", "copy", ")", "# make sure we actually converted to numeric:", "if", "dtype_numeric", "and", "array", ".", "dtype", ".", "kind", "==", "\"O\"", ":", "array", "=", "array", ".", "astype", "(", "np", ".", "float64", ")", "if", "not", "allow_nd", "and", "array", ".", "ndim", ">=", "3", ":", "raise", "ValueError", "(", "\"Found array with dim %d. Expected <= 2\"", "%", "array", ".", "ndim", ")", "if", "force_all_finite", ":", "_assert_all_finite", "(", "array", ")", "shape_repr", "=", "_shape_repr", "(", "array", ".", "shape", ")", "if", "ensure_min_samples", ">", "0", ":", "n_samples", "=", "_num_samples", "(", "array", ")", "if", "n_samples", "<", "ensure_min_samples", ":", "raise", "ValueError", "(", "\"Found array with %d sample(s) (shape=%s) while a\"", "\" minimum of %d is required.\"", "%", "(", "n_samples", ",", "shape_repr", ",", "ensure_min_samples", ")", ")", "if", "ensure_min_features", ">", "0", "and", "array", ".", "ndim", "==", "2", ":", "n_features", "=", "array", ".", "shape", "[", "1", "]", "if", "n_features", "<", "ensure_min_features", ":", "raise", "ValueError", "(", "\"Found array with %d feature(s) (shape=%s) while\"", "\" a minimum of %d is required.\"", "%", "(", "n_features", ",", "shape_repr", ",", "ensure_min_features", ")", ")", "return", "array" ]
Input validation on an array, list, sparse matrix or similar. By default, the input is converted to an at least 2nd numpy array. If the dtype of the array is object, attempt converting to float, raising on failure. Parameters ---------- array : object Input object to check / convert. accept_sparse : string, list of string or None (default=None) String[s] representing allowed sparse matrix formats, such as 'csc', 'csr', etc. None means that sparse matrix input will raise an error. If the input is sparse but not in the allowed format, it will be converted to the first listed format. dtype : string, type or None (default="numeric") Data type of result. If None, the dtype of the input is preserved. If "numeric", dtype is preserved unless array.dtype is object. order : 'F', 'C' or None (default=None) Whether an array will be forced to be fortran or c-style. copy : boolean (default=False) Whether a forced copy will be triggered. If copy=False, a copy might be triggered by a conversion. force_all_finite : boolean (default=True) Whether to raise an error on np.inf and np.nan in X. ensure_2d : boolean (default=True) Whether to make X at least 2d. allow_nd : boolean (default=False) Whether to allow X.ndim > 2. ensure_min_samples : int (default=1) Make sure that the array has a minimum number of samples in its first axis (rows for a 2D array). Setting to 0 disables this check. ensure_min_features : int (default=1) Make sure that the 2D array has some minimum number of features (columns). The default value of 1 rejects empty datasets. This check is only enforced when the input data has effectively 2 dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0 disables this check. Returns ------- X_converted : object The converted and validated X.
[ "Input", "validation", "on", "an", "array", "list", "sparse", "matrix", "or", "similar", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/utils.py#L229-L329
bhmm/bhmm
bhmm/util/analysis.py
beta_confidence_intervals
def beta_confidence_intervals(ci_X, ntrials, ci=0.95): """ Compute confidence intervals of beta distributions. Parameters ---------- ci_X : numpy.array Computed confidence interval estimate from `ntrials` experiments ntrials : int The number of trials that were run. ci : float, optional, default=0.95 Confidence interval to report (e.g. 0.95 for 95% confidence interval) Returns ------- Plow : float The lower bound of the symmetric confidence interval. Phigh : float The upper bound of the symmetric confidence interval. Examples -------- >>> ci_X = np.random.rand(10,10) >>> ntrials = 100 >>> [Plow, Phigh] = beta_confidence_intervals(ci_X, ntrials) """ # 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]): Plow[i,j] = beta.ppf(ci_low, a = ci_X[i,j] * ntrials, b = (1-ci_X[i,j]) * ntrials); Phigh[i,j] = beta.ppf(ci_high, a = ci_X[i,j] * ntrials, b = (1-ci_X[i,j]) * ntrials); return [Plow, Phigh]
python
def beta_confidence_intervals(ci_X, ntrials, ci=0.95): """ Compute confidence intervals of beta distributions. Parameters ---------- ci_X : numpy.array Computed confidence interval estimate from `ntrials` experiments ntrials : int The number of trials that were run. ci : float, optional, default=0.95 Confidence interval to report (e.g. 0.95 for 95% confidence interval) Returns ------- Plow : float The lower bound of the symmetric confidence interval. Phigh : float The upper bound of the symmetric confidence interval. Examples -------- >>> ci_X = np.random.rand(10,10) >>> ntrials = 100 >>> [Plow, Phigh] = beta_confidence_intervals(ci_X, ntrials) """ # 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]): Plow[i,j] = beta.ppf(ci_low, a = ci_X[i,j] * ntrials, b = (1-ci_X[i,j]) * ntrials); Phigh[i,j] = beta.ppf(ci_high, a = ci_X[i,j] * ntrials, b = (1-ci_X[i,j]) * ntrials); return [Plow, Phigh]
[ "def", "beta_confidence_intervals", "(", "ci_X", ",", "ntrials", ",", "ci", "=", "0.95", ")", ":", "# 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", "]", ")", ":", "Plow", "[", "i", ",", "j", "]", "=", "beta", ".", "ppf", "(", "ci_low", ",", "a", "=", "ci_X", "[", "i", ",", "j", "]", "*", "ntrials", ",", "b", "=", "(", "1", "-", "ci_X", "[", "i", ",", "j", "]", ")", "*", "ntrials", ")", "Phigh", "[", "i", ",", "j", "]", "=", "beta", ".", "ppf", "(", "ci_high", ",", "a", "=", "ci_X", "[", "i", ",", "j", "]", "*", "ntrials", ",", "b", "=", "(", "1", "-", "ci_X", "[", "i", ",", "j", "]", ")", "*", "ntrials", ")", "return", "[", "Plow", ",", "Phigh", "]" ]
Compute confidence intervals of beta distributions. Parameters ---------- ci_X : numpy.array Computed confidence interval estimate from `ntrials` experiments ntrials : int The number of trials that were run. ci : float, optional, default=0.95 Confidence interval to report (e.g. 0.95 for 95% confidence interval) Returns ------- Plow : float The lower bound of the symmetric confidence interval. Phigh : float The upper bound of the symmetric confidence interval. Examples -------- >>> ci_X = np.random.rand(10,10) >>> ntrials = 100 >>> [Plow, Phigh] = beta_confidence_intervals(ci_X, ntrials)
[ "Compute", "confidence", "intervals", "of", "beta", "distributions", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/analysis.py#L23-L64
bhmm/bhmm
bhmm/util/analysis.py
empirical_confidence_interval
def empirical_confidence_interval(sample, interval=0.95): """ Compute specified symmetric confidence interval for empirical sample. Parameters ---------- sample : numpy.array The empirical samples. interval : float, optional, default=0.95 Size of desired symmetric confidence interval (0 < interval < 1) e.g. 0.68 for 68% confidence interval, 0.95 for 95% confidence interval Returns ------- low : float The lower bound of the symmetric confidence interval. high : float The upper bound of the symmetric confidence interval. Examples -------- >>> sample = np.random.randn(1000) >>> [low, high] = empirical_confidence_interval(sample) >>> [low, high] = empirical_confidence_interval(sample, interval=0.65) >>> [low, high] = empirical_confidence_interval(sample, interval=0.99) """ # 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 = sample[low_index] high = sample[high_index] return [low, high]
python
def empirical_confidence_interval(sample, interval=0.95): """ Compute specified symmetric confidence interval for empirical sample. Parameters ---------- sample : numpy.array The empirical samples. interval : float, optional, default=0.95 Size of desired symmetric confidence interval (0 < interval < 1) e.g. 0.68 for 68% confidence interval, 0.95 for 95% confidence interval Returns ------- low : float The lower bound of the symmetric confidence interval. high : float The upper bound of the symmetric confidence interval. Examples -------- >>> sample = np.random.randn(1000) >>> [low, high] = empirical_confidence_interval(sample) >>> [low, high] = empirical_confidence_interval(sample, interval=0.65) >>> [low, high] = empirical_confidence_interval(sample, interval=0.99) """ # 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 = sample[low_index] high = sample[high_index] return [low, high]
[ "def", "empirical_confidence_interval", "(", "sample", ",", "interval", "=", "0.95", ")", ":", "# 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", "=", "sample", "[", "low_index", "]", "high", "=", "sample", "[", "high_index", "]", "return", "[", "low", ",", "high", "]" ]
Compute specified symmetric confidence interval for empirical sample. Parameters ---------- sample : numpy.array The empirical samples. interval : float, optional, default=0.95 Size of desired symmetric confidence interval (0 < interval < 1) e.g. 0.68 for 68% confidence interval, 0.95 for 95% confidence interval Returns ------- low : float The lower bound of the symmetric confidence interval. high : float The upper bound of the symmetric confidence interval. Examples -------- >>> sample = np.random.randn(1000) >>> [low, high] = empirical_confidence_interval(sample) >>> [low, high] = empirical_confidence_interval(sample, interval=0.65) >>> [low, high] = empirical_confidence_interval(sample, interval=0.99)
[ "Compute", "specified", "symmetric", "confidence", "interval", "for", "empirical", "sample", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/analysis.py#L67-L110
bhmm/bhmm
bhmm/util/analysis.py
generate_latex_table
def generate_latex_table(sampled_hmm, conf=0.95, dt=1, time_unit='ms', obs_name='force', obs_units='pN', caption='', outfile=None): """ Generate a LaTeX column-wide table showing various computed properties and uncertainties. Parameters ---------- conf : float confidence interval. Use 0.68 for 1 sigma, 0.95 for 2 sigma etc. """ # check input from bhmm.hmm.generic_sampled_hmm import SampledHMM from bhmm.hmm.gaussian_hmm import SampledGaussianHMM assert issubclass(sampled_hmm.__class__, SampledHMM), 'sampled_hmm ist not a SampledHMM' # confidence interval sampled_hmm.set_confidence(conf) # dt dt = float(dt) # nstates nstates = sampled_hmm.nstates table = """ \\begin{table} \\begin{tabular*}{\columnwidth}{@{\extracolsep{\\fill}}lcc} \hline {\\bf Property} & {\\bf Symbol} & {\\bf Value} \\\\ \hline """ # Stationary probability. p = sampled_hmm.stationary_distribution_mean p_lo, p_hi = sampled_hmm.stationary_distribution_conf for i in range(nstates): if i == 0: table += '\t\tEquilibrium probability ' table += '\t\t& $\pi_{%d}$ & $%0.3f_{\:%0.3f}^{\:%0.3f}$ \\\\' % (i+1, p[i], p_lo[i], p_hi[i]) + '\n' table += '\t\t\hline' + '\n' # Transition probabilities. P = sampled_hmm.transition_matrix_mean P_lo, P_hi = sampled_hmm.transition_matrix_conf for i in range(nstates): for j in range(nstates): if i == 0 and j == 0: table += '\t\tTransition probability ($\Delta t = $%s) ' % (str(dt)+' '+time_unit) table += '\t\t& $T_{%d%d}$ & $%0.4f_{\:%0.4f}^{\:%0.4f}$ \\\\' % (i+1, j+1, P[i, j], P_lo[i, j], P_hi[i, j]) + '\n' table += '\t\t\hline' + '\n' table += '\t\t\hline' + '\n' # Transition rates via pseudogenerator. K = P - np.eye(sampled_hmm.nstates) K /= dt K_lo = P_lo - np.eye(sampled_hmm.nstates) K_lo /= dt K_hi = P_hi - np.eye(sampled_hmm.nstates) K_hi /= dt for i in range(nstates): for j in range(nstates): if i == 0 and j == 0: table += '\t\tTransition rate (%s$^{-1}$) ' % time_unit if i != j: table += '\t\t& $k_{%d%d}$ & $%2.4f_{\:%2.4f}^{\:%2.4f}$ \\\\' % (i+1, j+1, K[i, j], K_lo[i, j], K_hi[i, j]) + '\n' table += '\t\t\hline' + '\n' # State mean lifetimes. l = sampled_hmm.lifetimes_mean l *= dt l_lo, l_hi = sampled_hmm.lifetimes_conf l_lo *= dt l_hi *= dt for i in range(nstates): if i == 0: table += '\t\tState mean lifetime (%s) ' % time_unit table += '\t\t& $t_{%d}$ & $%.3f_{\:%.3f}^{\:%.3f}$ \\\\' % (i+1, l[i], l_lo[i], l_hi[i]) + '\n' table += '\t\t\hline' + '\n' # State relaxation timescales. t = sampled_hmm.timescales_mean t *= dt t_lo, t_hi = sampled_hmm.timescales_conf t_lo *= dt t_hi *= dt for i in range(nstates-1): if i == 0: table += '\t\tRelaxation time (%s) ' % time_unit table += '\t\t& $\\tau_{%d}$ & $%.3f_{\:%.3f}^{\:%.3f}$ \\\\' % (i+1, t[i], t_lo[i], t_hi[i]) + '\n' table += '\t\t\hline' + '\n' if issubclass(sampled_hmm.__class__, SampledGaussianHMM): table += '\t\t\hline' + '\n' # State mean forces. m = sampled_hmm.means_mean m_lo, m_hi = sampled_hmm.means_conf for i in range(nstates): if i == 0: table += '\t\tState %s mean (%s) ' % (obs_name, obs_units) table += '\t\t& $\mu_{%d}$ & $%.3f_{\:%.3f}^{\:%.3f}$ \\\\' % (i+1, m[i], m_lo[i], m_hi[i]) + '\n' table += '\t\t\hline' + '\n' # State force standard deviations. s = sampled_hmm.sigmas_mean s_lo, s_hi = sampled_hmm.sigmas_conf for i in range(nstates): if i == 0: table += '\t\tState %s std dev (%s) ' % (obs_name, obs_units) table += '\t\t& $s_{%d}$ & $%.3f_{\:%.3f}^{\:%.3f}$ \\\\' % (i+1, s[i], s_lo[i], s_hi[i]) + '\n' table += '\t\t\hline' + '\n' table += """ \\hline \\end{tabular*} \\caption{{\\bf %s}} \\end{table} """ % caption # write to file if wanted: if outfile is not None: f = open(outfile, 'w') f.write(table) f.close() return table
python
def generate_latex_table(sampled_hmm, conf=0.95, dt=1, time_unit='ms', obs_name='force', obs_units='pN', caption='', outfile=None): """ Generate a LaTeX column-wide table showing various computed properties and uncertainties. Parameters ---------- conf : float confidence interval. Use 0.68 for 1 sigma, 0.95 for 2 sigma etc. """ # check input from bhmm.hmm.generic_sampled_hmm import SampledHMM from bhmm.hmm.gaussian_hmm import SampledGaussianHMM assert issubclass(sampled_hmm.__class__, SampledHMM), 'sampled_hmm ist not a SampledHMM' # confidence interval sampled_hmm.set_confidence(conf) # dt dt = float(dt) # nstates nstates = sampled_hmm.nstates table = """ \\begin{table} \\begin{tabular*}{\columnwidth}{@{\extracolsep{\\fill}}lcc} \hline {\\bf Property} & {\\bf Symbol} & {\\bf Value} \\\\ \hline """ # Stationary probability. p = sampled_hmm.stationary_distribution_mean p_lo, p_hi = sampled_hmm.stationary_distribution_conf for i in range(nstates): if i == 0: table += '\t\tEquilibrium probability ' table += '\t\t& $\pi_{%d}$ & $%0.3f_{\:%0.3f}^{\:%0.3f}$ \\\\' % (i+1, p[i], p_lo[i], p_hi[i]) + '\n' table += '\t\t\hline' + '\n' # Transition probabilities. P = sampled_hmm.transition_matrix_mean P_lo, P_hi = sampled_hmm.transition_matrix_conf for i in range(nstates): for j in range(nstates): if i == 0 and j == 0: table += '\t\tTransition probability ($\Delta t = $%s) ' % (str(dt)+' '+time_unit) table += '\t\t& $T_{%d%d}$ & $%0.4f_{\:%0.4f}^{\:%0.4f}$ \\\\' % (i+1, j+1, P[i, j], P_lo[i, j], P_hi[i, j]) + '\n' table += '\t\t\hline' + '\n' table += '\t\t\hline' + '\n' # Transition rates via pseudogenerator. K = P - np.eye(sampled_hmm.nstates) K /= dt K_lo = P_lo - np.eye(sampled_hmm.nstates) K_lo /= dt K_hi = P_hi - np.eye(sampled_hmm.nstates) K_hi /= dt for i in range(nstates): for j in range(nstates): if i == 0 and j == 0: table += '\t\tTransition rate (%s$^{-1}$) ' % time_unit if i != j: table += '\t\t& $k_{%d%d}$ & $%2.4f_{\:%2.4f}^{\:%2.4f}$ \\\\' % (i+1, j+1, K[i, j], K_lo[i, j], K_hi[i, j]) + '\n' table += '\t\t\hline' + '\n' # State mean lifetimes. l = sampled_hmm.lifetimes_mean l *= dt l_lo, l_hi = sampled_hmm.lifetimes_conf l_lo *= dt l_hi *= dt for i in range(nstates): if i == 0: table += '\t\tState mean lifetime (%s) ' % time_unit table += '\t\t& $t_{%d}$ & $%.3f_{\:%.3f}^{\:%.3f}$ \\\\' % (i+1, l[i], l_lo[i], l_hi[i]) + '\n' table += '\t\t\hline' + '\n' # State relaxation timescales. t = sampled_hmm.timescales_mean t *= dt t_lo, t_hi = sampled_hmm.timescales_conf t_lo *= dt t_hi *= dt for i in range(nstates-1): if i == 0: table += '\t\tRelaxation time (%s) ' % time_unit table += '\t\t& $\\tau_{%d}$ & $%.3f_{\:%.3f}^{\:%.3f}$ \\\\' % (i+1, t[i], t_lo[i], t_hi[i]) + '\n' table += '\t\t\hline' + '\n' if issubclass(sampled_hmm.__class__, SampledGaussianHMM): table += '\t\t\hline' + '\n' # State mean forces. m = sampled_hmm.means_mean m_lo, m_hi = sampled_hmm.means_conf for i in range(nstates): if i == 0: table += '\t\tState %s mean (%s) ' % (obs_name, obs_units) table += '\t\t& $\mu_{%d}$ & $%.3f_{\:%.3f}^{\:%.3f}$ \\\\' % (i+1, m[i], m_lo[i], m_hi[i]) + '\n' table += '\t\t\hline' + '\n' # State force standard deviations. s = sampled_hmm.sigmas_mean s_lo, s_hi = sampled_hmm.sigmas_conf for i in range(nstates): if i == 0: table += '\t\tState %s std dev (%s) ' % (obs_name, obs_units) table += '\t\t& $s_{%d}$ & $%.3f_{\:%.3f}^{\:%.3f}$ \\\\' % (i+1, s[i], s_lo[i], s_hi[i]) + '\n' table += '\t\t\hline' + '\n' table += """ \\hline \\end{tabular*} \\caption{{\\bf %s}} \\end{table} """ % caption # write to file if wanted: if outfile is not None: f = open(outfile, 'w') f.write(table) f.close() return table
[ "def", "generate_latex_table", "(", "sampled_hmm", ",", "conf", "=", "0.95", ",", "dt", "=", "1", ",", "time_unit", "=", "'ms'", ",", "obs_name", "=", "'force'", ",", "obs_units", "=", "'pN'", ",", "caption", "=", "''", ",", "outfile", "=", "None", ")", ":", "# check input", "from", "bhmm", ".", "hmm", ".", "generic_sampled_hmm", "import", "SampledHMM", "from", "bhmm", ".", "hmm", ".", "gaussian_hmm", "import", "SampledGaussianHMM", "assert", "issubclass", "(", "sampled_hmm", ".", "__class__", ",", "SampledHMM", ")", ",", "'sampled_hmm ist not a SampledHMM'", "# confidence interval", "sampled_hmm", ".", "set_confidence", "(", "conf", ")", "# dt", "dt", "=", "float", "(", "dt", ")", "# nstates", "nstates", "=", "sampled_hmm", ".", "nstates", "table", "=", "\"\"\"\n\\\\begin{table}\n \\\\begin{tabular*}{\\columnwidth}{@{\\extracolsep{\\\\fill}}lcc}\n \\hline\n {\\\\bf Property} & {\\\\bf Symbol} & {\\\\bf Value} \\\\\\\\\n \\hline\n \"\"\"", "# Stationary probability.", "p", "=", "sampled_hmm", ".", "stationary_distribution_mean", "p_lo", ",", "p_hi", "=", "sampled_hmm", ".", "stationary_distribution_conf", "for", "i", "in", "range", "(", "nstates", ")", ":", "if", "i", "==", "0", ":", "table", "+=", "'\\t\\tEquilibrium probability '", "table", "+=", "'\\t\\t& $\\pi_{%d}$ & $%0.3f_{\\:%0.3f}^{\\:%0.3f}$ \\\\\\\\'", "%", "(", "i", "+", "1", ",", "p", "[", "i", "]", ",", "p_lo", "[", "i", "]", ",", "p_hi", "[", "i", "]", ")", "+", "'\\n'", "table", "+=", "'\\t\\t\\hline'", "+", "'\\n'", "# Transition probabilities.", "P", "=", "sampled_hmm", ".", "transition_matrix_mean", "P_lo", ",", "P_hi", "=", "sampled_hmm", ".", "transition_matrix_conf", "for", "i", "in", "range", "(", "nstates", ")", ":", "for", "j", "in", "range", "(", "nstates", ")", ":", "if", "i", "==", "0", "and", "j", "==", "0", ":", "table", "+=", "'\\t\\tTransition probability ($\\Delta t = $%s) '", "%", "(", "str", "(", "dt", ")", "+", "' '", "+", "time_unit", ")", "table", "+=", "'\\t\\t& $T_{%d%d}$ & $%0.4f_{\\:%0.4f}^{\\:%0.4f}$ \\\\\\\\'", "%", "(", "i", "+", "1", ",", "j", "+", "1", ",", "P", "[", "i", ",", "j", "]", ",", "P_lo", "[", "i", ",", "j", "]", ",", "P_hi", "[", "i", ",", "j", "]", ")", "+", "'\\n'", "table", "+=", "'\\t\\t\\hline'", "+", "'\\n'", "table", "+=", "'\\t\\t\\hline'", "+", "'\\n'", "# Transition rates via pseudogenerator.", "K", "=", "P", "-", "np", ".", "eye", "(", "sampled_hmm", ".", "nstates", ")", "K", "/=", "dt", "K_lo", "=", "P_lo", "-", "np", ".", "eye", "(", "sampled_hmm", ".", "nstates", ")", "K_lo", "/=", "dt", "K_hi", "=", "P_hi", "-", "np", ".", "eye", "(", "sampled_hmm", ".", "nstates", ")", "K_hi", "/=", "dt", "for", "i", "in", "range", "(", "nstates", ")", ":", "for", "j", "in", "range", "(", "nstates", ")", ":", "if", "i", "==", "0", "and", "j", "==", "0", ":", "table", "+=", "'\\t\\tTransition rate (%s$^{-1}$) '", "%", "time_unit", "if", "i", "!=", "j", ":", "table", "+=", "'\\t\\t& $k_{%d%d}$ & $%2.4f_{\\:%2.4f}^{\\:%2.4f}$ \\\\\\\\'", "%", "(", "i", "+", "1", ",", "j", "+", "1", ",", "K", "[", "i", ",", "j", "]", ",", "K_lo", "[", "i", ",", "j", "]", ",", "K_hi", "[", "i", ",", "j", "]", ")", "+", "'\\n'", "table", "+=", "'\\t\\t\\hline'", "+", "'\\n'", "# State mean lifetimes.", "l", "=", "sampled_hmm", ".", "lifetimes_mean", "l", "*=", "dt", "l_lo", ",", "l_hi", "=", "sampled_hmm", ".", "lifetimes_conf", "l_lo", "*=", "dt", "l_hi", "*=", "dt", "for", "i", "in", "range", "(", "nstates", ")", ":", "if", "i", "==", "0", ":", "table", "+=", "'\\t\\tState mean lifetime (%s) '", "%", "time_unit", "table", "+=", "'\\t\\t& $t_{%d}$ & $%.3f_{\\:%.3f}^{\\:%.3f}$ \\\\\\\\'", "%", "(", "i", "+", "1", ",", "l", "[", "i", "]", ",", "l_lo", "[", "i", "]", ",", "l_hi", "[", "i", "]", ")", "+", "'\\n'", "table", "+=", "'\\t\\t\\hline'", "+", "'\\n'", "# State relaxation timescales.", "t", "=", "sampled_hmm", ".", "timescales_mean", "t", "*=", "dt", "t_lo", ",", "t_hi", "=", "sampled_hmm", ".", "timescales_conf", "t_lo", "*=", "dt", "t_hi", "*=", "dt", "for", "i", "in", "range", "(", "nstates", "-", "1", ")", ":", "if", "i", "==", "0", ":", "table", "+=", "'\\t\\tRelaxation time (%s) '", "%", "time_unit", "table", "+=", "'\\t\\t& $\\\\tau_{%d}$ & $%.3f_{\\:%.3f}^{\\:%.3f}$ \\\\\\\\'", "%", "(", "i", "+", "1", ",", "t", "[", "i", "]", ",", "t_lo", "[", "i", "]", ",", "t_hi", "[", "i", "]", ")", "+", "'\\n'", "table", "+=", "'\\t\\t\\hline'", "+", "'\\n'", "if", "issubclass", "(", "sampled_hmm", ".", "__class__", ",", "SampledGaussianHMM", ")", ":", "table", "+=", "'\\t\\t\\hline'", "+", "'\\n'", "# State mean forces.", "m", "=", "sampled_hmm", ".", "means_mean", "m_lo", ",", "m_hi", "=", "sampled_hmm", ".", "means_conf", "for", "i", "in", "range", "(", "nstates", ")", ":", "if", "i", "==", "0", ":", "table", "+=", "'\\t\\tState %s mean (%s) '", "%", "(", "obs_name", ",", "obs_units", ")", "table", "+=", "'\\t\\t& $\\mu_{%d}$ & $%.3f_{\\:%.3f}^{\\:%.3f}$ \\\\\\\\'", "%", "(", "i", "+", "1", ",", "m", "[", "i", "]", ",", "m_lo", "[", "i", "]", ",", "m_hi", "[", "i", "]", ")", "+", "'\\n'", "table", "+=", "'\\t\\t\\hline'", "+", "'\\n'", "# State force standard deviations.", "s", "=", "sampled_hmm", ".", "sigmas_mean", "s_lo", ",", "s_hi", "=", "sampled_hmm", ".", "sigmas_conf", "for", "i", "in", "range", "(", "nstates", ")", ":", "if", "i", "==", "0", ":", "table", "+=", "'\\t\\tState %s std dev (%s) '", "%", "(", "obs_name", ",", "obs_units", ")", "table", "+=", "'\\t\\t& $s_{%d}$ & $%.3f_{\\:%.3f}^{\\:%.3f}$ \\\\\\\\'", "%", "(", "i", "+", "1", ",", "s", "[", "i", "]", ",", "s_lo", "[", "i", "]", ",", "s_hi", "[", "i", "]", ")", "+", "'\\n'", "table", "+=", "'\\t\\t\\hline'", "+", "'\\n'", "table", "+=", "\"\"\"\n \\\\hline\n \\\\end{tabular*}\n \\\\caption{{\\\\bf %s}}\n\\\\end{table}\n \"\"\"", "%", "caption", "# write to file if wanted:", "if", "outfile", "is", "not", "None", ":", "f", "=", "open", "(", "outfile", ",", "'w'", ")", "f", ".", "write", "(", "table", ")", "f", ".", "close", "(", ")", "return", "table" ]
Generate a LaTeX column-wide table showing various computed properties and uncertainties. Parameters ---------- conf : float confidence interval. Use 0.68 for 1 sigma, 0.95 for 2 sigma etc.
[ "Generate", "a", "LaTeX", "column", "-", "wide", "table", "showing", "various", "computed", "properties", "and", "uncertainties", "." ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/analysis.py#L113-L236
bhmm/bhmm
bhmm/util/statistics.py
confidence_interval
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 alpha : float in [0,1] the confidence level, i.e. percentage of data included in the interval Returns ------- [m,l,r] where m is the mean of the data, and (l,r) are the m-alpha/2 and m+alpha/2 confidence interval boundaries. """ 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: pm = (im-1) + (m-sdata[im-1]) / (sdata[im]-sdata[im-1]) # left interval boundary pl = pm - alpha * pm il1 = max(0, int(math.floor(pl))) il2 = min(len(sdata)-1, int(math.ceil(pl))) l = sdata[il1] + (pl - il1)*(sdata[il2] - sdata[il1]) # right interval boundary pr = pm + alpha * (len(data)-im) ir1 = max(0, int(math.floor(pr))) ir2 = min(len(sdata)-1, int(math.ceil(pr))) r = sdata[ir1] + (pr - ir1)*(sdata[ir2] - sdata[ir1]) # return return m, l, r
python
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 alpha : float in [0,1] the confidence level, i.e. percentage of data included in the interval Returns ------- [m,l,r] where m is the mean of the data, and (l,r) are the m-alpha/2 and m+alpha/2 confidence interval boundaries. """ 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: pm = (im-1) + (m-sdata[im-1]) / (sdata[im]-sdata[im-1]) # left interval boundary pl = pm - alpha * pm il1 = max(0, int(math.floor(pl))) il2 = min(len(sdata)-1, int(math.ceil(pl))) l = sdata[il1] + (pl - il1)*(sdata[il2] - sdata[il1]) # right interval boundary pr = pm + alpha * (len(data)-im) ir1 = max(0, int(math.floor(pr))) ir2 = min(len(sdata)-1, int(math.ceil(pr))) r = sdata[ir1] + (pr - ir1)*(sdata[ir2] - sdata[ir1]) # return return m, l, r
[ "def", "confidence_interval", "(", "data", ",", "alpha", ")", ":", "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", ":", "pm", "=", "(", "im", "-", "1", ")", "+", "(", "m", "-", "sdata", "[", "im", "-", "1", "]", ")", "/", "(", "sdata", "[", "im", "]", "-", "sdata", "[", "im", "-", "1", "]", ")", "# left interval boundary", "pl", "=", "pm", "-", "alpha", "*", "pm", "il1", "=", "max", "(", "0", ",", "int", "(", "math", ".", "floor", "(", "pl", ")", ")", ")", "il2", "=", "min", "(", "len", "(", "sdata", ")", "-", "1", ",", "int", "(", "math", ".", "ceil", "(", "pl", ")", ")", ")", "l", "=", "sdata", "[", "il1", "]", "+", "(", "pl", "-", "il1", ")", "*", "(", "sdata", "[", "il2", "]", "-", "sdata", "[", "il1", "]", ")", "# right interval boundary", "pr", "=", "pm", "+", "alpha", "*", "(", "len", "(", "data", ")", "-", "im", ")", "ir1", "=", "max", "(", "0", ",", "int", "(", "math", ".", "floor", "(", "pr", ")", ")", ")", "ir2", "=", "min", "(", "len", "(", "sdata", ")", "-", "1", ",", "int", "(", "math", ".", "ceil", "(", "pr", ")", ")", ")", "r", "=", "sdata", "[", "ir1", "]", "+", "(", "pr", "-", "ir1", ")", "*", "(", "sdata", "[", "ir2", "]", "-", "sdata", "[", "ir1", "]", ")", "# return", "return", "m", ",", "l", ",", "r" ]
Computes the mean and alpha-confidence interval of the given sample set Parameters ---------- data : ndarray a 1D-array of samples alpha : float in [0,1] the confidence level, i.e. percentage of data included in the interval Returns ------- [m,l,r] where m is the mean of the data, and (l,r) are the m-alpha/2 and m+alpha/2 confidence interval boundaries.
[ "Computes", "the", "mean", "and", "alpha", "-", "confidence", "interval", "of", "the", "given", "sample", "set" ]
train
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/statistics.py#L34-L75