output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Returns a normalized request string as described in iN OAuth 2 MAC spec. | Make a summary of the following Python 3 code
def get_normalized_request_string(method, url, nonce, params, ext='', body_hash=None):
urlparts = urlparse.urlparse(url)
if urlparts.query:
norm_url = '%s?%s' % (urlparts.path, urlparts.query)
elif params:
norm_url = '%s?%s' % (urlparts.path, get... | You are a Python code generator, capable of creating scripts from specifications. |
def get_body_hash(params):
"""
Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec.
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2
"""
norm_params = get_normalized_params(params)
return binascii.b2a_base64(hashlib.sha1(norm_params).digest())[:-1] | How would you implement a function in Python 3 that
returns the body hash of the given params. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns HMAC - SHA1 signature | How would you explain what the following Python 3 function does
def get_mac_signature(api_secret, norm_request_string):
hashed = hmac.new(str(api_secret), norm_request_string, hashlib.sha1)
return binascii.b2a_base64(hashed.digest())[:-1] | You are a Python code generator, capable of creating scripts from specifications. |
open file and return contents. | Explain what the following Python 3 code does
def open_file(self, access_mode="r"):
try:
with open(self, access_mode, encoding='utf-8') as file:
return file.read()
except IOError:
print(self + " File not found.")
sys.exit(0) | As a Python code composer, you craft elegant and concise scripts. |
This method computes the forward and backward steps for the internal state of the HMM. | Can you generate the documentation for the following Python 3 function
def _forward_backward(self, itraj):
# get parameters
A = self._hmm.transition_matrix
pi = self._hmm.initial_distribution
obs = self._observations[itraj]
T = len(obs)
# compute output probability matrix... | You are a Python code generator, capable of creating scripts from specifications. |
def _update_model(self, gammas, count_matrices, maxiter=10000000):
"""
Maximization step: Updates the HMM model given the hidden state assignment and count matrices
Parameters
----------
gamma : [ ndarray(T,N, dtype=float) ]
list of state probabilities for each traje... | Create a Python 3 function for
updating the HMM model given the hidden state assignment and count matrices. | You are a Python code architect, reviewing and designing scalable and efficient code |
Computes the viterbi paths for the current trajectory and returns a numpy array of the paths. | Make a summary of the following Python 3 code
def compute_viterbi_paths(self):
# get parameters
K = len(self._observations)
A = self._hmm.transition_matrix
pi = self._hmm.initial_distribution
# compute viterbi path for each trajectory
paths = np.empty(K, dtype=object)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def fit(self):
"""
Maximum-likelihood estimation of the HMM using the Baum-Welch algorithm
Returns
-------
model : HMM
The maximum likelihood HMM model.
"""
logger().info("=================================================================")
lo... | How would you code a function in Python 3 to
fit the maximum likelihood estimation of the HMM using Baum - Welch algorithm. | As a Python code composer, you craft elegant and concise scripts. |
Generate random samples from a Gaussian distribution. | Can you generate a brief explanation for the following Python 3 code
def sample_gaussian(mean, covar, covariance_type='diag', n_samples=1,
random_state=None):
"""Generate random samples from a Gaussian distribution.
Parameters
----------
mean : array_like, shape (n_features,)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _covar_mstep_diag(gmm, X, responsibilities, weighted_X_sum, norm,
min_covar):
"""Performing the covariance M step for diagonal cases"""
avg_X2 = np.dot(responsibilities.T, X * X) * norm
avg_means2 = gmm.means_ ** 2
avg_X_means = gmm.means_ * weighted_X_sum * norm
return avg... | Write a Python 3 script to
perform the covariance M step for diagonal cases | As a Python code composer, you craft elegant and concise scripts. |
def _covar_mstep_spherical(*args):
"""Performing the covariance M step for spherical cases"""
cv = _covar_mstep_diag(*args)
return np.tile(cv.mean(axis=1)[:, np.newaxis], (1, cv.shape[1])) | Can you create a Python 3 function that
performs the covariance M step for spherical cases | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _covar_mstep_full(gmm, X, responsibilities, weighted_X_sum, norm,
min_covar):
"""Performing the covariance M step for full cases"""
# Eq. 12 from K. Murphy, "Fitting a Conditional Linear Gaussian
# Distribution"
n_features = X.shape[1]
cv = np.empty((gmm.n_components, n_fea... | Write a Python 3 function for
performing the covariance M step for full cases. | As a python code expert, you are capable of creating scripts from specifications. |
def _get_covars(self):
"""Covariance parameters for each mixture component.
The shape depends on `cvtype`::
(`n_states`, 'n_features') if 'spherical',
(`n_features`, `n_features`) if 'tied',
(`n_states`, `n_features`) if 'di... | How would you implement a function in Python 3 that
returns the covariance parameters for each mixture component. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _set_covars(self, covars):
"""Provide values for covariance"""
covars = np.asarray(covars)
_validate_covars(covars, self.covariance_type, self.n_components)
self.covars_ = covars | Write a Python 3 function for
providing values for covariance | As a Python code analyst, you investigate and solve complex coding mysteries |
def score_samples(self, X):
"""Return the per-sample likelihood of the data under the model.
Compute the log probability of X under the model and
return the posterior distribution (responsibilities) of each
mixture component for each element of X.
Parameters
----------
... | Create a Python 3 function to
compute the log probability of each data point in X and return the posterior distribution of each mixture component of each element of X. | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the log probability under the model. | How would you explain what the following Python 3 function does
def score(self, X, y=None):
logprob, _ = self.score_samples(X)
return logprob | You are a Python code architect, reviewing and designing scalable and efficient code |
def predict(self, X):
"""Predict label for data.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = (n_samples,)
"""
logprob, responsibilities = self.score_samples(X)
return responsibi... | Can you write a function in Python 3 where it
predicts label for data. | As a Python code composer, you craft elegant and concise scripts. |
def sample(self, n_samples=1, random_state=None):
"""Generate random samples from the model.
Parameters
----------
n_samples : int, optional
Number of samples to generate. Defaults to 1.
Returns
-------
X : array_like, shape (n_samples, n_features)
... | Can you write a function in Python 3 where it
generates random samples from the model. | As a Python code analyst, you investigate and solve complex coding mysteries |
def fit(self, X, y=None):
"""Estimate model parameters with the expectation-maximization
algorithm.
A initialization step is performed before entering the em
algorithm. If you want to avoid this step, set the keyword
argument init_params to the empty string '' when creating the
... | Implement a function in Python 3 to
estimate model parameters with the expectation-maximization algorithm. A initialization step is performed before entering the em algorithm. If you want to avoid this step, set the keyword argument init_params to the empty string '' when creating the GMM object. Likewise, if you would... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _do_mstep(self, X, responsibilities, params, min_covar=0):
""" Perform the Mstep of the EM algorithm and return the class weihgts.
"""
weights = responsibilities.sum(axis=0)
weighted_X_sum = np.dot(responsibilities.T, X)
inverse_weights = 1.0 / (weights[:, np.newaxis] + 10 * ... | Implement a function in Python 3 to
perform the Mstep of the EM algorithm and return the class weihgts. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the number of free parameters in the model. | Given the following Python 3 function, write the documentation
def _n_parameters(self):
ndim = self.means_.shape[1]
if self.covariance_type == 'full':
cov_params = self.n_components * ndim * (ndim + 1) / 2.
elif self.covariance_type == 'diag':
cov_params = self.n_componen... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the parameter names for the estimator | Can you generate a brief explanation for the following Python 3 code
def _get_param_names(cls):
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, 'deprecated_original', cls.__init__)
if init is object.__init__:
... | As a python code expert, you are capable of creating scripts from specifications. |
def set_params(self, **params):
"""Set the parameters of this estimator.
The method works on simple estimators as well as on nested objects
(such as pipelines). The former have parameters of the form
``<component>__<parameter>`` so that it's possible to update each
component of ... | Implement a Python 3 function for
setting the parameters of this object. | As a Python code composer, you craft elegant and concise scripts. |
Generate an initial model with 1D - Gaussian output densities for a set of observations. | Make a summary of the following Python 3 code
def init_model_gaussian1d(observations, nstates, reversible=True):
ntrajectories = len(observations)
# Concatenate all observations.
collected_observations = np.array([], dtype=config.dtype)
for o_t in observations:
collected_observations = np.appen... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the output probability density of a single observation from all hidden states. | Make a summary of the following Python 3 code
def _p_o(self, o):
if self.__impl__ == self.__IMPL_C__:
return gc.p_o(o, self.means, self.sigmas, out=None, dtype=type(o))
elif self.__impl__ == self.__IMPL_PYTHON__:
if np.any(self.sigmas < np.finfo(self.sigmas.dtype).eps):
... | As a Python code composer, you craft elegant and concise scripts. |
Returns the output probabilities for an observation model and synthetic observation trajectory. | Can you tell what is the following Python 3 function doing
def p_obs(self, obs, out=None):
if self.__impl__ == self.__IMPL_C__:
res = gc.p_obs(obs, self.means, self.sigmas, out=out, dtype=config.dtype)
return self._handle_outliers(res)
elif self.__impl__ == self.__IMPL_PYTHON__:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def estimate(self, observations, weights):
"""
Fits the output model given the observations and weights
Parameters
----------
observations : [ ndarray(T_k,) ] with K elements
A list of K observation trajectories, each having length T_k and d dimensions
weight... | Write a Python 3 function that can
fit the output model given the observations and weights. | You are a Python code architect, reviewing and designing scalable and efficient code |
Sample a new set of distribution parameters given a sample of observations from the given state. | Given the following Python 3 function, write the documentation
def sample(self, observations, prior=None):
for state_index in range(self.nstates):
# Update state emission distribution parameters.
observations_in_state = observations[state_index]
# Determine number of samples... | As a python code expert, you are capable of creating scripts from specifications. |
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
-------
... | Can you implement a function in Python 3 that
generates a synthetic observation data from a given state. | As a Python code analyst, you investigate and solve complex coding mysteries |
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 numbe... | How would you implement a function in Python 3 that
generates synthetic observation data from a given state. | As a Python code composer, you craft elegant and concise scripts. |
def generate_observation_trajectory(self, s_t):
"""
Generate synthetic observation data from a given state sequence.
Parameters
----------
s_t : numpy.array with shape (T,) of int type
s_t[t] is the hidden state sampled at time t
Returns
-------
... | Implement a function in Python 3 to
generate synthetic observation data from a given state sequence. | You are a Python code generator, capable of creating scripts from specifications. |
r Returns the samples of the initial distribution | Can you tell what is the following Python 3 function doing
def initial_distribution_samples(self):
res = np.empty((self.nsamples, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].stationary_distribution
return res | You are a Python code architect, reviewing and designing scalable and efficient code |
r Returns a numpy array of the lifetimes of the timescales | Can you generate the documentation for the following Python 3 function
def lifetimes_samples(self):
res = np.empty((self.nsamples, self.nstates), dtype=config.dtype)
for i in range(self.nsamples):
res[i, :] = self._sampled_hmms[i].lifetimes
return res | As a Python code translator, you convert algorithms and pseudocode into 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':... | How would you implement a function in Python 3 that
sets the implementation of this module. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the element - wise logarithm of the output probabilities for an entire trajectory and all hidden states. | How would you explain what the following Python 3 function does
def log_p_obs(self, obs, out=None, dtype=np.float32):
if out is None:
return np.log(self.p_obs(obs))
else:
self.p_obs(obs, out=out, dtype=dtype)
np.log(out, out=out)
return out | As a Python code composer, you craft elegant and concise scripts. |
Sets observation probabilities of outliers to uniform if ignore_outliers is set. | Can you generate a brief explanation for the following Python 3 code
def _handle_outliers(self, p_o):
if self.ignore_outliers:
outliers = np.where(p_o.sum(axis=1)==0)[0]
if outliers.size > 0:
p_o[outliers, :] = 1.0
self.found_outliers = True
return... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 obser... | Write a Python 3 script to
compute the forward term of the given sequence A and B. | You are a Python code architect, reviewing and designing scalable and efficient code |
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 probab... | How would you implement a function in Python 3 that
computes all backward coefficients of the hidden states A and pobs. | You are a Python code generator, capable of creating scripts from specifications. |
Sum for all t the probability to transition from state i to state j. | Can you generate the documentation for the following Python 3 function
def transition_counts(alpha, beta, A, pobs, T=None, out=None, dtype=np.float32):
# set T
if T is None:
T = pobs.shape[0] # if not set, use the length of pobs as trajectory length
elif T > pobs.shape[0]:
raise ValueError(... | As a Python code composer, you craft elegant and concise scripts. |
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 observa... | Implement a Python 3 function for
estimating the hidden pathway of maximum likelihood using the Viterbi algorithm. | You are a Python code architect, reviewing and designing scalable and efficient code |
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 ... | How would you implement a function in Python 3 that
samples from the path of the hidden state. | As a python code expert, you are capable of creating scripts from specifications. |
Coarse grain transition matrix P using memberships M | Make a summary of the following Python 3 code
def coarse_grain_transition_matrix(P, M):
# coarse-grain matrix: Pc = (M' M)^-1 M' P M
W = np.linalg.inv(np.dot(M.T, M))
A = np.dot(np.dot(M.T, P), M)
P_coarse = np.dot(W, A)
# this coarse-graining can lead to negative elements. Setting them to zero her... | As a python code expert, you are capable of creating scripts from specifications. |
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.
Avoid... | Can you create a Python 3 function that
regularizes the hidden initial distribution and transition matrix P. | You are a Python code architect, reviewing and designing scalable and efficient code |
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 stu... | Can you create a Python 3 function that
regularizes the output probabilities of the given set of observed states. | As a Python code analyst, you investigate and solve complex coding mysteries |
Initializes discrete HMM using spectral clustering of observation counts C_full. | Can you generate the documentation for the following Python 3 function
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 observatio... | As a python code expert, you are capable of creating scripts from specifications. |
Initializes discrete HMM using maximum likelihood of observation counts | How would you explain what the following Python 3 function does
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"""
rais... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Returns True if the MSM is stationary. | Can you generate the documentation for the following Python 3 function
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.allclo... | As a python code expert, you are capable of creating scripts from specifications. |
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 distri... | How would you code a function in Python 3 to
compute the stationary distribution of hidden states if possible. | As a Python code composer, you craft elegant and concise scripts. |
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
:ma... | Create a Python 3 function for
returning the relaxation timescales of the hidden transition matrix. | As a python code expert, you are capable of creating scripts from specifications. |
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_{... | Implement a Python 3 function for
returning the lifetimes of the hidden transition matrix. | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Returns the HMM restricted to the selected subset of states | Given the following Python 3 function, write the documentation
def sub_hmm(self, states):
# restrict initial distribution
pi_sub = self._Pi[states]
pi_sub /= pi_sub.sum()
# restrict transition matrix
P_sub = self._Tij[states, :][:, states]
# checks if this selection is p... | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the transition count matrix from the hidden state trajectory. | Given the following Python 3 function, write the documentation
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.... | You are a Python code analyst, evaluating scripts for potential improvements. |
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 h... | Create a Python 3 function for
computing the counts at the first time step | As a Python code analyst, you investigate and solve complex coding mysteries |
Collect a vector of all observations belonging to a specified hidden state. | Here you have a function in Python 3, explain what it does
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
----------
... | You are a Python code analyst, evaluating scripts for potential improvements. |
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 :... | Implement a function in Python 3 to
generate a synthetic state trajectory. | As a Python code composer, you craft elegant and concise scripts. |
Generate a synthetic state trajectory for an equilibrium realization. | How would you explain what the following Python 3 function does
def generate_synthetic_observation_trajectory(self, length, initial_Pi=None):
# First, generate synthetic state trajetory.
s_t = self.generate_synthetic_state_trajectory(length, initial_Pi=initial_Pi)
# Next, generate observations ... | As a Python code translator, you convert algorithms and pseudocode into 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 :... | Write a Python 3 function for
generating a number of synthetic realization of observables from this model. | As a Python code composer, you craft elegant and concise scripts. |
def nb_to_python(nb_path):
"""convert notebook to python script"""
exporter = python.PythonExporter()
output, resources = exporter.from_filename(nb_path)
return output | Implement a Python 3 function for
converting notebook to python script | As a Python code composer, you craft elegant and concise scripts. |
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... | Write a Python 3 script for
converting notebook to html | As a python code expert, you are capable of creating scripts from specifications. |
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)
... | Implement a function in Python 3 to
return the output probabilities for an entire trajectory and all hidden states at time point t. | As a python code expert, you are capable of creating scripts from specifications. |
Sample a new set of distribution parameters given a sample of observations from the given state. | Can you generate the documentation for the following Python 3 function
def sample(self, observations_by_state):
from numpy.random import dirichlet
N, M = self._output_probabilities.shape # nstates, nsymbols
for i, obs_by_state in enumerate(observations_by_state):
# count symbols fou... | As a python code expert, you are capable of creating scripts from specifications. |
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
-------
... | Write a Python 3 script to
generate a single synthetic observation data from a given state. | You are a Python code architect, reviewing and designing scalable and efficient code |
Generate synthetic observation data from a given state. | Can you tell what is the following Python 3 function doing
def generate_observations_from_state(self, state_index, nobs):
import scipy.stats
gen = scipy.stats.rv_discrete(values=(range(self._nsymbols), self._output_probabilities[state_index]))
gen.rvs(size=nobs) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate synthetic observation data from a given state sequence. | Can you generate a brief explanation for the following Python 3 code
def generate_observation_trajectory(self, s_t, dtype=None):
if dtype is None:
dtype = np.int32
# Determine number of samples to generate.
T = s_t.shape[0]
nsymbols = self._output_probabilities.shape[1]
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets the implementation of this module
| Given the following Python 3 function, write the documentation
def set_implementation(impl):
global __impl__
if impl.lower() == 'python':
__impl__ = __IMPL_PYTHON__
elif impl.lower() == 'c':
__impl__ = __IMPL_C__
else:
import warnings
warnings.warn('Implementation '+impl+... | You are a Python code generator, capable of creating scripts from specifications. |
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... | How would you implement a function in Python 3 that
computes P ( obs | A B pi ) and all forward coefficients. | As a Python code composer, you craft elegant and concise scripts. |
Compute all backward coefficients of the hidden states A. | Here you have a function in Python 3, explain what it does
def backward(A, pobs, T=None, beta_out=None):
if __impl__ == __IMPL_PYTHON__:
return ip.backward(A, pobs, T=T, beta_out=beta_out, dtype=config.dtype)
elif __impl__ == __IMPL_C__:
return ic.backward(A, pobs, T=T, beta_out=beta_out, dtype=... | You are a Python code analyst, evaluating scripts for potential improvements. |
Calculates the probability matrix for being in state i at time t. | Can you generate the documentation for the following Python 3 function
def state_probabilities(alpha, beta, T=None, gamma_out=None):
# get summation helper - we use matrix multiplication with 1's because it's faster than the np.sum function (yes!)
global ones_size
if ones_size != alpha.shape[1]:
glo... | You are a Python code generator, capable of creating scripts from specifications. |
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
... | How would you implement a function in Python 3 that
sums the probabilities of being in state i to time t | You are a Python code analyst, evaluating scripts for potential improvements. |
Sum for all t the probability to transition from state i to state j. | Can you tell what is the following Python 3 function doing
def transition_counts(alpha, beta, A, pobs, T=None, out=None):
if __impl__ == __IMPL_PYTHON__:
return ip.transition_counts(alpha, beta, A, pobs, T=T, out=out, dtype=config.dtype)
elif __impl__ == __IMPL_C__:
return ic.transition_counts(a... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Estimate the hidden pathway of maximum likelihood using the Viterbi algorithm. | How would you explain what the following Python 3 function does
def viterbi(A, pobs, pi):
if __impl__ == __IMPL_PYTHON__:
return ip.viterbi(A, pobs, pi, dtype=config.dtype)
elif __impl__ == __IMPL_C__:
return ic.viterbi(A, pobs, pi, dtype=config.dtype)
else:
raise RuntimeError('Nonex... | You are a Python code generator, capable of creating scripts from specifications. |
Sample the hidden pathway S from the conditional distribution P. | Can you tell what is the following Python 3 function doing
def sample_path(alpha, A, pobs, T=None):
if __impl__ == __IMPL_PYTHON__:
return ip.sample_path(alpha, A, pobs, T=T, dtype=config.dtype)
elif __impl__ == __IMPL_C__:
return ic.sample_path(alpha, A, pobs, T=T, dtype=config.dtype)
else:... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates a logger instance associated with the given name. | Can you tell what is the following Python 3 function doing
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 ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Sample from the BHMM posterior. | Can you generate the documentation for the following Python 3 function
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 sampl... | You are a Python code generator, capable of creating scripts from specifications. |
Update the current model using one round of Gibbs sampling. | Make a summary of the following Python 3 code
def _update(self):
initial_time = time.time()
self._updateHiddenStateTrajectories()
self._updateEmissionProbabilities()
self._updateTransitionMatrix()
final_time = time.time()
elapsed_time = final_time - initial_time
... | You are a Python code architect, reviewing and designing scalable and efficient code |
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._sampleHiddenStateT... | Implement a function in Python 3 to
update the hidden state trajectories attribute of the current state model. | As a Python code analyst, you investigate and solve complex coding mysteries |
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, o... | Can you write a function in Python 3 where it
samples a hidden state trajectory from the conditional distribution P s | T E o. | As a python code expert, you are capable of creating scripts from specifications. |
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.nstat... | How would you code a function in Python 3 to
update the emission probabilites of the current state. | You are a Python code generator, capable of creating scripts from specifications. |
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... | How would you implement a function in Python 3 that
updates the hidden - state transition matrix and the initial distribution. | You are a Python code architect, reviewing and designing scalable and efficient code |
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,... | Can you create a Python 3 function that
initializes using an MLHMM and generate a model | You are a Python code generator, capable of creating scripts from specifications. |
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.
"""
... | Create a Python 3 function to
compute the connected sets of the given count matrix. | You are a Python code analyst, evaluating scripts for potential improvements. |
Computes strongly connected closed sets of a single site. | Given the following Python 3 function, write the documentation
def closed_sets(C, mincount_connectivity=0):
n = np.shape(C)[0]
S = connected_sets(C, mincount_connectivity=mincount_connectivity, strong=True)
closed = []
for s in S:
mask = np.zeros(n, dtype=bool)
mask[s] = True
if ... | You are a Python code analyst, evaluating scripts for potential improvements. |
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
... | Can you create a Python 3 function that
returns the set of states that have at least one incoming or outgoing count. | As a Python code composer, you craft elegant and concise scripts. |
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_sta... | How would you code a function in Python 3 to
estimate full transition matrix for general connectivity structure. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function computes the partial reversible transition matrix. | Explain what the following Python 3 code does
def transition_matrix_partial_rev(C, P, S, maxiter=1000000, maxerr=1e-8):
# test input
assert np.array_equal(C.shape, P.shape)
# constants
A = C[S][:, S]
B = C[S][:, ~S]
ATA = A + A.T
countsums = C[S].sum(axis=1)
# initialize
X = 0.5 * AT... | You are a Python code generator, capable of creating scripts from specifications. |
Enforces transition matrix P to be reversible on its closed sets. | Explain what the following Python 3 code does
def enforce_reversible_on_closed(P):
import msmtools.analysis as msmana
n = np.shape(P)[0]
Prev = P.copy()
# treat each weakly connected set separately
sets = closed_sets(P)
for s in sets:
I = np.ix_(s, s)
# compute stationary probabi... | You are a Python code generator, capable of creating scripts from specifications. |
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):
... | Write a Python 3 function for
returning if P is reversible on its weakly connected sets. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Suggests a HMM model type based on the observation data. | Can you generate the documentation for the following Python 3 function
def _guess_output_type(observations):
from bhmm.util import types as _types
o1 = _np.array(observations[0])
# CASE: vector of int? Then we want a discrete HMM
if _types.is_int_vector(o1):
return 'discrete'
# CASE: not ... | As a Python code composer, you craft elegant and concise scripts. |
r Returns a list of observations that are subsampled at lag but shifted by 1. | How would you explain what the following Python 3 function does
def lag_observations(observations, lag, stride=1):
obsnew = []
for obs in observations:
for shift in range(0, lag, stride):
obs_lagged = (obs[shift:][::lag])
if len(obs_lagged) > 1:
obsnew.append(obs_... | You are a Python code architect, reviewing and designing scalable and efficient code |
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
sigma... | Write a Python 3 script to
initialize a 1D - Gaussian HMM with the given initial distribution pi P and means and sigmas. Returns a 1D - Gaussian HMM containing the current state of the current state. | As a Python code composer, you craft elegant and concise scripts. |
Initializes a discrete HMM with the given initial distribution P and pout. | Here you have a function in Python 3, explain what it does
def discrete_hmm(pi, P, pout):
from bhmm.hmm.discrete_hmm import DiscreteHMM
from bhmm.output_models.discrete import DiscreteOutputModel
# initialize output model
output_model = DiscreteOutputModel(pout)
# initialize general HMM
from bhm... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Use a heuristic scheme to generate an initial model for a set of states. | Here you have a function in Python 3, explain what it does
def init_hmm(observations, nstates, lag=1, output=None, reversible=True):
# select output model type
if output is None:
output = _guess_output_type(observations)
if output == 'discrete':
return init_discrete_hmm(observations, nstate... | As a python code expert, you are capable of creating scripts from specifications. |
Generate a new initial model for a gaussian model. | Can you generate a brief explanation for the following Python 3 code
def init_gaussian_hmm(observations, nstates, lag=1, reversible=True):
from bhmm.init import gaussian
if lag > 1:
observations = lag_observations(observations, lag)
hmm0 = gaussian.init_model_gaussian1d(observations, nstates, revers... | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate a discrete HMM for a given set of observations. | Given the following Python 3 function, write the documentation
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
---------... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Estimates the maximum - likelihood of a given set of observations. | How would you explain what the following Python 3 function does
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-l... | As a Python code analyst, you investigate and solve complex coding mysteries |
r Bayesian HMM based on sampling the observed data. | Make a summary of the following Python 3 code
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-... | You are a Python code analyst, evaluating scripts for potential improvements. |
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)
>... | Write a Python 3 script to
compute the sum of arr assuming arr is in the log domain. | You are a Python code generator, capable of creating scripts from specifications. |
Convert a sparse matrix to a given format. | Can you generate the documentation for the following Python 3 function
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.
Parameter... | As a Python code analyst, you investigate and solve complex coding mysteries |
Input validation on an array. | Can you tell what is the following Python 3 function doing
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, s... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a random set of confidence intervals for beta distributions. | Here you have a function in Python 3, explain what it does
def beta_confidence_intervals(ci_X, ntrials, ci=0.95):
# Compute low and high confidence interval for symmetric CI about mean.
ci_low = 0.5 - ci/2;
ci_high = 0.5 + ci/2;
# Compute for every element of ci_X.
from scipy.stats import beta
... | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.