repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
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", ".", "...
r""" Samples of the timescales
[ "r", "Samples", "of", "the", "timescales" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_sampled_hmm.py#L231-L236
train
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'", ":", "sel...
Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"]
[ "Sets", "the", "implementation", "of", "this", "module" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/outputmodel.py#L69-L86
train
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", ":", ...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/outputmodel.py#L93-L117
train
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", "."...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/outputmodel.py#L119-L131
train
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", "]...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/impl_python/hidden.py#L33-L96
train
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 ...
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!" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/impl_python/hidden.py#L99-L148
train
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", ".", "sh...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/impl_python/hidden.py#L151-L204
train
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", "=", "...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/impl_python/hidden.py#L207-L247
train
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", "."...
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",...
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/impl_python/hidden.py#L250-L285
train
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",...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/discrete.py#L26-L57
train
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", ...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/discrete.py#L60-L116
train
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...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/discrete.py#L119-L164
train
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", ",", "separat...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/discrete.py#L167-L338
train
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", ...
Initializes discrete HMM using maximum likelihood of observation counts
[ "Initializes", "discrete", "HMM", "using", "maximum", "likelihood", "of", "observation", "counts" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/init/discrete.py#L342-L345
train
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_trans...
r""" Updates the transition matrix and recomputes all derived quantities
[ "r", "Updates", "the", "transition", "matrix", "and", "recomputes", "all", "derived", "quantities" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L79-L93
train
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", ".", ...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L167-L172
train
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", "m...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L185-L196
train
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", "(...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L243-L258
train
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L261-L272
train
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...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L274-L295
train
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 stat...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L297-L319
train
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", ...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L321-L334
train
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 ...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L398-L431
train
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", ...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L433-L479
train
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", "=",...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L506-L545
train
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...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/generic_hmm.py#L547-L589
train
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/docs/sphinxext/notebook_sphinxext.py#L107-L111
train
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", ".", "sp...
convert notebook to html
[ "convert", "notebook", "to", "html" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/docs/sphinxext/notebook_sphinxext.py#L113-L143
train
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", ...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L130-L157
train
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", ".", ...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L159-L215
train
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", ...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L217-L251
train
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", "(...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L253-L283
train
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", ")",...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L285-L315
train
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",...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/output_models/discrete.py#L317-L378
train
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_...
Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"]
[ "Sets", "the", "implementation", "of", "this", "module" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L44-L62
train
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", "=", ...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L65-L96
train
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", ...
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!" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L99-L125
train
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_si...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L133-L188
train
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L191-L211
train
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",...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L214-L248
train
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__", "=="...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L251-L274
train
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", ...
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", ")" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hidden/api.py#L277-L302
train
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...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/logger.py#L25-L50
train
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", ...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L206-L263
train
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", "(", ")", "fina...
Update the current model using one round of Gibbs sampling.
[ "Update", "the", "current", "model", "using", "one", "round", "of", "Gibbs", "sampling", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L265-L277
train
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", ...
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", ")" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L279-L287
train
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",...
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", ")" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L289-L327
train
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", ".", "...
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", ")" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L329-L335
train
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", ".", "rever...
Updates the hidden-state transition matrix and the initial distribution
[ "Updates", "the", "hidden", "-", "state", "transition", "matrix", "and", "the", "initial", "distribution" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L337-L369
train
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", "MaximumLikelihood...
Initialize using an MLHMM.
[ "Initialize", "using", "an", "MLHMM", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/bayesian_sampling.py#L371-L380
train
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", ":", ...
r"""Makes sure that dtraj is a discrete trajectory (array of int)
[ "r", "Makes", "sure", "that", "dtraj", "is", "a", "discrete", "trajectory", "(", "array", "of", "int", ")" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/types.py#L160-L169
train
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", ",",...
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", ")" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/types.py#L172-L185
train
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", "(", ...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L28-L43
train
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",...
Computes the strongly connected closed sets of C
[ "Computes", "the", "strongly", "connected", "closed", "sets", "of", "C" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L46-L56
train
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", "....
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L59-L65
train
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", ...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L68-L123
train
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", ")", "# cons...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L126-L190
train
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 separa...
Enforces transition matrix P to be reversible on its closed sets.
[ "Enforces", "transition", "matrix", "P", "to", "be", "reversible", "on", "its", "closed", "sets", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L193-L209
train
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", ...
Returns if P is reversible on its weakly connected sets
[ "Returns", "if", "P", "is", "reversible", "on", "its", "weakly", "connected", "sets" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L212-L226
train
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", ".", "station...
Simple estimator for stationary distribution for multiple strongly connected sets
[ "Simple", "estimator", "for", "stationary", "distribution", "for", "multiple", "strongly", "connected", "sets" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/estimators/_tmatrix_disconnected.py#L229-L251
train
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", "...
r""" Samples of the Gaussian distribution means
[ "r", "Samples", "of", "the", "Gaussian", "distribution", "means" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/gaussian_hmm.py#L67-L73
train
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", ...
r""" Samples of the Gaussian distribution standard deviations
[ "r", "Samples", "of", "the", "Gaussian", "distribution", "standard", "deviations" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/hmm/gaussian_hmm.py#L91-L97
train
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", "_typ...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L23-L67
train
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...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L70-L94
train
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...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L97-L127
train
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", "out...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L130-L158
train
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", "(", "...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L161-L199
train
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", "(", ...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L202-L227
train
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", "...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L231-L305
train
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", "=...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L309-L372
train
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", ...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/api.py#L375-L470
train
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", "(", ...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/utils.py#L112-L135
train
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...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/utils.py#L137-L199
train
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", "=", "Fal...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/_external/sklearn/utils.py#L229-L329
train
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 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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/analysis.py#L23-L64
train
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 l...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/analysis.py#L67-L110
train
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", ")"...
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", "." ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/analysis.py#L113-L236
train
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", "=", "...
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" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/statistics.py#L34-L75
train
bhmm/bhmm
bhmm/util/statistics.py
confidence_interval_arr
def confidence_interval_arr(data, conf=0.95): r""" Computes element-wise confidence intervals from a sample of ndarrays Given a sample of arbitrarily shaped ndarrays, computes element-wise confidence intervals Parameters ---------- data : ndarray (K, (shape)) ndarray of ndarrays, the first index is a sample index, the remaining indexes are specific to the array of interest conf : float, optional, default = 0.95 confidence interval Return ------ lower : ndarray(shape) element-wise lower bounds upper : ndarray(shape) element-wise upper bounds """ if conf < 0 or conf > 1: raise ValueError('Not a meaningful confidence level: '+str(conf)) # list or 1D-array? then fuse it if types.is_list(data) or (isinstance(data, np.ndarray) and np.ndim(data) == 1): newshape = tuple([len(data)] + list(data[0].shape)) newdata = np.zeros(newshape) for i in range(len(data)): newdata[i, :] = data[i] data = newdata # do we have an array now? if yes go, if no fail if types.is_float_array(data): I = _indexes(data[0]) lower = np.zeros(data[0].shape) upper = np.zeros(data[0].shape) for i in I: col = _column(data, i) m, lower[i], upper[i] = confidence_interval(col, conf) # return return lower, upper else: raise TypeError('data cannot be converted to an ndarray')
python
def confidence_interval_arr(data, conf=0.95): r""" Computes element-wise confidence intervals from a sample of ndarrays Given a sample of arbitrarily shaped ndarrays, computes element-wise confidence intervals Parameters ---------- data : ndarray (K, (shape)) ndarray of ndarrays, the first index is a sample index, the remaining indexes are specific to the array of interest conf : float, optional, default = 0.95 confidence interval Return ------ lower : ndarray(shape) element-wise lower bounds upper : ndarray(shape) element-wise upper bounds """ if conf < 0 or conf > 1: raise ValueError('Not a meaningful confidence level: '+str(conf)) # list or 1D-array? then fuse it if types.is_list(data) or (isinstance(data, np.ndarray) and np.ndim(data) == 1): newshape = tuple([len(data)] + list(data[0].shape)) newdata = np.zeros(newshape) for i in range(len(data)): newdata[i, :] = data[i] data = newdata # do we have an array now? if yes go, if no fail if types.is_float_array(data): I = _indexes(data[0]) lower = np.zeros(data[0].shape) upper = np.zeros(data[0].shape) for i in I: col = _column(data, i) m, lower[i], upper[i] = confidence_interval(col, conf) # return return lower, upper else: raise TypeError('data cannot be converted to an ndarray')
[ "def", "confidence_interval_arr", "(", "data", ",", "conf", "=", "0.95", ")", ":", "if", "conf", "<", "0", "or", "conf", ">", "1", ":", "raise", "ValueError", "(", "'Not a meaningful confidence level: '", "+", "str", "(", "conf", ")", ")", "# list or 1D-arra...
r""" Computes element-wise confidence intervals from a sample of ndarrays Given a sample of arbitrarily shaped ndarrays, computes element-wise confidence intervals Parameters ---------- data : ndarray (K, (shape)) ndarray of ndarrays, the first index is a sample index, the remaining indexes are specific to the array of interest conf : float, optional, default = 0.95 confidence interval Return ------ lower : ndarray(shape) element-wise lower bounds upper : ndarray(shape) element-wise upper bounds
[ "r", "Computes", "element", "-", "wise", "confidence", "intervals", "from", "a", "sample", "of", "ndarrays" ]
9804d18c2ddb684fb4d90b544cc209617a89ca9a
https://github.com/bhmm/bhmm/blob/9804d18c2ddb684fb4d90b544cc209617a89ca9a/bhmm/util/statistics.py#L108-L151
train
adobe-apiplatform/umapi-client.py
umapi_client/connection.py
Connection.status
def status(self, remote=False): """ Return the connection status, both locally and remotely. The local connection status is a dictionary that gives: * the count of multiple queries sent to the server. * the count of single queries sent to the server. * the count of actions sent to the server. * the count of actions executed successfully by the server. * the count of actions queued to go to the server. The remote connection status includes whether the server is live, as well as data about version and build. The server data is cached, unless the remote flag is specified. :param remote: whether to query the server for its latest status :return: tuple of status dicts: (local, server). """ if remote: components = urlparse.urlparse(self.endpoint) try: result = self.session.get(components[0] + "://" + components[1] + "/status", timeout=self.timeout) except Exception as e: if self.logger: self.logger.debug("Failed to connect to server for status: %s", e) result = None if result and result.status_code == 200: self.server_status = result.json() self.server_status["endpoint"] = self.endpoint elif result: if self.logger: self.logger.debug("Server status response not understandable: Status: %d, Body: %s", result.status_code, result.text) self.server_status = {"endpoint": self.endpoint, "status": ("Unexpected HTTP status " + str(result.status_code) + " at: " + strftime("%d %b %Y %H:%M:%S +0000", gmtime()))} else: self.server_status = {"endpoint": self.endpoint, "status": "Unreachable at: " + strftime("%d %b %Y %H:%M:%S +0000", gmtime())} return self.local_status, self.server_status
python
def status(self, remote=False): """ Return the connection status, both locally and remotely. The local connection status is a dictionary that gives: * the count of multiple queries sent to the server. * the count of single queries sent to the server. * the count of actions sent to the server. * the count of actions executed successfully by the server. * the count of actions queued to go to the server. The remote connection status includes whether the server is live, as well as data about version and build. The server data is cached, unless the remote flag is specified. :param remote: whether to query the server for its latest status :return: tuple of status dicts: (local, server). """ if remote: components = urlparse.urlparse(self.endpoint) try: result = self.session.get(components[0] + "://" + components[1] + "/status", timeout=self.timeout) except Exception as e: if self.logger: self.logger.debug("Failed to connect to server for status: %s", e) result = None if result and result.status_code == 200: self.server_status = result.json() self.server_status["endpoint"] = self.endpoint elif result: if self.logger: self.logger.debug("Server status response not understandable: Status: %d, Body: %s", result.status_code, result.text) self.server_status = {"endpoint": self.endpoint, "status": ("Unexpected HTTP status " + str(result.status_code) + " at: " + strftime("%d %b %Y %H:%M:%S +0000", gmtime()))} else: self.server_status = {"endpoint": self.endpoint, "status": "Unreachable at: " + strftime("%d %b %Y %H:%M:%S +0000", gmtime())} return self.local_status, self.server_status
[ "def", "status", "(", "self", ",", "remote", "=", "False", ")", ":", "if", "remote", ":", "components", "=", "urlparse", ".", "urlparse", "(", "self", ".", "endpoint", ")", "try", ":", "result", "=", "self", ".", "session", ".", "get", "(", "componen...
Return the connection status, both locally and remotely. The local connection status is a dictionary that gives: * the count of multiple queries sent to the server. * the count of single queries sent to the server. * the count of actions sent to the server. * the count of actions executed successfully by the server. * the count of actions queued to go to the server. The remote connection status includes whether the server is live, as well as data about version and build. The server data is cached, unless the remote flag is specified. :param remote: whether to query the server for its latest status :return: tuple of status dicts: (local, server).
[ "Return", "the", "connection", "status", "both", "locally", "and", "remotely", "." ]
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/connection.py#L164-L201
train
adobe-apiplatform/umapi-client.py
umapi_client/connection.py
Connection.query_single
def query_single(self, object_type, url_params, query_params=None): # type: (str, list, dict) -> dict """ Query for a single object. :param object_type: string query type (e.g., "users" or "groups") :param url_params: required list of strings to provide as additional URL components :param query_params: optional dictionary of query options :return: the found object (a dictionary), which is empty if none were found """ # Server API convention (v2) is that the pluralized object type goes into the endpoint # but the object type is the key in the response dictionary for the returned object. self.local_status["single-query-count"] += 1 query_type = object_type + "s" # poor man's plural query_path = "/organizations/{}/{}".format(self.org_id, query_type) for component in url_params if url_params else []: query_path += "/" + urlparse.quote(component, safe='/@') if query_params: query_path += "?" + urlparse.urlencode(query_params) try: result = self.make_call(query_path) body = result.json() except RequestError as re: if re.result.status_code == 404: if self.logger: self.logger.debug("Ran %s query: %s %s (0 found)", object_type, url_params, query_params) return {} else: raise re if body.get("result") == "success": value = body.get(object_type, {}) if self.logger: self.logger.debug("Ran %s query: %s %s (1 found)", object_type, url_params, query_params) return value else: raise ClientError("OK status but no 'success' result", result)
python
def query_single(self, object_type, url_params, query_params=None): # type: (str, list, dict) -> dict """ Query for a single object. :param object_type: string query type (e.g., "users" or "groups") :param url_params: required list of strings to provide as additional URL components :param query_params: optional dictionary of query options :return: the found object (a dictionary), which is empty if none were found """ # Server API convention (v2) is that the pluralized object type goes into the endpoint # but the object type is the key in the response dictionary for the returned object. self.local_status["single-query-count"] += 1 query_type = object_type + "s" # poor man's plural query_path = "/organizations/{}/{}".format(self.org_id, query_type) for component in url_params if url_params else []: query_path += "/" + urlparse.quote(component, safe='/@') if query_params: query_path += "?" + urlparse.urlencode(query_params) try: result = self.make_call(query_path) body = result.json() except RequestError as re: if re.result.status_code == 404: if self.logger: self.logger.debug("Ran %s query: %s %s (0 found)", object_type, url_params, query_params) return {} else: raise re if body.get("result") == "success": value = body.get(object_type, {}) if self.logger: self.logger.debug("Ran %s query: %s %s (1 found)", object_type, url_params, query_params) return value else: raise ClientError("OK status but no 'success' result", result)
[ "def", "query_single", "(", "self", ",", "object_type", ",", "url_params", ",", "query_params", "=", "None", ")", ":", "# type: (str, list, dict) -> dict", "# Server API convention (v2) is that the pluralized object type goes into the endpoint", "# but the object type is the key in t...
Query for a single object. :param object_type: string query type (e.g., "users" or "groups") :param url_params: required list of strings to provide as additional URL components :param query_params: optional dictionary of query options :return: the found object (a dictionary), which is empty if none were found
[ "Query", "for", "a", "single", "object", ".", ":", "param", "object_type", ":", "string", "query", "type", "(", "e", ".", "g", ".", "users", "or", "groups", ")", ":", "param", "url_params", ":", "required", "list", "of", "strings", "to", "provide", "as...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/connection.py#L203-L235
train
adobe-apiplatform/umapi-client.py
umapi_client/connection.py
Connection.query_multiple
def query_multiple(self, object_type, page=0, url_params=None, query_params=None): # type: (str, int, list, dict) -> tuple """ Query for a page of objects. Defaults to the (0-based) first page. Sadly, the sort order is undetermined. :param object_type: string constant query type: either "user" or "group") :param page: numeric page (0-based) of results to get (up to 200 in a page) :param url_params: optional list of strings to provide as additional URL components :param query_params: optional dictionary of query options :return: tuple (list of returned dictionaries (one for each query result), bool for whether this is last page) """ # As of 2017-10-01, we are moving to to different URLs for user and user-group queries, # and these endpoints have different conventions for pagination. For the time being, # we are also preserving the more general "group" query capability. self.local_status["multiple-query-count"] += 1 if object_type in ("user", "group"): query_path = "/{}s/{}/{:d}".format(object_type, self.org_id, page) if url_params: query_path += "/" + "/".join([urlparse.quote(c) for c in url_params]) if query_params: query_path += "?" + urlparse.urlencode(query_params) elif object_type == "user-group": query_path = "/{}/user-groups".format(self.org_id) if url_params: query_path += "/" + "/".join([urlparse.quote(c) for c in url_params]) query_path += "?page={:d}".format(page+1) if query_params: query_path += "&" + urlparse.urlencode(query_params) else: raise ArgumentError("Unknown query object type ({}): must be 'user' or 'group'".format(object_type)) try: result = self.make_call(query_path) body = result.json() except RequestError as re: if re.result.status_code == 404: if self.logger: self.logger.debug("Ran %s query: %s %s (0 found)", object_type, url_params, query_params) return [], True else: raise re if object_type in ("user", "group"): if body.get("result") == "success": values = body.get(object_type + "s", []) last_page = body.get("lastPage", False) if self.logger: self.logger.debug("Ran multi-%s query: %s %s (page %d: %d found)", object_type, url_params, query_params, page, len(values)) return values, last_page else: raise ClientError("OK status but no 'success' result", result) elif object_type == "user-group": page_number = result.headers.get("X-Current-Page", "1") page_count = result.headers.get("X-Page-Count", "1") if self.logger: self.logger.debug("Ran multi-group query: %s %s (page %d: %d found)", url_params, query_params, page, len(body)) return body, int(page_number) >= int(page_count) else: # this would actually be caught above, but we use a parallel construction in both places # to make it easy to add query object types raise ArgumentError("Unknown query object type ({}): must be 'user' or 'group'".format(object_type))
python
def query_multiple(self, object_type, page=0, url_params=None, query_params=None): # type: (str, int, list, dict) -> tuple """ Query for a page of objects. Defaults to the (0-based) first page. Sadly, the sort order is undetermined. :param object_type: string constant query type: either "user" or "group") :param page: numeric page (0-based) of results to get (up to 200 in a page) :param url_params: optional list of strings to provide as additional URL components :param query_params: optional dictionary of query options :return: tuple (list of returned dictionaries (one for each query result), bool for whether this is last page) """ # As of 2017-10-01, we are moving to to different URLs for user and user-group queries, # and these endpoints have different conventions for pagination. For the time being, # we are also preserving the more general "group" query capability. self.local_status["multiple-query-count"] += 1 if object_type in ("user", "group"): query_path = "/{}s/{}/{:d}".format(object_type, self.org_id, page) if url_params: query_path += "/" + "/".join([urlparse.quote(c) for c in url_params]) if query_params: query_path += "?" + urlparse.urlencode(query_params) elif object_type == "user-group": query_path = "/{}/user-groups".format(self.org_id) if url_params: query_path += "/" + "/".join([urlparse.quote(c) for c in url_params]) query_path += "?page={:d}".format(page+1) if query_params: query_path += "&" + urlparse.urlencode(query_params) else: raise ArgumentError("Unknown query object type ({}): must be 'user' or 'group'".format(object_type)) try: result = self.make_call(query_path) body = result.json() except RequestError as re: if re.result.status_code == 404: if self.logger: self.logger.debug("Ran %s query: %s %s (0 found)", object_type, url_params, query_params) return [], True else: raise re if object_type in ("user", "group"): if body.get("result") == "success": values = body.get(object_type + "s", []) last_page = body.get("lastPage", False) if self.logger: self.logger.debug("Ran multi-%s query: %s %s (page %d: %d found)", object_type, url_params, query_params, page, len(values)) return values, last_page else: raise ClientError("OK status but no 'success' result", result) elif object_type == "user-group": page_number = result.headers.get("X-Current-Page", "1") page_count = result.headers.get("X-Page-Count", "1") if self.logger: self.logger.debug("Ran multi-group query: %s %s (page %d: %d found)", url_params, query_params, page, len(body)) return body, int(page_number) >= int(page_count) else: # this would actually be caught above, but we use a parallel construction in both places # to make it easy to add query object types raise ArgumentError("Unknown query object type ({}): must be 'user' or 'group'".format(object_type))
[ "def", "query_multiple", "(", "self", ",", "object_type", ",", "page", "=", "0", ",", "url_params", "=", "None", ",", "query_params", "=", "None", ")", ":", "# type: (str, int, list, dict) -> tuple", "# As of 2017-10-01, we are moving to to different URLs for user and user-...
Query for a page of objects. Defaults to the (0-based) first page. Sadly, the sort order is undetermined. :param object_type: string constant query type: either "user" or "group") :param page: numeric page (0-based) of results to get (up to 200 in a page) :param url_params: optional list of strings to provide as additional URL components :param query_params: optional dictionary of query options :return: tuple (list of returned dictionaries (one for each query result), bool for whether this is last page)
[ "Query", "for", "a", "page", "of", "objects", ".", "Defaults", "to", "the", "(", "0", "-", "based", ")", "first", "page", ".", "Sadly", "the", "sort", "order", "is", "undetermined", ".", ":", "param", "object_type", ":", "string", "constant", "query", ...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/connection.py#L237-L291
train
adobe-apiplatform/umapi-client.py
umapi_client/connection.py
Connection.execute_single
def execute_single(self, action, immediate=False): """ Execute a single action (containing commands on a single object). Normally, since actions are batched so as to be most efficient about execution, but if you want this command sent immediately (and all prior queued commands sent earlier in this command's batch), specify a True value for the immediate flag. Since any command can fill the current batch, your command may be submitted even if you don't specify the immediate flag. So don't think of this always being a queue call if immedidate=False. Returns the number of actions in the queue, that got sent, and that executed successfully. :param action: the Action to be executed :param immediate: whether the Action should be executed immediately :return: the number of actions in the queue, that got sent, and that executed successfully. """ return self.execute_multiple([action], immediate=immediate)
python
def execute_single(self, action, immediate=False): """ Execute a single action (containing commands on a single object). Normally, since actions are batched so as to be most efficient about execution, but if you want this command sent immediately (and all prior queued commands sent earlier in this command's batch), specify a True value for the immediate flag. Since any command can fill the current batch, your command may be submitted even if you don't specify the immediate flag. So don't think of this always being a queue call if immedidate=False. Returns the number of actions in the queue, that got sent, and that executed successfully. :param action: the Action to be executed :param immediate: whether the Action should be executed immediately :return: the number of actions in the queue, that got sent, and that executed successfully. """ return self.execute_multiple([action], immediate=immediate)
[ "def", "execute_single", "(", "self", ",", "action", ",", "immediate", "=", "False", ")", ":", "return", "self", ".", "execute_multiple", "(", "[", "action", "]", ",", "immediate", "=", "immediate", ")" ]
Execute a single action (containing commands on a single object). Normally, since actions are batched so as to be most efficient about execution, but if you want this command sent immediately (and all prior queued commands sent earlier in this command's batch), specify a True value for the immediate flag. Since any command can fill the current batch, your command may be submitted even if you don't specify the immediate flag. So don't think of this always being a queue call if immedidate=False. Returns the number of actions in the queue, that got sent, and that executed successfully. :param action: the Action to be executed :param immediate: whether the Action should be executed immediately :return: the number of actions in the queue, that got sent, and that executed successfully.
[ "Execute", "a", "single", "action", "(", "containing", "commands", "on", "a", "single", "object", ")", ".", "Normally", "since", "actions", "are", "batched", "so", "as", "to", "be", "most", "efficient", "about", "execution", "but", "if", "you", "want", "th...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/connection.py#L293-L310
train
adobe-apiplatform/umapi-client.py
umapi_client/connection.py
Connection.execute_multiple
def execute_multiple(self, actions, immediate=True): """ Execute multiple Actions (each containing commands on a single object). Normally, the actions are sent for execution immediately (possibly preceded by earlier queued commands), but if you are going for maximum efficiency you can set immeediate=False which will cause the connection to wait and batch as many actions as allowed in each server call. Since any command can fill the current batch, one or more of your commands may be submitted even if you don't specify the immediate flag. So don't think of this call as always being a queue call when immedidate=False. Returns the number of actions left in the queue, that got sent, and that executed successfully. NOTE: This is where we throttle the number of commands per action. So the number of actions we were given may not be the same as the number we queue or send to the server. NOTE: If the server gives us a response we don't understand, we note that and continue processing as usual. Then, at the end of the batch, we throw in order to warn the client that we had a problem understanding the server. :param actions: the list of Action objects to be executed :param immediate: whether to immediately send them to the server :return: tuple: the number of actions in the queue, that got sent, and that executed successfully. """ # throttling part 1: split up each action into smaller actions, as needed # optionally split large lists of groups in add/remove commands (if action supports it) split_actions = [] exceptions = [] for a in actions: if len(a.commands) == 0: if self.logger: self.logger.warning("Sending action with no commands: %s", a.frame) # maybe_split_groups is a UserAction attribute, so the call may throw an AttributeError try: if a.maybe_split_groups(self.throttle_groups): if self.logger: self.logger.debug( "Throttling actions %s to have a maximum of %d entries in group lists.", a.frame, self.throttle_groups) except AttributeError: pass if len(a.commands) > self.throttle_commands: if self.logger: self.logger.debug("Throttling action %s to have a maximum of %d commands.", a.frame, self.throttle_commands) split_actions += a.split(self.throttle_commands) else: split_actions.append(a) actions = self.action_queue + split_actions # throttling part 2: execute the action list in batches, as needed sent = completed = 0 batch_size = self.throttle_actions min_size = 1 if immediate else batch_size while len(actions) >= min_size: batch, actions = actions[0:batch_size], actions[batch_size:] if self.logger: self.logger.debug("Executing %d actions (%d remaining).", len(batch), len(actions)) sent += len(batch) try: completed += self._execute_batch(batch) except Exception as e: exceptions.append(e) self.action_queue = actions self.local_status["actions-queued"] = queued = len(actions) self.local_status["actions-sent"] += sent self.local_status["actions-completed"] += completed if exceptions: raise BatchError(exceptions, queued, sent, completed) return queued, sent, completed
python
def execute_multiple(self, actions, immediate=True): """ Execute multiple Actions (each containing commands on a single object). Normally, the actions are sent for execution immediately (possibly preceded by earlier queued commands), but if you are going for maximum efficiency you can set immeediate=False which will cause the connection to wait and batch as many actions as allowed in each server call. Since any command can fill the current batch, one or more of your commands may be submitted even if you don't specify the immediate flag. So don't think of this call as always being a queue call when immedidate=False. Returns the number of actions left in the queue, that got sent, and that executed successfully. NOTE: This is where we throttle the number of commands per action. So the number of actions we were given may not be the same as the number we queue or send to the server. NOTE: If the server gives us a response we don't understand, we note that and continue processing as usual. Then, at the end of the batch, we throw in order to warn the client that we had a problem understanding the server. :param actions: the list of Action objects to be executed :param immediate: whether to immediately send them to the server :return: tuple: the number of actions in the queue, that got sent, and that executed successfully. """ # throttling part 1: split up each action into smaller actions, as needed # optionally split large lists of groups in add/remove commands (if action supports it) split_actions = [] exceptions = [] for a in actions: if len(a.commands) == 0: if self.logger: self.logger.warning("Sending action with no commands: %s", a.frame) # maybe_split_groups is a UserAction attribute, so the call may throw an AttributeError try: if a.maybe_split_groups(self.throttle_groups): if self.logger: self.logger.debug( "Throttling actions %s to have a maximum of %d entries in group lists.", a.frame, self.throttle_groups) except AttributeError: pass if len(a.commands) > self.throttle_commands: if self.logger: self.logger.debug("Throttling action %s to have a maximum of %d commands.", a.frame, self.throttle_commands) split_actions += a.split(self.throttle_commands) else: split_actions.append(a) actions = self.action_queue + split_actions # throttling part 2: execute the action list in batches, as needed sent = completed = 0 batch_size = self.throttle_actions min_size = 1 if immediate else batch_size while len(actions) >= min_size: batch, actions = actions[0:batch_size], actions[batch_size:] if self.logger: self.logger.debug("Executing %d actions (%d remaining).", len(batch), len(actions)) sent += len(batch) try: completed += self._execute_batch(batch) except Exception as e: exceptions.append(e) self.action_queue = actions self.local_status["actions-queued"] = queued = len(actions) self.local_status["actions-sent"] += sent self.local_status["actions-completed"] += completed if exceptions: raise BatchError(exceptions, queued, sent, completed) return queued, sent, completed
[ "def", "execute_multiple", "(", "self", ",", "actions", ",", "immediate", "=", "True", ")", ":", "# throttling part 1: split up each action into smaller actions, as needed", "# optionally split large lists of groups in add/remove commands (if action supports it)", "split_actions", "=",...
Execute multiple Actions (each containing commands on a single object). Normally, the actions are sent for execution immediately (possibly preceded by earlier queued commands), but if you are going for maximum efficiency you can set immeediate=False which will cause the connection to wait and batch as many actions as allowed in each server call. Since any command can fill the current batch, one or more of your commands may be submitted even if you don't specify the immediate flag. So don't think of this call as always being a queue call when immedidate=False. Returns the number of actions left in the queue, that got sent, and that executed successfully. NOTE: This is where we throttle the number of commands per action. So the number of actions we were given may not be the same as the number we queue or send to the server. NOTE: If the server gives us a response we don't understand, we note that and continue processing as usual. Then, at the end of the batch, we throw in order to warn the client that we had a problem understanding the server. :param actions: the list of Action objects to be executed :param immediate: whether to immediately send them to the server :return: tuple: the number of actions in the queue, that got sent, and that executed successfully.
[ "Execute", "multiple", "Actions", "(", "each", "containing", "commands", "on", "a", "single", "object", ")", ".", "Normally", "the", "actions", "are", "sent", "for", "execution", "immediately", "(", "possibly", "preceded", "by", "earlier", "queued", "commands", ...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/connection.py#L319-L384
train
adobe-apiplatform/umapi-client.py
umapi_client/connection.py
Connection._execute_batch
def _execute_batch(self, actions): """ Execute a single batch of Actions. For each action that has a problem, we annotate the action with the error information for that action, and we return the number of successful actions in the batch. :param actions: the list of Action objects to be executed :return: count of successful actions """ wire_form = [a.wire_dict() for a in actions] if self.test_mode: result = self.make_call("/action/%s?testOnly=true" % self.org_id, wire_form) else: result = self.make_call("/action/%s" % self.org_id, wire_form) body = result.json() if body.get("errors", None) is None: if body.get("result") != "success": if self.logger: self.logger.warning("Server action result: no errors, but no success:\n%s", body) return len(actions) try: if body.get("result") == "success": if self.logger: self.logger.warning("Server action result: errors, but success report:\n%s", body) for error in body["errors"]: actions[error["index"]].report_command_error(error) except: raise ClientError(str(body), result) return body.get("completed", 0)
python
def _execute_batch(self, actions): """ Execute a single batch of Actions. For each action that has a problem, we annotate the action with the error information for that action, and we return the number of successful actions in the batch. :param actions: the list of Action objects to be executed :return: count of successful actions """ wire_form = [a.wire_dict() for a in actions] if self.test_mode: result = self.make_call("/action/%s?testOnly=true" % self.org_id, wire_form) else: result = self.make_call("/action/%s" % self.org_id, wire_form) body = result.json() if body.get("errors", None) is None: if body.get("result") != "success": if self.logger: self.logger.warning("Server action result: no errors, but no success:\n%s", body) return len(actions) try: if body.get("result") == "success": if self.logger: self.logger.warning("Server action result: errors, but success report:\n%s", body) for error in body["errors"]: actions[error["index"]].report_command_error(error) except: raise ClientError(str(body), result) return body.get("completed", 0)
[ "def", "_execute_batch", "(", "self", ",", "actions", ")", ":", "wire_form", "=", "[", "a", ".", "wire_dict", "(", ")", "for", "a", "in", "actions", "]", "if", "self", ".", "test_mode", ":", "result", "=", "self", ".", "make_call", "(", "\"/action/%s?t...
Execute a single batch of Actions. For each action that has a problem, we annotate the action with the error information for that action, and we return the number of successful actions in the batch. :param actions: the list of Action objects to be executed :return: count of successful actions
[ "Execute", "a", "single", "batch", "of", "Actions", ".", "For", "each", "action", "that", "has", "a", "problem", "we", "annotate", "the", "action", "with", "the", "error", "information", "for", "that", "action", "and", "we", "return", "the", "number", "of"...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/connection.py#L386-L412
train
adobe-apiplatform/umapi-client.py
umapi_client/connection.py
Connection.make_call
def make_call(self, path, body=None, delete=False): """ Make a single UMAPI call with error handling and retry on temporary failure. :param path: the string endpoint path for the call :param body: (optional) list of dictionaries to be serialized into the request body :return: the requests.result object (on 200 response), raise error otherwise """ if body: request_body = json.dumps(body) def call(): return self.session.post(self.endpoint + path, auth=self.auth, data=request_body, timeout=self.timeout) else: if not delete: def call(): return self.session.get(self.endpoint + path, auth=self.auth, timeout=self.timeout) else: def call(): return self.session.delete(self.endpoint + path, auth=self.auth, timeout=self.timeout) start_time = time() result = None for num_attempts in range(1, self.retry_max_attempts + 1): try: result = call() if result.status_code in [200,201,204]: return result elif result.status_code in [429, 502, 503, 504]: if self.logger: self.logger.warning("UMAPI timeout...service unavailable (code %d on try %d)", result.status_code, num_attempts) retry_wait = 0 if "Retry-After" in result.headers: advice = result.headers["Retry-After"] advised_time = parsedate_tz(advice) if advised_time is not None: # header contains date retry_wait = int(mktime_tz(advised_time) - time()) else: # header contains delta seconds retry_wait = int(advice) if retry_wait <= 0: # use exponential back-off with random delay delay = randint(0, self.retry_random_delay) retry_wait = (int(pow(2, num_attempts - 1)) * self.retry_first_delay) + delay elif 201 <= result.status_code < 400: raise ClientError("Unexpected HTTP Status {:d}: {}".format(result.status_code, result.text), result) elif 400 <= result.status_code < 500: raise RequestError(result) else: raise ServerError(result) except requests.Timeout: if self.logger: self.logger.warning("UMAPI connection timeout...(%d seconds on try %d)", self.timeout, num_attempts) retry_wait = 0 result = None if num_attempts < self.retry_max_attempts: if retry_wait > 0: if self.logger: self.logger.warning("Next retry in %d seconds...", retry_wait) sleep(retry_wait) else: if self.logger: self.logger.warning("Immediate retry...") total_time = int(time() - start_time) if self.logger: self.logger.error("UMAPI timeout...giving up after %d attempts (%d seconds).", self.retry_max_attempts, total_time) raise UnavailableError(self.retry_max_attempts, total_time, result)
python
def make_call(self, path, body=None, delete=False): """ Make a single UMAPI call with error handling and retry on temporary failure. :param path: the string endpoint path for the call :param body: (optional) list of dictionaries to be serialized into the request body :return: the requests.result object (on 200 response), raise error otherwise """ if body: request_body = json.dumps(body) def call(): return self.session.post(self.endpoint + path, auth=self.auth, data=request_body, timeout=self.timeout) else: if not delete: def call(): return self.session.get(self.endpoint + path, auth=self.auth, timeout=self.timeout) else: def call(): return self.session.delete(self.endpoint + path, auth=self.auth, timeout=self.timeout) start_time = time() result = None for num_attempts in range(1, self.retry_max_attempts + 1): try: result = call() if result.status_code in [200,201,204]: return result elif result.status_code in [429, 502, 503, 504]: if self.logger: self.logger.warning("UMAPI timeout...service unavailable (code %d on try %d)", result.status_code, num_attempts) retry_wait = 0 if "Retry-After" in result.headers: advice = result.headers["Retry-After"] advised_time = parsedate_tz(advice) if advised_time is not None: # header contains date retry_wait = int(mktime_tz(advised_time) - time()) else: # header contains delta seconds retry_wait = int(advice) if retry_wait <= 0: # use exponential back-off with random delay delay = randint(0, self.retry_random_delay) retry_wait = (int(pow(2, num_attempts - 1)) * self.retry_first_delay) + delay elif 201 <= result.status_code < 400: raise ClientError("Unexpected HTTP Status {:d}: {}".format(result.status_code, result.text), result) elif 400 <= result.status_code < 500: raise RequestError(result) else: raise ServerError(result) except requests.Timeout: if self.logger: self.logger.warning("UMAPI connection timeout...(%d seconds on try %d)", self.timeout, num_attempts) retry_wait = 0 result = None if num_attempts < self.retry_max_attempts: if retry_wait > 0: if self.logger: self.logger.warning("Next retry in %d seconds...", retry_wait) sleep(retry_wait) else: if self.logger: self.logger.warning("Immediate retry...") total_time = int(time() - start_time) if self.logger: self.logger.error("UMAPI timeout...giving up after %d attempts (%d seconds).", self.retry_max_attempts, total_time) raise UnavailableError(self.retry_max_attempts, total_time, result)
[ "def", "make_call", "(", "self", ",", "path", ",", "body", "=", "None", ",", "delete", "=", "False", ")", ":", "if", "body", ":", "request_body", "=", "json", ".", "dumps", "(", "body", ")", "def", "call", "(", ")", ":", "return", "self", ".", "s...
Make a single UMAPI call with error handling and retry on temporary failure. :param path: the string endpoint path for the call :param body: (optional) list of dictionaries to be serialized into the request body :return: the requests.result object (on 200 response), raise error otherwise
[ "Make", "a", "single", "UMAPI", "call", "with", "error", "handling", "and", "retry", "on", "temporary", "failure", ".", ":", "param", "path", ":", "the", "string", "endpoint", "path", "for", "the", "call", ":", "param", "body", ":", "(", "optional", ")",...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/connection.py#L414-L477
train
adobe-apiplatform/umapi-client.py
umapi_client/legacy.py
paginate
def paginate(query, org_id, max_pages=maxsize, max_records=maxsize): """ Paginate through all results of a UMAPI query :param query: a query method from a UMAPI instance (callable as a function) :param org_id: the organization being queried :param max_pages: the max number of pages to collect before returning (default all) :param max_records: the max number of records to collect before returning (default all) :return: the queried records """ page_count = 0 record_count = 0 records = [] while page_count < max_pages and record_count < max_records: res = make_call(query, org_id, page_count) page_count += 1 # the following incredibly ugly piece of code is very fragile. # the problem is that we are a "dumb helper" that doesn't understand # the semantics of the UMAPI or know which query we were given. if "groups" in res: records += res["groups"] elif "users" in res: records += res["users"] record_count = len(records) if res.get("lastPage"): break return records
python
def paginate(query, org_id, max_pages=maxsize, max_records=maxsize): """ Paginate through all results of a UMAPI query :param query: a query method from a UMAPI instance (callable as a function) :param org_id: the organization being queried :param max_pages: the max number of pages to collect before returning (default all) :param max_records: the max number of records to collect before returning (default all) :return: the queried records """ page_count = 0 record_count = 0 records = [] while page_count < max_pages and record_count < max_records: res = make_call(query, org_id, page_count) page_count += 1 # the following incredibly ugly piece of code is very fragile. # the problem is that we are a "dumb helper" that doesn't understand # the semantics of the UMAPI or know which query we were given. if "groups" in res: records += res["groups"] elif "users" in res: records += res["users"] record_count = len(records) if res.get("lastPage"): break return records
[ "def", "paginate", "(", "query", ",", "org_id", ",", "max_pages", "=", "maxsize", ",", "max_records", "=", "maxsize", ")", ":", "page_count", "=", "0", "record_count", "=", "0", "records", "=", "[", "]", "while", "page_count", "<", "max_pages", "and", "r...
Paginate through all results of a UMAPI query :param query: a query method from a UMAPI instance (callable as a function) :param org_id: the organization being queried :param max_pages: the max number of pages to collect before returning (default all) :param max_records: the max number of records to collect before returning (default all) :return: the queried records
[ "Paginate", "through", "all", "results", "of", "a", "UMAPI", "query", ":", "param", "query", ":", "a", "query", "method", "from", "a", "UMAPI", "instance", "(", "callable", "as", "a", "function", ")", ":", "param", "org_id", ":", "the", "organization", "...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/legacy.py#L186-L211
train
adobe-apiplatform/umapi-client.py
umapi_client/legacy.py
make_call
def make_call(query, org_id, page): """ Make a single UMAPI call with error handling and server-controlled throttling. (Adapted from sample code at https://www.adobe.io/products/usermanagement/docs/samples#retry) :param query: a query method from a UMAPI instance (callable as a function) :param org_id: the organization being queried :param page: the page number of the desired result set :return: the json (dictionary) received from the server (if any) """ wait_time = 0 num_attempts = 0 while num_attempts < retry_max_attempts: if wait_time > 0: sleep(wait_time) wait_time = 0 try: num_attempts += 1 return query(org_id, page) except UMAPIRetryError as e: logger.warning("UMAPI service temporarily unavailable (attempt %d) -- %s", num_attempts, e.res.status_code) if "Retry-After" in e.res.headers: advice = e.res.headers["Retry-After"] advised_time = parsedate_tz(advice) if advised_time is not None: # header contains date wait_time = int(mktime_tz(advised_time) - time()) else: # header contains delta seconds wait_time = int(advice) if wait_time <= 0: # use exponential back-off with random delay delay = randint(0, retry_random_delay_max) wait_time = (int(pow(2, num_attempts)) * retry_exponential_backoff_factor) + delay logger.warning("Next retry in %d seconds...", wait_time) continue except UMAPIRequestError as e: logger.warning("UMAPI error processing request -- %s", e.code) return {} except UMAPIError as e: logger.warning("HTTP error processing request -- %s: %s", e.res.status_code, e.res.text) return {} logger.error("UMAPI timeout...giving up on results page %d after %d attempts.", page, retry_max_attempts) return {}
python
def make_call(query, org_id, page): """ Make a single UMAPI call with error handling and server-controlled throttling. (Adapted from sample code at https://www.adobe.io/products/usermanagement/docs/samples#retry) :param query: a query method from a UMAPI instance (callable as a function) :param org_id: the organization being queried :param page: the page number of the desired result set :return: the json (dictionary) received from the server (if any) """ wait_time = 0 num_attempts = 0 while num_attempts < retry_max_attempts: if wait_time > 0: sleep(wait_time) wait_time = 0 try: num_attempts += 1 return query(org_id, page) except UMAPIRetryError as e: logger.warning("UMAPI service temporarily unavailable (attempt %d) -- %s", num_attempts, e.res.status_code) if "Retry-After" in e.res.headers: advice = e.res.headers["Retry-After"] advised_time = parsedate_tz(advice) if advised_time is not None: # header contains date wait_time = int(mktime_tz(advised_time) - time()) else: # header contains delta seconds wait_time = int(advice) if wait_time <= 0: # use exponential back-off with random delay delay = randint(0, retry_random_delay_max) wait_time = (int(pow(2, num_attempts)) * retry_exponential_backoff_factor) + delay logger.warning("Next retry in %d seconds...", wait_time) continue except UMAPIRequestError as e: logger.warning("UMAPI error processing request -- %s", e.code) return {} except UMAPIError as e: logger.warning("HTTP error processing request -- %s: %s", e.res.status_code, e.res.text) return {} logger.error("UMAPI timeout...giving up on results page %d after %d attempts.", page, retry_max_attempts) return {}
[ "def", "make_call", "(", "query", ",", "org_id", ",", "page", ")", ":", "wait_time", "=", "0", "num_attempts", "=", "0", "while", "num_attempts", "<", "retry_max_attempts", ":", "if", "wait_time", ">", "0", ":", "sleep", "(", "wait_time", ")", "wait_time",...
Make a single UMAPI call with error handling and server-controlled throttling. (Adapted from sample code at https://www.adobe.io/products/usermanagement/docs/samples#retry) :param query: a query method from a UMAPI instance (callable as a function) :param org_id: the organization being queried :param page: the page number of the desired result set :return: the json (dictionary) received from the server (if any)
[ "Make", "a", "single", "UMAPI", "call", "with", "error", "handling", "and", "server", "-", "controlled", "throttling", ".", "(", "Adapted", "from", "sample", "code", "at", "https", ":", "//", "www", ".", "adobe", ".", "io", "/", "products", "/", "userman...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/legacy.py#L214-L257
train
adobe-apiplatform/umapi-client.py
umapi_client/legacy.py
Action.do
def do(self, **kwargs): """ Here for compatibility with legacy clients only - DO NOT USE!!! This is sort of mix of "append" and "insert": it puts commands in the list, with some half smarts about which commands go at the front or back. If you add multiple commands to the back in one call, they will get added sorted by command name. :param kwargs: the commands in key=val format :return: the Action, so you can do Action(...).do(...).do(...) """ # add "create" / "add" / "removeFrom" first for k, v in list(six.iteritems(kwargs)): if k.startswith("create") or k.startswith("addAdobe") or k.startswith("removeFrom"): self.commands.append({k: v}) del kwargs[k] # now do the other actions, in a canonical order (to avoid py2/py3 variations) for k, v in sorted(six.iteritems(kwargs)): if k in ['add', 'remove']: self.commands.append({k: {"product": v}}) else: self.commands.append({k: v}) return self
python
def do(self, **kwargs): """ Here for compatibility with legacy clients only - DO NOT USE!!! This is sort of mix of "append" and "insert": it puts commands in the list, with some half smarts about which commands go at the front or back. If you add multiple commands to the back in one call, they will get added sorted by command name. :param kwargs: the commands in key=val format :return: the Action, so you can do Action(...).do(...).do(...) """ # add "create" / "add" / "removeFrom" first for k, v in list(six.iteritems(kwargs)): if k.startswith("create") or k.startswith("addAdobe") or k.startswith("removeFrom"): self.commands.append({k: v}) del kwargs[k] # now do the other actions, in a canonical order (to avoid py2/py3 variations) for k, v in sorted(six.iteritems(kwargs)): if k in ['add', 'remove']: self.commands.append({k: {"product": v}}) else: self.commands.append({k: v}) return self
[ "def", "do", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# add \"create\" / \"add\" / \"removeFrom\" first", "for", "k", ",", "v", "in", "list", "(", "six", ".", "iteritems", "(", "kwargs", ")", ")", ":", "if", "k", ".", "startswith", "(", "\"create...
Here for compatibility with legacy clients only - DO NOT USE!!! This is sort of mix of "append" and "insert": it puts commands in the list, with some half smarts about which commands go at the front or back. If you add multiple commands to the back in one call, they will get added sorted by command name. :param kwargs: the commands in key=val format :return: the Action, so you can do Action(...).do(...).do(...)
[ "Here", "for", "compatibility", "with", "legacy", "clients", "only", "-", "DO", "NOT", "USE!!!", "This", "is", "sort", "of", "mix", "of", "append", "and", "insert", ":", "it", "puts", "commands", "in", "the", "list", "with", "some", "half", "smarts", "ab...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/legacy.py#L62-L83
train
adobe-apiplatform/umapi-client.py
umapi_client/api.py
Action.split
def split(self, max_commands): """ Split this action into an equivalent list of actions, each of which have at most max_commands commands. :param max_commands: max number of commands allowed in any action :return: the list of commands created from this one """ a_prior = Action(**self.frame) a_prior.commands = list(self.commands) self.split_actions = [a_prior] while len(a_prior.commands) > max_commands: a_next = Action(**self.frame) a_prior.commands, a_next.commands = a_prior.commands[0:max_commands], a_prior.commands[max_commands:] self.split_actions.append(a_next) a_prior = a_next return self.split_actions
python
def split(self, max_commands): """ Split this action into an equivalent list of actions, each of which have at most max_commands commands. :param max_commands: max number of commands allowed in any action :return: the list of commands created from this one """ a_prior = Action(**self.frame) a_prior.commands = list(self.commands) self.split_actions = [a_prior] while len(a_prior.commands) > max_commands: a_next = Action(**self.frame) a_prior.commands, a_next.commands = a_prior.commands[0:max_commands], a_prior.commands[max_commands:] self.split_actions.append(a_next) a_prior = a_next return self.split_actions
[ "def", "split", "(", "self", ",", "max_commands", ")", ":", "a_prior", "=", "Action", "(", "*", "*", "self", ".", "frame", ")", "a_prior", ".", "commands", "=", "list", "(", "self", ".", "commands", ")", "self", ".", "split_actions", "=", "[", "a_pri...
Split this action into an equivalent list of actions, each of which have at most max_commands commands. :param max_commands: max number of commands allowed in any action :return: the list of commands created from this one
[ "Split", "this", "action", "into", "an", "equivalent", "list", "of", "actions", "each", "of", "which", "have", "at", "most", "max_commands", "commands", ".", ":", "param", "max_commands", ":", "max", "number", "of", "commands", "allowed", "in", "any", "actio...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L44-L58
train
adobe-apiplatform/umapi-client.py
umapi_client/api.py
Action.append
def append(self, **kwargs): """ Add commands at the end of the sequence. Be careful: because this runs in Python 2.x, the order of the kwargs dict may not match the order in which the args were specified. Thus, if you care about specific ordering, you must make multiple calls to append in that order. Luckily, append returns the Action so you can compose easily: Action(...).append(...).append(...). See also insert, below. :param kwargs: the key/value pairs to add :return: the action """ for k, v in six.iteritems(kwargs): self.commands.append({k: v}) return self
python
def append(self, **kwargs): """ Add commands at the end of the sequence. Be careful: because this runs in Python 2.x, the order of the kwargs dict may not match the order in which the args were specified. Thus, if you care about specific ordering, you must make multiple calls to append in that order. Luckily, append returns the Action so you can compose easily: Action(...).append(...).append(...). See also insert, below. :param kwargs: the key/value pairs to add :return: the action """ for k, v in six.iteritems(kwargs): self.commands.append({k: v}) return self
[ "def", "append", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "self", ".", "commands", ".", "append", "(", "{", "k", ":", "v", "}", ")", "return", "self" ]
Add commands at the end of the sequence. Be careful: because this runs in Python 2.x, the order of the kwargs dict may not match the order in which the args were specified. Thus, if you care about specific ordering, you must make multiple calls to append in that order. Luckily, append returns the Action so you can compose easily: Action(...).append(...).append(...). See also insert, below. :param kwargs: the key/value pairs to add :return: the action
[ "Add", "commands", "at", "the", "end", "of", "the", "sequence", "." ]
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L67-L81
train
adobe-apiplatform/umapi-client.py
umapi_client/api.py
Action.insert
def insert(self, **kwargs): """ Insert commands at the beginning of the sequence. This is provided because certain commands have to come first (such as user creation), but may be need to beadded after other commands have already been specified. Later calls to insert put their commands before those in the earlier calls. Also, since the order of iterated kwargs is not guaranteed (in Python 2.x), you should really only call insert with one keyword at a time. See the doc of append for more details. :param kwargs: the key/value pair to append first :return: the action, so you can append Action(...).insert(...).append(...) """ for k, v in six.iteritems(kwargs): self.commands.insert(0, {k: v}) return self
python
def insert(self, **kwargs): """ Insert commands at the beginning of the sequence. This is provided because certain commands have to come first (such as user creation), but may be need to beadded after other commands have already been specified. Later calls to insert put their commands before those in the earlier calls. Also, since the order of iterated kwargs is not guaranteed (in Python 2.x), you should really only call insert with one keyword at a time. See the doc of append for more details. :param kwargs: the key/value pair to append first :return: the action, so you can append Action(...).insert(...).append(...) """ for k, v in six.iteritems(kwargs): self.commands.insert(0, {k: v}) return self
[ "def", "insert", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "kwargs", ")", ":", "self", ".", "commands", ".", "insert", "(", "0", ",", "{", "k", ":", "v", "}", ")", "return", "sel...
Insert commands at the beginning of the sequence. This is provided because certain commands have to come first (such as user creation), but may be need to beadded after other commands have already been specified. Later calls to insert put their commands before those in the earlier calls. Also, since the order of iterated kwargs is not guaranteed (in Python 2.x), you should really only call insert with one keyword at a time. See the doc of append for more details. :param kwargs: the key/value pair to append first :return: the action, so you can append Action(...).insert(...).append(...)
[ "Insert", "commands", "at", "the", "beginning", "of", "the", "sequence", "." ]
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L83-L100
train
adobe-apiplatform/umapi-client.py
umapi_client/api.py
Action.report_command_error
def report_command_error(self, error_dict): """ Report a server error executing a command. We keep track of the command's position in the command list, and we add annotation of what the command was, to the error. :param error_dict: The server's error dict for the error encountered """ error = dict(error_dict) error["command"] = self.commands[error_dict["step"]] error["target"] = self.frame del error["index"] # throttling can change which action this was in the batch del error["step"] # throttling can change which step this was in the action self.errors.append(error)
python
def report_command_error(self, error_dict): """ Report a server error executing a command. We keep track of the command's position in the command list, and we add annotation of what the command was, to the error. :param error_dict: The server's error dict for the error encountered """ error = dict(error_dict) error["command"] = self.commands[error_dict["step"]] error["target"] = self.frame del error["index"] # throttling can change which action this was in the batch del error["step"] # throttling can change which step this was in the action self.errors.append(error)
[ "def", "report_command_error", "(", "self", ",", "error_dict", ")", ":", "error", "=", "dict", "(", "error_dict", ")", "error", "[", "\"command\"", "]", "=", "self", ".", "commands", "[", "error_dict", "[", "\"step\"", "]", "]", "error", "[", "\"target\"",...
Report a server error executing a command. We keep track of the command's position in the command list, and we add annotation of what the command was, to the error. :param error_dict: The server's error dict for the error encountered
[ "Report", "a", "server", "error", "executing", "a", "command", "." ]
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L102-L115
train
adobe-apiplatform/umapi-client.py
umapi_client/api.py
Action.execution_errors
def execution_errors(self): """ Return a list of commands that encountered execution errors, with the error. Each dictionary entry gives the command dictionary and the error dictionary :return: list of commands that gave errors, with their error information """ if self.split_actions: # throttling split this action, get errors from the split return [dict(e) for s in self.split_actions for e in s.errors] else: return [dict(e) for e in self.errors]
python
def execution_errors(self): """ Return a list of commands that encountered execution errors, with the error. Each dictionary entry gives the command dictionary and the error dictionary :return: list of commands that gave errors, with their error information """ if self.split_actions: # throttling split this action, get errors from the split return [dict(e) for s in self.split_actions for e in s.errors] else: return [dict(e) for e in self.errors]
[ "def", "execution_errors", "(", "self", ")", ":", "if", "self", ".", "split_actions", ":", "# throttling split this action, get errors from the split", "return", "[", "dict", "(", "e", ")", "for", "s", "in", "self", ".", "split_actions", "for", "e", "in", "s", ...
Return a list of commands that encountered execution errors, with the error. Each dictionary entry gives the command dictionary and the error dictionary :return: list of commands that gave errors, with their error information
[ "Return", "a", "list", "of", "commands", "that", "encountered", "execution", "errors", "with", "the", "error", "." ]
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L117-L128
train
adobe-apiplatform/umapi-client.py
umapi_client/api.py
Action.maybe_split_groups
def maybe_split_groups(self, max_groups): """ Check if group lists in add/remove directives should be split and split them if needed :param max_groups: Max group list size :return: True if at least one command was split, False if none were split """ split_commands = [] # return True if we split at least once maybe_split = False valid_step_keys = ['add', 'addRoles', 'remove'] for command in self.commands: # commands are assumed to contain a single key step_key, step_args = next(six.iteritems(command)) if step_key not in valid_step_keys or not isinstance(step_args, dict): split_commands.append(command) continue new_commands = [command] while True: new_command = {step_key: {}} for group_type, groups in six.iteritems(command[step_key]): if len(groups) > max_groups: command[step_key][group_type], new_command[step_key][group_type] = \ groups[0:max_groups], groups[max_groups:] if new_command[step_key]: new_commands.append(new_command) command = new_command maybe_split = True else: break split_commands += new_commands self.commands = split_commands return maybe_split
python
def maybe_split_groups(self, max_groups): """ Check if group lists in add/remove directives should be split and split them if needed :param max_groups: Max group list size :return: True if at least one command was split, False if none were split """ split_commands = [] # return True if we split at least once maybe_split = False valid_step_keys = ['add', 'addRoles', 'remove'] for command in self.commands: # commands are assumed to contain a single key step_key, step_args = next(six.iteritems(command)) if step_key not in valid_step_keys or not isinstance(step_args, dict): split_commands.append(command) continue new_commands = [command] while True: new_command = {step_key: {}} for group_type, groups in six.iteritems(command[step_key]): if len(groups) > max_groups: command[step_key][group_type], new_command[step_key][group_type] = \ groups[0:max_groups], groups[max_groups:] if new_command[step_key]: new_commands.append(new_command) command = new_command maybe_split = True else: break split_commands += new_commands self.commands = split_commands return maybe_split
[ "def", "maybe_split_groups", "(", "self", ",", "max_groups", ")", ":", "split_commands", "=", "[", "]", "# return True if we split at least once", "maybe_split", "=", "False", "valid_step_keys", "=", "[", "'add'", ",", "'addRoles'", ",", "'remove'", "]", "for", "c...
Check if group lists in add/remove directives should be split and split them if needed :param max_groups: Max group list size :return: True if at least one command was split, False if none were split
[ "Check", "if", "group", "lists", "in", "add", "/", "remove", "directives", "should", "be", "split", "and", "split", "them", "if", "needed", ":", "param", "max_groups", ":", "Max", "group", "list", "size", ":", "return", ":", "True", "if", "at", "least", ...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L130-L161
train
adobe-apiplatform/umapi-client.py
umapi_client/api.py
QueryMultiple.reload
def reload(self): """ Rerun the query (lazily). The results will contain any values on the server side that have changed since the last run. :return: None """ self._results = [] self._next_item_index = 0 self._next_page_index = 0 self._last_page_seen = False
python
def reload(self): """ Rerun the query (lazily). The results will contain any values on the server side that have changed since the last run. :return: None """ self._results = [] self._next_item_index = 0 self._next_page_index = 0 self._last_page_seen = False
[ "def", "reload", "(", "self", ")", ":", "self", ".", "_results", "=", "[", "]", "self", ".", "_next_item_index", "=", "0", "self", ".", "_next_page_index", "=", "0", "self", ".", "_last_page_seen", "=", "False" ]
Rerun the query (lazily). The results will contain any values on the server side that have changed since the last run. :return: None
[ "Rerun", "the", "query", "(", "lazily", ")", ".", "The", "results", "will", "contain", "any", "values", "on", "the", "server", "side", "that", "have", "changed", "since", "the", "last", "run", ".", ":", "return", ":", "None" ]
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L187-L196
train
adobe-apiplatform/umapi-client.py
umapi_client/api.py
QueryMultiple._next_page
def _next_page(self): """ Fetch the next page of the query. """ if self._last_page_seen: raise StopIteration new, self._last_page_seen = self.conn.query_multiple(self.object_type, self._next_page_index, self.url_params, self.query_params) self._next_page_index += 1 if len(new) == 0: self._last_page_seen = True # don't bother with next page if nothing was returned else: self._results += new
python
def _next_page(self): """ Fetch the next page of the query. """ if self._last_page_seen: raise StopIteration new, self._last_page_seen = self.conn.query_multiple(self.object_type, self._next_page_index, self.url_params, self.query_params) self._next_page_index += 1 if len(new) == 0: self._last_page_seen = True # don't bother with next page if nothing was returned else: self._results += new
[ "def", "_next_page", "(", "self", ")", ":", "if", "self", ".", "_last_page_seen", ":", "raise", "StopIteration", "new", ",", "self", ".", "_last_page_seen", "=", "self", ".", "conn", ".", "query_multiple", "(", "self", ".", "object_type", ",", "self", ".",...
Fetch the next page of the query.
[ "Fetch", "the", "next", "page", "of", "the", "query", "." ]
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L198-L210
train
adobe-apiplatform/umapi-client.py
umapi_client/api.py
QueryMultiple.all_results
def all_results(self): """ Eagerly fetch all the results. This can be called after already doing some amount of iteration, and it will return all the previously-iterated results as well as any results that weren't yet iterated. :return: a list of all the results. """ while not self._last_page_seen: self._next_page() self._next_item_index = len(self._results) return list(self._results)
python
def all_results(self): """ Eagerly fetch all the results. This can be called after already doing some amount of iteration, and it will return all the previously-iterated results as well as any results that weren't yet iterated. :return: a list of all the results. """ while not self._last_page_seen: self._next_page() self._next_item_index = len(self._results) return list(self._results)
[ "def", "all_results", "(", "self", ")", ":", "while", "not", "self", ".", "_last_page_seen", ":", "self", ".", "_next_page", "(", ")", "self", ".", "_next_item_index", "=", "len", "(", "self", ".", "_results", ")", "return", "list", "(", "self", ".", "...
Eagerly fetch all the results. This can be called after already doing some amount of iteration, and it will return all the previously-iterated results as well as any results that weren't yet iterated. :return: a list of all the results.
[ "Eagerly", "fetch", "all", "the", "results", ".", "This", "can", "be", "called", "after", "already", "doing", "some", "amount", "of", "iteration", "and", "it", "will", "return", "all", "the", "previously", "-", "iterated", "results", "as", "well", "as", "a...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L241-L251
train
adobe-apiplatform/umapi-client.py
umapi_client/api.py
QuerySingle._fetch_result
def _fetch_result(self): """ Fetch the queried object. """ self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params)
python
def _fetch_result(self): """ Fetch the queried object. """ self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params)
[ "def", "_fetch_result", "(", "self", ")", ":", "self", ".", "_result", "=", "self", ".", "conn", ".", "query_single", "(", "self", ".", "object_type", ",", "self", ".", "url_params", ",", "self", ".", "query_params", ")" ]
Fetch the queried object.
[ "Fetch", "the", "queried", "object", "." ]
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/api.py#L282-L286
train
adobe-apiplatform/umapi-client.py
umapi_client/functional.py
UserAction.create
def create(self, first_name=None, last_name=None, country=None, email=None, on_conflict=IfAlreadyExistsOptions.ignoreIfAlreadyExists): """ Create the user on the Adobe back end. See [Issue 32](https://github.com/adobe-apiplatform/umapi-client.py/issues/32): because we retry create calls if they time out, the default conflict handling for creation is to ignore the create call if the user already exists (possibly from an earlier call that timed out). :param first_name: (optional) user first name :param last_name: (optional) user last name :param country: (optional except for Federated ID) user 2-letter ISO country code :param email: user email, if not already specified at create time :param on_conflict: IfAlreadyExistsOption (or string name thereof) controlling creation of existing users :return: the User, so you can do User(...).create(...).add_to_groups(...) """ # first validate the params: email, on_conflict, first_name, last_name, country create_params = {} if email is None: if not self.email: raise ArgumentError("You must specify email when creating a user") elif self.email is None: self.email = email elif self.email.lower() != email.lower(): raise ArgumentError("Specified email (%s) doesn't match user's email (%s)" % (email, self.email)) create_params["email"] = self.email if on_conflict in IfAlreadyExistsOptions.__members__: on_conflict = IfAlreadyExistsOptions[on_conflict] if on_conflict not in IfAlreadyExistsOptions: raise ArgumentError("on_conflict must be one of {}".format([o.name for o in IfAlreadyExistsOptions])) if on_conflict != IfAlreadyExistsOptions.errorIfAlreadyExists: create_params["option"] = on_conflict.name if first_name: create_params["firstname"] = first_name # per issue #54 now allowed for all identity types if last_name: create_params["lastname"] = last_name # per issue #54 now allowed for all identity types if country: create_params["country"] = country # per issue #55 should not be defaulted # each type is created using a different call if self.id_type == IdentityTypes.adobeID: return self.insert(addAdobeID=dict(**create_params)) elif self.id_type == IdentityTypes.enterpriseID: return self.insert(createEnterpriseID=dict(**create_params)) else: return self.insert(createFederatedID=dict(**create_params))
python
def create(self, first_name=None, last_name=None, country=None, email=None, on_conflict=IfAlreadyExistsOptions.ignoreIfAlreadyExists): """ Create the user on the Adobe back end. See [Issue 32](https://github.com/adobe-apiplatform/umapi-client.py/issues/32): because we retry create calls if they time out, the default conflict handling for creation is to ignore the create call if the user already exists (possibly from an earlier call that timed out). :param first_name: (optional) user first name :param last_name: (optional) user last name :param country: (optional except for Federated ID) user 2-letter ISO country code :param email: user email, if not already specified at create time :param on_conflict: IfAlreadyExistsOption (or string name thereof) controlling creation of existing users :return: the User, so you can do User(...).create(...).add_to_groups(...) """ # first validate the params: email, on_conflict, first_name, last_name, country create_params = {} if email is None: if not self.email: raise ArgumentError("You must specify email when creating a user") elif self.email is None: self.email = email elif self.email.lower() != email.lower(): raise ArgumentError("Specified email (%s) doesn't match user's email (%s)" % (email, self.email)) create_params["email"] = self.email if on_conflict in IfAlreadyExistsOptions.__members__: on_conflict = IfAlreadyExistsOptions[on_conflict] if on_conflict not in IfAlreadyExistsOptions: raise ArgumentError("on_conflict must be one of {}".format([o.name for o in IfAlreadyExistsOptions])) if on_conflict != IfAlreadyExistsOptions.errorIfAlreadyExists: create_params["option"] = on_conflict.name if first_name: create_params["firstname"] = first_name # per issue #54 now allowed for all identity types if last_name: create_params["lastname"] = last_name # per issue #54 now allowed for all identity types if country: create_params["country"] = country # per issue #55 should not be defaulted # each type is created using a different call if self.id_type == IdentityTypes.adobeID: return self.insert(addAdobeID=dict(**create_params)) elif self.id_type == IdentityTypes.enterpriseID: return self.insert(createEnterpriseID=dict(**create_params)) else: return self.insert(createFederatedID=dict(**create_params))
[ "def", "create", "(", "self", ",", "first_name", "=", "None", ",", "last_name", "=", "None", ",", "country", "=", "None", ",", "email", "=", "None", ",", "on_conflict", "=", "IfAlreadyExistsOptions", ".", "ignoreIfAlreadyExists", ")", ":", "# first validate th...
Create the user on the Adobe back end. See [Issue 32](https://github.com/adobe-apiplatform/umapi-client.py/issues/32): because we retry create calls if they time out, the default conflict handling for creation is to ignore the create call if the user already exists (possibly from an earlier call that timed out). :param first_name: (optional) user first name :param last_name: (optional) user last name :param country: (optional except for Federated ID) user 2-letter ISO country code :param email: user email, if not already specified at create time :param on_conflict: IfAlreadyExistsOption (or string name thereof) controlling creation of existing users :return: the User, so you can do User(...).create(...).add_to_groups(...)
[ "Create", "the", "user", "on", "the", "Adobe", "back", "end", ".", "See", "[", "Issue", "32", "]", "(", "https", ":", "//", "github", ".", "com", "/", "adobe", "-", "apiplatform", "/", "umapi", "-", "client", ".", "py", "/", "issues", "/", "32", ...
1c446d79643cc8615adaa23e12dce3ac5782cf76
https://github.com/adobe-apiplatform/umapi-client.py/blob/1c446d79643cc8615adaa23e12dce3ac5782cf76/umapi_client/functional.py#L116-L156
train