text
stringlengths
81
112k
r""" Samples of the timescales 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
Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"] def set_implementation(self, impl): """ Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"]...
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 *dur...
Sets observation probabilities of outliers to uniform if ignore_outliers is set. Parameters ---------- p_o : ndarray((T, N)) output probabilities def _handle_outliers(self, p_o): """ Sets observation probabilities of outliers to uniform if ignore_outliers is set. Par...
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 : ...
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 : nda...
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...
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 hid...
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 t...
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 -----...
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 stat...
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 : ndar...
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 probabili...
Initializes discrete HMM using maximum likelihood of observation counts 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"""...
r""" Updates the transition matrix and recomputes all derived quantities 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) ...
r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution of the hidden transition matrix. def is_stationary(self): r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution of the hidden transition ...
r""" Compute stationary distribution of hidden states if possible. Raises ------ ValueError if the HMM is not stationary def stationary_distribution(self): r""" Compute stationary distribution of hidden states if possible. Raises ------ ValueError if the HMM is...
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 ...
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...
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 def sub_hmm(self, states): r""" Returns HMM on a subset of states Returns the HMM restricted to ...
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 raise...
Compute the counts at the first time step Returns ------- n : ndarray(nstates) n[i] is the number of trajectories starting in state i def count_init(self): """Compute the counts at the first time step Returns ------- n : ndarray(nstates) ...
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 retr...
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...
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...
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 sh...
convert notebook to python script def nb_to_python(nb_path): """convert notebook to python script""" exporter = python.PythonExporter() output, resources = exporter.from_filename(nb_path) return output
convert notebook 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)[...
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 ti...
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 li...
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 associate...
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...
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 ------- observation...
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[...
Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"] def set_implementation(impl): """ Sets the implementation of this module Parameters ---------- impl : str One of ["python", "c"] """ global __impl__ if impl.lowe...
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 : ...
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, optio...
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 th...
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) ...
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...
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 hid...
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...
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 logg...
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, defa...
Update the current model using one round of Gibbs sampling. def _update(self): """Update the current model using one round of Gibbs sampling. """ initial_time = time.time() self._updateHiddenStateTrajectories() self._updateEmissionProbabilities() self._updateTransition...
Sample a new set of state trajectories from the conditional distribution P(S | T, E, O) 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_...
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 returne...
Sample a new set of emission probabilites from the conditional distribution P(E | S, O) 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....
Updates the hidden-state transition matrix and the initial distribution 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 ...
Initialize using an MLHMM. 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 = MaximumLikelihood...
r"""Makes sure that dtraj is a discrete trajectory (array of int) 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 T...
r"""Makes sure that dtrajs is a list of discrete trajectories (array of int) 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): ...
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. def connected_sets(C, mincount_connectivity=0, strong=True): """ Computes...
Computes the strongly connected closed sets of C 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...
Returns the set of states that have at least one incoming or outgoing count 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 ...
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 ...
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 t...
Enforces transition matrix P to be reversible on its closed sets. 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 set...
Returns if P is reversible on its weakly connected sets 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, :][:,...
Simple estimator for stationary distribution for multiple strongly connected sets 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 msm...
r""" Samples of the Gaussian distribution means 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): ...
r""" Samples of the Gaussian distribution standard deviations 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(s...
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 obse...
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 witho...
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 deviatio...
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, ) Fi...
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, 'gaussia...
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. ...
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. reversi...
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 ...
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 ...
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....
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 allow...
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. ...
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...
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...
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. def generate_latex_table(sampled_hmm, conf=0.95, dt=1, time_unit='ms', obs_name='force', obs_units='pN', ...
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 me...
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 ar...
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 action...
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 em...
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 lis...
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 immed...
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 ...
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 succe...
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 def ma...
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 col...
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 pa...
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 comm...
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 def split(self, max_commands): """ Split this action into an equi...
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...
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...
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 def report_command_error(self, error_dict): """ ...
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 def execution_errors(self): """ Return a list of commands th...
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 def maybe_split_groups(self, max_groups): """ Check if group lists in add/remove direct...
Rerun the query (lazily). The results will contain any values on the server side that have changed since the last run. :return: None def reload(self): """ Rerun the query (lazily). The results will contain any values on the server side that have changed since the last run. ...
Fetch the next page of the query. 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, ...
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. def all_results(self): """ Eagerly fetch a...
Fetch the queried object. def _fetch_result(self): """ Fetch the queried object. """ self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params)
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...