signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def _get_log_likelihood_cl_func(self):
return SimpleCLFunction.from_string('''<STR_LIT>''' + self._ll_func.get_cl_function_name() + '''<STR_LIT>''', dependencies=[self._ll_func])<EOL>
Get the CL log likelihood compute function. This uses local reduction to compute the log likelihood for every observation in CL local space. The results are then summed in the first work item and returned using a pointer. Returns: str: the CL code for the log likelihood compute fun...
f15532:c0:m10
def __init__(self, ll_func, log_prior_func, x0, proposal_stds, use_random_scan=False,<EOL>finalize_proposal_func=None, **kwargs):
super().__init__(ll_func, log_prior_func, x0, **kwargs)<EOL>self._proposal_stds = np.require(np.copy(proposal_stds), requirements='<STR_LIT>',<EOL>dtype=self._cl_runtime_info.mot_float_dtype)<EOL>self._use_random_scan = use_random_scan<EOL>self._finalize_proposal_func = finalize_proposal_func or SimpleCLFunction.from_s...
An abstract basis for Random Walk Metropolis (RWM) samplers. Random Walk Metropolis (RWM) samplers require for every parameter and every modeling instance an proposal standard deviation, used in the random walk. Args: ll_func (mot.lib.cl_function.CLFunction): The log-likelihood fun...
f15532:c1:m0
def _get_mcmc_method_kernel_data_elements(self):
return {'<STR_LIT>': Array(self._proposal_stds, '<STR_LIT>', mode='<STR_LIT>', ensure_zero_copy=True),<EOL>'<STR_LIT>': LocalMemory('<STR_LIT>', nmr_items=<NUM_LIT:1> + self._nmr_params)}<EOL>
Get the mcmc method kernel data elements. Used by :meth:`_get_mcmc_method_kernel_data`.
f15532:c1:m2
def _get_proposal_update_function(self, nmr_samples, thinning, return_output):
return '''<STR_LIT>'''<EOL>
Get the proposal update function. Returns: str: the update function for the proposal standard deviations. Should be a string with CL code with the signature: .. code-block:: c void _updateProposalState(_mcmc_method_data* method_data, ...
f15532:c1:m3
def _at_acceptance_callback_c_func(self):
return '''<STR_LIT>'''<EOL>
Get a CL function that is to be applied at the moment a sample is accepted. Returns: str: a piece of C code to be applied when the function is accepted. Should be a string with CL code with the signature: .. code-block:: c void _sampleAccepted(_m...
f15532:c1:m4
def get_samples(self):
raise NotImplementedError()<EOL>
Get the matrix containing the sample results. Returns: ndarray: the sampled parameter maps, a (d, p, n) array with for d problems and p parameters n samples.
f15532:c2:m0
def get_log_likelihoods(self):
raise NotImplementedError()<EOL>
Get per set of sampled parameters the log likelihood value associated with that set of parameters. Returns: ndarray: the log likelihood values, a (d, n) array with for d problems and n samples the log likelihood value.
f15532:c2:m1
def get_log_priors(self):
raise NotImplementedError()<EOL>
Get per set of sampled parameters the log prior value associated with that set of parameters. Returns: ndarray: the log prior values, a (d, n) array with for d problems and n samples the prior value.
f15532:c2:m2
def __init__(self, samples, log_likelihoods, log_priors):
self._samples = samples<EOL>self._log_likelihood = log_likelihoods<EOL>self._log_prior = log_priors<EOL>
Simple storage container for the sample output
f15532:c3:m0
def __init__(self, ll_func, log_prior_func, x0, proposal_stds, target_acceptance_rate=<NUM_LIT>,<EOL>batch_size=<NUM_LIT:50>, damping_factor=<NUM_LIT:1>, min_val=<NUM_LIT>, max_val=<NUM_LIT>, **kwargs):
super().__init__(ll_func, log_prior_func, x0, proposal_stds, **kwargs)<EOL>self._target_acceptance_rate = target_acceptance_rate<EOL>self._batch_size = batch_size<EOL>self._damping_factor = damping_factor<EOL>self._min_val = min_val<EOL>self._max_val = max_val<EOL>self._acceptance_counter = np.zeros((self._nmr_problems...
r"""An implementation of the Adaptive Metropolis-Within-Gibbs (AMWG) MCMC algorithm [1]. This scales the proposal parameter (typically the std) such that it oscillates towards the chosen acceptance rate. We implement the delta function (see [1]) as: :math:`\delta(n) = \sqrt{1 / (d*n)}`. Where n...
f15533:c0:m0
def __init__(self, ll_func, log_prior_func, x0, proposal_stds,<EOL>waiting_period=<NUM_LIT:100>, scaling_factor=<NUM_LIT>, epsilon=<NUM_LIT>, **kwargs):
super().__init__(ll_func, log_prior_func, x0, proposal_stds, **kwargs)<EOL>self._waiting_period = waiting_period<EOL>self._scaling_factor = scaling_factor<EOL>self._epsilon = epsilon<EOL>if is_scalar(self._epsilon):<EOL><INDENT>self._epsilon = np.ones(x0.shape[<NUM_LIT:1>]) * self._epsilon<EOL><DEDENT>self._parameter_m...
r"""An implementation of the Single Component Adaptive Metropolis (SCAM) MCMC algorithm [1]. The SCAM method works by adapting the proposal standard deviation to the empirical standard deviation of the component's marginal distribution. That is, the standard deviation :math:`\sigma_i^{(t)}` for the pro...
f15534:c0:m0
def __init__(self, ll_func, log_prior_func, x0, proposal_stds, **kwargs):
super().__init__(ll_func, log_prior_func, x0, proposal_stds, **kwargs)<EOL>
r"""An implementation of the Metropolis-Within-Gibbs MCMC algorithm [1]. This does not scale the proposal standard deviations during sampling. Args: ll_func (mot.lib.cl_function.CLFunction): The log-likelihood function. See parent docs. log_prior_func (mot.lib.cl_function.CLFun...
f15535:c0:m0
def __init__(self, ll_func, log_prior_func, x0, x1, finalize_proposal_func=None,<EOL>subset_size=<NUM_LIT:4>, walk_scale=<NUM_LIT>, traverse_scale=<NUM_LIT:6>,<EOL>move_probabilities=(<NUM_LIT>/<NUM_LIT>, <NUM_LIT>/<NUM_LIT>, <NUM_LIT:1>/<NUM_LIT>, <NUM_LIT:1>/<NUM_LIT>), **kwargs):
super().__init__(ll_func, log_prior_func, x0, **kwargs)<EOL>self._subset_size = subset_size<EOL>self._param_choose_prob = min(self._nmr_params, self._subset_size) / (float(self._nmr_params))<EOL>self._walk_scale = walk_scale<EOL>self._traverse_scale = traverse_scale<EOL>self._move_probabilities = move_probabilities<EOL...
The thoughtful- or traverse- walk MCMC algorithm. The t-walk (twalk) algorithm of Christen and Fox [1] is a general-purpose MCMC algorithm that requires no tuning, is scale-invariant, is technically non-adaptive (but self-adjusting), and can sample from target distributions with arbitrary scale...
f15537:c0:m0
def compute_log_likelihood(ll_func, parameters, data=None, cl_runtime_info=None):
def get_cl_function():<EOL><INDENT>nmr_params = parameters.shape[<NUM_LIT:1>]<EOL>if len(parameters.shape) > <NUM_LIT:2>:<EOL><INDENT>return SimpleCLFunction.from_string('''<STR_LIT>''' + str(nmr_params) + '''<STR_LIT>''' + str(parameters.shape[<NUM_LIT:2>]) + '''<STR_LIT>''' + str(nmr_params) + '''<STR_LIT>''' + str(p...
Calculate and return the log likelihood of the given model for the given parameters. This calculates the log likelihoods for every problem in the model (typically after optimization), or a log likelihood for every sample of every model (typically after sample). In the case of the first (after optimization)...
f15538:m0
def compute_objective_value(objective_func, parameters, data=None, cl_runtime_info=None):
return objective_func.evaluate({'<STR_LIT:data>': data, '<STR_LIT>': Array(parameters, '<STR_LIT>', mode='<STR_LIT:r>')},<EOL>parameters.shape[<NUM_LIT:0>], use_local_reduction=True, cl_runtime_info=cl_runtime_info)<EOL>
Calculate and return the objective function value of the given model for the given parameters. Args: objective_func (mot.lib.cl_function.CLFunction): A CL function with the signature: .. code-block:: c double <func_name>(local const mot_float_type* const x, ...
f15538:m1
def estimate_hessian(objective_func, parameters,<EOL>lower_bounds=None, upper_bounds=None,<EOL>step_ratio=<NUM_LIT:2>, nmr_steps=<NUM_LIT:5>,<EOL>max_step_sizes=None,<EOL>data=None, cl_runtime_info=None):
if len(parameters.shape) == <NUM_LIT:1>:<EOL><INDENT>parameters = parameters[None, :]<EOL><DEDENT>nmr_voxels = parameters.shape[<NUM_LIT:0>]<EOL>nmr_params = parameters.shape[<NUM_LIT:1>]<EOL>nmr_derivatives = nmr_params * (nmr_params + <NUM_LIT:1>) // <NUM_LIT:2><EOL>initial_step = _get_initial_step(parameters, lower_...
Estimate and return the upper triangular elements of the Hessian of the given function at the given parameters. This calculates the Hessian using central difference (using a 2nd order Taylor expansion) with a Richardson extrapolation over the proposed sequence of steps. If enough steps are given, we apply a Wy...
f15539:m0
def _get_numdiff_hessian_element_func(objective_func, nmr_steps, step_ratio):
return SimpleCLFunction.from_string('''<STR_LIT>''' + str(nmr_steps) + '''<STR_LIT>''', dependencies=[<EOL>_get_numdiff_hessian_steps_func(objective_func, nmr_steps, step_ratio),<EOL>_get_numdiff_hessian_richardson_extrapolation_func(nmr_steps, step_ratio),<EOL>_get_numdiff_wynn_extrapolation_func(),<EOL>_get_numdiff_f...
Return a function to compute one element of the Hessian matrix.
f15539:m1
def _get_numdiff_hessian_steps_func(objective_func, nmr_steps, step_ratio):
return SimpleCLFunction.from_string('''<STR_LIT>''' + str(nmr_steps) + '''<STR_LIT>''' + str(float(step_ratio)) + '''<STR_LIT>''' + str(nmr_steps) + '''<STR_LIT>''' + str(float(step_ratio)) + '''<STR_LIT>''' + str(float(step_ratio)) + '''<STR_LIT>''', dependencies=[SimpleCLFunction.from_string('''<STR_LIT>''' + objecti...
Get a function to compute the multiple step sizes for a single element of the Hessian.
f15539:m2
def _get_initial_step(parameters, lower_bounds, upper_bounds, max_step_sizes):
nmr_params = parameters.shape[<NUM_LIT:1>]<EOL>initial_step = np.zeros_like(parameters)<EOL>if max_step_sizes is None:<EOL><INDENT>max_step_sizes = <NUM_LIT:0.1><EOL><DEDENT>if isinstance(max_step_sizes, Number):<EOL><INDENT>max_step_sizes = [max_step_sizes] * nmr_params<EOL><DEDENT>max_step_sizes = np.array(max_step_s...
Get an initial step size to use for every parameter. This chooses the step sizes based on the maximum step size and the lower and upper bounds. Args: parameters (ndarray): The parameters at which to evaluate the gradient. A (d, p) matrix with d problems, p parameters and n samples. ...
f15539:m6
def __init__(self):
super().__init__('''<STR_LIT>''')<EOL>
Get the Richardson extrapolation function.
f15539:c0:m0
def multivariate_ess(samples, batch_size_generator=None):
samples_generator = _get_sample_generator(samples)<EOL>return np.array(multiprocess_mapping(_MultivariateESSMultiProcessing(batch_size_generator), samples_generator()))<EOL>
r"""Estimate the multivariate Effective Sample Size for the samples of every problem. This essentially applies :func:`estimate_multivariate_ess` to every problem. Args: samples (ndarray, dict or generator): either a matrix of shape (d, p, n) with d problems, p parameters and n samples, or ...
f15540:m0
def univariate_ess(samples, method='<STR_LIT>', **kwargs):
samples_generator = _get_sample_generator(samples)<EOL>return np.array(multiprocess_mapping(_UnivariateESSMultiProcessing(method, **kwargs), samples_generator()))<EOL>
r"""Estimate the univariate Effective Sample Size for the samples of every problem. This computes the ESS using: .. math:: ESS(X) = n * \frac{\lambda^{2}}{\sigma^{2}} Where :math:`\lambda` is the standard deviation of the chain and :math:`\sigma` is estimated using the monte ...
f15540:m1
def _get_sample_generator(samples):
if isinstance(samples, Mapping):<EOL><INDENT>def samples_generator():<EOL><INDENT>for ind in range(samples[list(samples.keys())[<NUM_LIT:0>]].shape[<NUM_LIT:0>]):<EOL><INDENT>yield np.array([samples[s][ind, :] for s in sorted(samples)])<EOL><DEDENT><DEDENT><DEDENT>elif isinstance(samples, np.ndarray):<EOL><INDENT>def s...
Get a sample generator from the given polymorphic input. Args: samples (ndarray, dict or generator): either an matrix of shape (d, p, n) with d problems, p parameters and n samples, or a dictionary with for every parameter a matrix with shape (d, n) or, finally, a generator function...
f15540:m2
def get_auto_correlation(chain, lag):
normalized_chain = chain - np.mean(chain, dtype=np.float64)<EOL>lagged_mean = np.mean(normalized_chain[:len(chain) - lag] * normalized_chain[lag:], dtype=np.float64)<EOL>return lagged_mean / np.var(chain, dtype=np.float64)<EOL>
r"""Estimates the auto correlation for the given chain (1d vector) with the given lag. Given a lag :math:`k`, the auto correlation coefficient :math:`\rho_{k}` is estimated as: .. math:: \hat{\rho}_{k} = \frac{E[(X_{t} - \mu)(X_{t + k} - \mu)]}{\sigma^{2}} Please note that this equation only wor...
f15540:m3
def get_auto_correlation_time(chain, max_lag=None):
max_lag = max_lag or min(len(chain) // <NUM_LIT:3>, <NUM_LIT:1000>)<EOL>normalized_chain = chain - np.mean(chain, dtype=np.float64)<EOL>previous_accoeff = <NUM_LIT:0><EOL>auto_corr_sum = <NUM_LIT:0><EOL>for lag in range(<NUM_LIT:1>, max_lag):<EOL><INDENT>auto_correlation_coeff = np.mean(normalized_chain[:len(chain) - l...
r"""Compute the auto correlation time up to the given lag for the given chain (1d vector). This will halt when the maximum lag :math:`m` is reached or when the sum of two consecutive lags for any odd lag is lower or equal to zero. The auto correlation sum is estimated as: .. math:: \tau = 1 ...
f15540:m4
def estimate_univariate_ess_autocorrelation(chain, max_lag=None):
return len(chain) / (<NUM_LIT:1> + <NUM_LIT:2> * get_auto_correlation_time(chain, max_lag))<EOL>
r"""Estimate effective sample size (ESS) using the autocorrelation of the chain. The ESS is an estimate of the size of an iid sample with the same variance as the current sample. This function implements the ESS as described in Kass et al. (1998) and Robert and Casella (2004; p. 500): .. math:: E...
f15540:m5
def estimate_univariate_ess_standard_error(chain, batch_size_generator=None, compute_method=None):
sigma = (monte_carlo_standard_error(chain, batch_size_generator=batch_size_generator,<EOL>compute_method=compute_method) ** <NUM_LIT:2> * len(chain))<EOL>lambda_ = np.var(chain, dtype=np.float64)<EOL>return len(chain) * (lambda_ / sigma)<EOL>
r"""Compute the univariate ESS using the standard error method. This computes the ESS using: .. math:: ESS(X) = n * \frac{\lambda^{2}}{\sigma^{2}} Where :math:`\lambda` is the standard deviation of the chain and :math:`\sigma` is estimated using the monte carlo standard error (which in turn ...
f15540:m6
def minimum_multivariate_ess(nmr_params, alpha=<NUM_LIT>, epsilon=<NUM_LIT>):
tmp = <NUM_LIT> / nmr_params<EOL>log_min_ess = tmp * np.log(<NUM_LIT:2>) + np.log(np.pi) - tmp * (np.log(nmr_params) + gammaln(nmr_params / <NUM_LIT:2>))+ np.log(chi2.ppf(<NUM_LIT:1> - alpha, nmr_params)) - <NUM_LIT:2> * np.log(epsilon)<EOL>return int(round(np.exp(log_min_ess)))<EOL>
r"""Calculate the minimum multivariate Effective Sample Size you will need to obtain the desired precision. This implements the inequality from Vats et al. (2016): .. math:: \widehat{ESS} \geq \frac{2^{2/p}\pi}{(p\Gamma(p/2))^{2/p}} \frac{\chi^{2}_{1-\alpha,p}}{\epsilon^{2}} Where :math:`p` is t...
f15540:m7
def multivariate_ess_precision(nmr_params, multi_variate_ess, alpha=<NUM_LIT>):
tmp = <NUM_LIT> / nmr_params<EOL>log_min_ess = tmp * np.log(<NUM_LIT:2>) + np.log(np.pi) - tmp * (np.log(nmr_params) + gammaln(nmr_params / <NUM_LIT:2>))+ np.log(chi2.ppf(<NUM_LIT:1> - alpha, nmr_params)) - np.log(multi_variate_ess)<EOL>return np.sqrt(np.exp(log_min_ess))<EOL>
r"""Calculate the precision given your multivariate Effective Sample Size. Given that you obtained :math:`ESS` multivariate effective samples in your estimate you can calculate the precision with which you approximated your desired confidence region. This implements the inequality from Vats et al. (2016),...
f15540:m8
def estimate_multivariate_ess_sigma(samples, batch_size):
sample_means = np.mean(samples, axis=<NUM_LIT:1>, dtype=np.float64)<EOL>nmr_params, chain_length = samples.shape<EOL>nmr_batches = int(np.floor(chain_length / batch_size))<EOL>sigma = np.zeros((nmr_params, nmr_params))<EOL>nmr_offsets = chain_length - nmr_batches * batch_size + <NUM_LIT:1><EOL>for offset in range(nmr_o...
r"""Calculates the Sigma matrix which is part of the multivariate ESS calculation. This implementation is based on the Matlab implementation found at: https://github.com/lacerbi/multiESS The Sigma matrix is defined as: .. math:: \Sigma = \Lambda + 2 * \sum_{k=1}^{\infty}{Cov(Y_{1}, Y_{1+k})} ...
f15540:m9
def estimate_multivariate_ess(samples, batch_size_generator=None, full_output=False):
batch_size_generator = batch_size_generator or SquareRootSingleBatch()<EOL>batch_sizes = batch_size_generator.get_multivariate_ess_batch_sizes(*samples.shape)<EOL>nmr_params, chain_length = samples.shape<EOL>nmr_batches = len(batch_sizes)<EOL>det_lambda = det(np.cov(samples))<EOL>ess_estimates = np.zeros(nmr_batches)<E...
r"""Compute the multivariate Effective Sample Size of your (single instance set of) samples. This multivariate ESS is defined in Vats et al. (2016) and is given by: .. math:: ESS = n \bigg(\frac{|\Lambda|}{|\Sigma|}\bigg)^{1/p} Where :math:`n` is the number of samples, :math:`p` the number of pa...
f15540:m10
def monte_carlo_standard_error(chain, batch_size_generator=None, compute_method=None):
batch_size_generator = batch_size_generator or SquareRootSingleBatch()<EOL>compute_method = compute_method or BatchMeansMCSE()<EOL>batch_sizes = batch_size_generator.get_univariate_ess_batch_sizes(len(chain))<EOL>return np.min(list(compute_method.compute_standard_error(chain, b) for b in batch_sizes))<EOL>
Compute Monte Carlo standard errors for the expectations This is a convenience function that calls the compute method for each batch size and returns the lowest ESS over the used batch sizes. Args: chain (ndarray): the Markov chain batch_size_generator (UniVariateESSBatchSizeGenerator): th...
f15540:m11
def __init__(self, batch_size_generator):
self._batch_size_generator = batch_size_generator<EOL>
Used in the function :func:`multivariate_ess` to estimate the multivariate ESS using multiprocessing.
f15540:c0:m0
def __init__(self, method, **kwargs):
self._method = method<EOL>self._kwargs = kwargs<EOL>
Used in the function :func:`univariate_ess` to estimate the univariate ESS using multiprocessing.
f15540:c1:m0
def get_multivariate_ess_batch_sizes(self, nmr_params, chain_length):
r"""Get the batch sizes to use for the calculation of the Effective Sample Size (ESS). This should return a list of batch sizes that the ESS calculation will use to determine :math:`\Sigma` Args: nmr_params (int): the number of parameters in the samples chain_length (int): the ...
f15540:c2:m0
def get_univariate_ess_batch_sizes(self, chain_length):
r"""Get the batch sizes to use for the calculation of the univariate Effective Sample Size (ESS). This should return a list of batch sizes that the ESS calculation will use to determine :math:`\sigma` Args: chain_length (int): the length of the chain Returns: list: the...
f15540:c3:m0
def __init__(self, nmr_batches=<NUM_LIT:200>):
self._nmr_batches = nmr_batches<EOL>
r"""Returns a number of batch sizes from which the ESS algorithm will select the one with the lowest ESS. This is a conservative choice since the lowest ESS of all batch sizes is chosen. The batch sizes are generated as linearly spaced values in: .. math:: \Big[ n^{1/4}, max(\lfl...
f15540:c6:m0
def compute_standard_error(self, chain, batch_size):
raise NotImplementedError()<EOL>
Compute the standard error of the given chain and the given batch size. Args: chain (ndarray): the chain for which to compute the SE batch_size (int): batch size or window size to use in the computations Returns: float: the Monte Carlo Standard Error
f15540:c7:m0
def get_nmr_constraints(self):
raise NotImplementedError()<EOL>
Get the number of constraints defined in this function. Returns: int: the number of constraints defined in this function.
f15541:c1:m0
@classmethod<EOL><INDENT>def from_string(cls, cl_function, dependencies=(), nmr_constraints=None):<DEDENT>
return_type, function_name, parameter_list, body = split_cl_function(cl_function)<EOL>return SimpleConstraintFunction(return_type, function_name, parameter_list, body, dependencies=dependencies,<EOL>nmr_constraints=nmr_constraints)<EOL>
Parse the given CL function into a SimpleCLFunction object. Args: cl_function (str): the function we wish to turn into an object dependencies (list or tuple of CLLibrary): The list of CL libraries this function depends on Returns: SimpleCLFunction: the CL data type ...
f15541:c2:m1
def minimize(func, x0, data=None, method=None, lower_bounds=None, upper_bounds=None, constraints_func=None,<EOL>nmr_observations=None, cl_runtime_info=None, options=None):
if not method:<EOL><INDENT>method = '<STR_LIT>'<EOL><DEDENT>cl_runtime_info = cl_runtime_info or CLRuntimeInfo()<EOL>if len(x0.shape) < <NUM_LIT:2>:<EOL><INDENT>x0 = x0[..., None]<EOL><DEDENT>lower_bounds = _bounds_to_array(lower_bounds or np.ones(x0.shape[<NUM_LIT:1>]) * -np.inf)<EOL>upper_bounds = _bounds_to_array(up...
Minimization of one or more variables. For an easy wrapper of function maximization, see :func:`maximize`. All boundary conditions are enforced using the penalty method. That is, we optimize the objective function: .. math:: F(x) = f(x) \mu \sum \max(0, g_i(x))^2 where :math:`F(x)` is the n...
f15542:m0
def _bounds_to_array(bounds):
elements = []<EOL>for value in bounds:<EOL><INDENT>if all_elements_equal(value):<EOL><INDENT>elements.append(Scalar(get_single_value(value), ctype='<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>elements.append(Array(value, ctype='<STR_LIT>', as_scalar=True))<EOL><DEDENT><DEDENT>return CompositeArray(elements, '<STR_LIT>',...
Create a CompositeArray to hold the bounds.
f15542:m1
def maximize(func, x0, nmr_observations, **kwargs):
wrapped_func = SimpleCLFunction.from_string('''<STR_LIT>''' + func.get_cl_function_name() + '''<STR_LIT>''' + func.get_cl_function_name() + '''<STR_LIT>''' + str(nmr_observations) + '''<STR_LIT>''', dependencies=[func])<EOL>kwargs['<STR_LIT>'] = nmr_observations<EOL>return minimize(wrapped_func, x0, **kwargs)<EOL>
Maximization of a function. This wraps the objective function to take the negative of the computed values and passes it then on to one of the minimization routines. Args: func (mot.lib.cl_function.CLFunction): A CL function with the signature: .. code-block:: c double...
f15542:m2
def get_minimizer_options(method):
if method == '<STR_LIT>':<EOL><INDENT>return {'<STR_LIT>': <NUM_LIT:2>,<EOL>'<STR_LIT>': None,<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return {'<STR_LIT>': <NUM_LIT:200>,<EOL>'<STR_LIT>': <NUM_LIT:1.0>, '<STR_LIT>': <NUM_LIT:0.5>, '<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT:0...
Return a dictionary with the default options for the given minimization method. Args: method (str): the name of the method we want the options off Returns: dict: a dictionary with the default options
f15542:m3
def _clean_options(method, provided_options):
provided_options = provided_options or {}<EOL>default_options = get_minimizer_options(method)<EOL>result = {}<EOL>for name, default in default_options.items():<EOL><INDENT>if name in provided_options:<EOL><INDENT>result[name] = provided_options[name]<EOL><DEDENT>else:<EOL><INDENT>result[name] = default_options[name]<EO...
Clean the given input options. This will make sure that all options are present, either with their default values or with the given values, and that no other options are present then those supported. Args: method (str): the method name provided_options (dict): the given options Return...
f15542:m4
def _minimize_powell(func, x0, cl_runtime_info, lower_bounds, upper_bounds,<EOL>constraints_func=None, data=None, options=None):
options = options or {}<EOL>nmr_problems = x0.shape[<NUM_LIT:0>]<EOL>nmr_parameters = x0.shape[<NUM_LIT:1>]<EOL>penalty_data, penalty_func = _get_penalty_function(nmr_parameters, constraints_func)<EOL>eval_func = SimpleCLFunction.from_string('''<STR_LIT>''' + str(options.get('<STR_LIT>', <NUM_LIT>)) + '''<STR_LIT>''' +...
Options: patience (int): Used to set the maximum number of iterations to patience*(number_of_parameters+1) reset_method (str): one of 'EXTRAPOLATED_POINT' or 'RESET_TO_IDENTITY' lower case or upper case. patience_line_search (int): the patience of the searching algorithm. Defaults to the same patien...
f15542:m5
def _minimize_nmsimplex(func, x0, cl_runtime_info, lower_bounds, upper_bounds,<EOL>constraints_func=None, data=None, options=None):
options = options or {}<EOL>nmr_problems = x0.shape[<NUM_LIT:0>]<EOL>nmr_parameters = x0.shape[<NUM_LIT:1>]<EOL>penalty_data, penalty_func = _get_penalty_function(nmr_parameters, constraints_func)<EOL>eval_func = SimpleCLFunction.from_string('''<STR_LIT>''' + str(options.get('<STR_LIT>', <NUM_LIT>)) + '''<STR_LIT>''' +...
Use the Nelder-Mead simplex method to calculate the optimimum. The scales should satisfy the following constraints: .. code-block:: python alpha > 0 0 < beta < 1 gamma > 1 gamma > alpha 0 < delta < 1 Options: patience (int): Used to...
f15542:m6
def _minimize_subplex(func, x0, cl_runtime_info, lower_bounds, upper_bounds,<EOL>constraints_func=None, data=None, options=None):
options = options or {}<EOL>nmr_problems = x0.shape[<NUM_LIT:0>]<EOL>nmr_parameters = x0.shape[<NUM_LIT:1>]<EOL>penalty_data, penalty_func = _get_penalty_function(nmr_parameters, constraints_func)<EOL>eval_func = SimpleCLFunction.from_string('''<STR_LIT>''' + str(options.get('<STR_LIT>', <NUM_LIT>)) + '''<STR_LIT>''' +...
Variation on the Nelder-Mead Simplex method by Thomas H. Rowan. This method uses NMSimplex to search subspace regions for the minimum. See Rowan's thesis titled "Functional Stability analysis of numerical algorithms" for more details. The scales should satisfy the following constraints: .. code-...
f15542:m7
def _lm_numdiff_jacobian(eval_func, nmr_params, nmr_observations):
return SimpleCLFunction.from_string(r'''<STR_LIT>''' + str(nmr_params) + '''<STR_LIT>''' + str(nmr_observations) + '''<STR_LIT>''', dependencies=[eval_func, SimpleCLFunction.from_string('''<STR_LIT>''' + str(nmr_observations) + '''<STR_LIT>''' + eval_func.get_cl_function_name() + '''<STR_LIT>''' + eval_func.get_cl_func...
Get a numerical differentiated Jacobian function. This computes the Jacobian of the observations (function vector) with respect to the parameters. Args: eval_func (mot.lib.cl_function.CLFunction): the evaluation function nmr_params (int): the number of parameters nmr_observations (int)...
f15542:m9
def _get_penalty_function(nmr_parameters, constraints_func=None):
dependencies = []<EOL>data_requirements = {'<STR_LIT>': LocalMemory('<STR_LIT>', <NUM_LIT:1>)}<EOL>constraints_code = '<STR_LIT>'<EOL>if constraints_func and constraints_func.get_nmr_constraints() > <NUM_LIT:0>:<EOL><INDENT>nmr_constraints = constraints_func.get_nmr_constraints()<EOL>dependencies.append(constraints_fun...
Get a function to compute the penalty term for the boundary conditions. This is meant to be used in the evaluation function of the optimization routines. Args: nmr_parameters (int): the number of parameters in the model constraints_func (mot.optimize.base.ConstraintFunction): function to compu...
f15542:m10
def fit_gaussian(samples, ddof=<NUM_LIT:0>):
if len(samples.shape) == <NUM_LIT:1>:<EOL><INDENT>return np.mean(samples), np.std(samples, ddof=ddof)<EOL><DEDENT>return np.mean(samples, axis=<NUM_LIT:1>), np.std(samples, axis=<NUM_LIT:1>, ddof=ddof)<EOL>
Calculates the mean and the standard deviation of the given samples. Args: samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all values. If two dimensional, we fit the Gaussian for every set of samples over the first dimension. ddof (int): ...
f15543:m0
def fit_circular_gaussian(samples, high=np.pi, low=<NUM_LIT:0>):
cl_func = SimpleCLFunction.from_string('''<STR_LIT>''')<EOL>def run_cl(samples):<EOL><INDENT>data = {'<STR_LIT>': Array(samples, '<STR_LIT>'),<EOL>'<STR_LIT>': Zeros(samples.shape[<NUM_LIT:0>], '<STR_LIT>'),<EOL>'<STR_LIT>': Zeros(samples.shape[<NUM_LIT:0>], '<STR_LIT>'),<EOL>'<STR_LIT>': Scalar(samples.shape[<NUM_LIT:...
Compute the circular mean for samples in a range Args: samples (ndarray): a one or two dimensional array. If one dimensional we calculate the fit using all values. If two dimensional, we fit the Gaussian for every set of samples over the first dimension. high (float): The maximum wrap p...
f15543:m1
def fit_truncated_gaussian(samples, lower_bounds, upper_bounds):
if len(samples.shape) == <NUM_LIT:1>:<EOL><INDENT>return _TruncatedNormalFitter()((samples, lower_bounds, upper_bounds))<EOL><DEDENT>def item_generator():<EOL><INDENT>for ind in range(samples.shape[<NUM_LIT:0>]):<EOL><INDENT>if is_scalar(lower_bounds):<EOL><INDENT>lower_bound = lower_bounds<EOL><DEDENT>else:<EOL><INDEN...
Fits a truncated gaussian distribution on the given samples. This will do a maximum likelihood estimation of a truncated Gaussian on the provided samples, with the truncation points given by the lower and upper bounds. Args: samples (ndarray): a one or two dimensional array. If one dimensional we ...
f15543:m2
def gaussian_overlapping_coefficient(means_0, stds_0, means_1, stds_1, lower=None, upper=None):
if lower is None:<EOL><INDENT>lower = -np.inf<EOL><DEDENT>if upper is None:<EOL><INDENT>upper = np.inf<EOL><DEDENT>def point_iterator():<EOL><INDENT>for ind in range(means_0.shape[<NUM_LIT:0>]):<EOL><INDENT>yield np.squeeze(means_0[ind]), np.squeeze(stds_0[ind]), np.squeeze(means_1[ind]), np.squeeze(stds_1[ind])<EOL><D...
Compute the overlapping coefficient of two Gaussian continuous_distributions. This computes the :math:`\int_{-\infty}^{\infty}{\min(f(x), g(x))\partial x}` where :math:`f \sim \mathcal{N}(\mu_0, \sigma_0^{2})` and :math:`f \sim \mathcal{N}(\mu_1, \sigma_1^{2})` are normally distributed variables. This...
f15543:m3
def deviance_information_criterions(mean_posterior_lls, ll_per_sample):
mean_deviance = -<NUM_LIT:2> * np.mean(ll_per_sample, axis=<NUM_LIT:1>)<EOL>deviance_at_mean = -<NUM_LIT:2> * mean_posterior_lls<EOL>pd_2002 = mean_deviance - deviance_at_mean<EOL>pd_2004 = np.var(ll_per_sample, axis=<NUM_LIT:1>) / <NUM_LIT><EOL>return {'<STR_LIT>': np.nan_to_num(mean_deviance + pd_2002),<EOL>'<STR_LIT...
r"""Calculates the Deviance Information Criteria (DIC) using three methods. This returns a dictionary returning the ``DIC_2002``, the ``DIC_2004`` and the ``DIC_Ando_2011`` method. The first is based on Spiegelhalter et al (2002), the second based on Gelman et al. (2004) and the last on Ando (2011). All ca...
f15543:m4
def __init__(self, lower, upper):
self.lower = lower<EOL>self.upper = upper<EOL>
Helper routine for :func:`gaussian_overlapping_coefficient`. This calculates the overlap between two Normal distribution by taking the integral from lower to upper over min(f, g).
f15543:c0:m0
def __call__(self, data):
m0, std0, m1, std1 = data<EOL>def overlap_func(x):<EOL><INDENT>fx = norm.pdf(x, m0, std0)<EOL>gx = norm.pdf(x, m1, std1)<EOL>return min(fx, gx)<EOL><DEDENT>return scipy.integrate.quad(overlap_func, self.lower, self.upper)[<NUM_LIT:0>]<EOL>
Compute the overlap. This expects data to be a tuple consisting of :math:`\mu_0, \sigma_0, \mu_1, \sigma_1`. Returns: float: the overlap between the two Gaussians.
f15543:c0:m1
def __call__(self, item):
samples, lower_bound, upper_bound = item<EOL>scaling_factor = <NUM_LIT:10> ** -np.round(np.log10(np.mean(samples)))<EOL>result = minimize(_TruncatedNormalFitter.truncated_normal_log_likelihood,<EOL>np.array([np.mean(samples), np.std(samples)]) * scaling_factor,<EOL>args=(lower_bound * scaling_factor,<EOL>upper_bound * ...
Fit the mean and std of the truncated normal to the given samples. Helper function of :func:`fit_truncated_gaussian`.
f15543:c1:m0
@staticmethod<EOL><INDENT>def truncated_normal_log_likelihood(params, low, high, data):<DEDENT>
mu = params[<NUM_LIT:0>]<EOL>sigma = params[<NUM_LIT:1>]<EOL>if sigma == <NUM_LIT:0>:<EOL><INDENT>return np.inf<EOL><DEDENT>ll = np.sum(norm.logpdf(data, mu, sigma))<EOL>ll -= len(data) * np.log((norm.cdf(high, mu, sigma) - norm.cdf(low, mu, sigma)))<EOL>return -ll<EOL>
Calculate the log likelihood of the truncated normal distribution. Args: params: tuple with (mean, std), the parameters under which we evaluate the model low (float): the lower truncation bound high (float): the upper truncation bound data (ndarray): the one dime...
f15543:c1:m1
@staticmethod<EOL><INDENT>def truncated_normal_ll_gradient(params, low, high, data):<DEDENT>
if params[<NUM_LIT:1>] == <NUM_LIT:0>:<EOL><INDENT>return np.array([np.inf, np.inf])<EOL><DEDENT>return np.array([_TruncatedNormalFitter.partial_derivative_mu(params[<NUM_LIT:0>], params[<NUM_LIT:1>], low, high, data),<EOL>_TruncatedNormalFitter.partial_derivative_sigma(params[<NUM_LIT:0>], params[<NUM_LIT:1>], low, hi...
Return the gradient of the log likelihood of the truncated normal at the given position. Args: params: tuple with (mean, std), the parameters under which we evaluate the model low (float): the lower truncation bound high (float): the upper truncation bound data (...
f15543:c1:m2
@staticmethod<EOL><INDENT>def partial_derivative_mu(mu, sigma, low, high, data):<DEDENT>
pd_mu = np.sum(data - mu) / sigma ** <NUM_LIT:2><EOL>pd_mu -= len(data) * ((norm.pdf(low, mu, sigma) - norm.pdf(high, mu, sigma))<EOL>/ (norm.cdf(high, mu, sigma) - norm.cdf(low, mu, sigma)))<EOL>return -pd_mu<EOL>
The partial derivative with respect to the mean. Args: mu (float): the mean of the truncated normal sigma (float): the std of the truncated normal low (float): the lower truncation bound high (float): the upper truncation bound data (ndarray): the one...
f15543:c1:m3
@staticmethod<EOL><INDENT>def partial_derivative_sigma(mu, sigma, low, high, data):<DEDENT>
pd_sigma = np.sum(-(<NUM_LIT:1> / sigma) + ((data - mu) ** <NUM_LIT:2> / (sigma ** <NUM_LIT:3>)))<EOL>pd_sigma -= len(data) * (((low - mu) * norm.pdf(low, mu, sigma) - (high - mu) * norm.pdf(high, mu, sigma))<EOL>/ (sigma * (norm.cdf(high, mu, sigma) - norm.cdf(low, mu, sigma))))<EOL>return -pd_sigma<EOL>
The partial derivative with respect to the standard deviation. Args: mu (float): the mean of the truncated normal sigma (float): the std of the truncated normal low (float): the lower truncation bound high (float): the upper truncation bound data (nda...
f15543:c1:m4
def get_cl_environments():
return _config['<STR_LIT>']<EOL>
Get the current CL environment to use during CL calculations. Returns: list of CLEnvironment: the current list of CL environments.
f15544:m0
def set_cl_environments(cl_environments):
if not cl_environments:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>_config['<STR_LIT>'] = cl_environments<EOL>
Set the current CL environments to the given list Please note that this will change the global configuration, i.e. this is a persistent change. If you do not want a persistent state change, consider using :func:`~mot.configuration.config_context` instead. Args: cl_environments (list of CLEnvironme...
f15544:m1
def get_compile_flags():
return list(_config['<STR_LIT>'])<EOL>
Get the default compile flags to use in a CL routine. Returns: list: the default list of compile flags we wish to use
f15544:m2
def set_compile_flags(compile_flags):
_config['<STR_LIT>'] = compile_flags<EOL>
Set the current compile flags. Args: compile_flags (list): the new list of compile flags
f15544:m3
def set_default_proposal_update(proposal_update):
_config['<STR_LIT>'] = proposal_update<EOL>
Set the default proposal update function to use in sample. Please note that this will change the global configuration, i.e. this is a persistent change. If you do not want a persistent state change, consider using :func:`~mot.configuration.config_context` instead. Args: mot.model_building.paramete...
f15544:m4
def use_double_precision():
return _config['<STR_LIT>']<EOL>
Check if we run the computations in default precision or not. Returns: boolean: if we run the computations in double precision or not
f15544:m5
def set_use_double_precision(double_precision):
_config['<STR_LIT>'] = double_precision<EOL>
Set the default use of double precision. Returns: boolean: if we use double precision by default or not
f15544:m6
@contextmanager<EOL>def config_context(config_action):
config_action.apply()<EOL>yield<EOL>config_action.unapply()<EOL>
Creates a context in which the config action is applied and unapplies the configuration after execution. Args: config_action (ConfigAction): the configuration action to use
f15544:m7
def __init__(self):
Defines a configuration action for use in a configuration context. This should define an apply and unapply function that sets and unsets the configuration options. The applying action needs to remember the state before the application of the action.
f15544:c0:m0
def apply(self):
Apply the current action to the current runtime configuration.
f15544:c0:m1
def unapply(self):
Reset the current configuration to the previous state.
f15544:c0:m2
def __init__(self):
super().__init__()<EOL>self._old_config = {}<EOL>
Defines a default implementation of a configuration action. This simple config implements a default ``apply()`` method that saves the current state and a default ``unapply()`` that restores the previous state. For developers, it is easiest to implement ``_apply()`` such that you do not manuall...
f15544:c1:m0
def apply(self):
self._old_config = {k: v for k, v in _config.items()}<EOL>self._apply()<EOL>
Apply the current action to the current runtime configuration.
f15544:c1:m1
def unapply(self):
for key, value in self._old_config.items():<EOL><INDENT>_config[key] = value<EOL><DEDENT>
Reset the current configuration to the previous state.
f15544:c1:m2
def _apply(self):
Implement this function add apply() logic after this class saves the current config.
f15544:c1:m3
def __init__(self, cl_runtime_info):
super().__init__()<EOL>self._cl_runtime_info = cl_runtime_info<EOL>
Set the current configuration to use the information in the given configuration action. Args: cl_runtime_info (CLRuntimeInfo): the runtime info with the configuration options
f15544:c2:m0
def __init__(self, cl_environments=None, compile_flags=None, double_precision=None):
super().__init__()<EOL>self._cl_environments = cl_environments<EOL>self._compile_flags = compile_flags<EOL>self._double_precision = double_precision<EOL>
Updates the runtime settings. Args: cl_environments (list of CLEnvironment): the new CL environments we wish to use for future computations compile_flags (list): the list of compile flags to use during analysis. double_precision (boolean): if we compute in double precision o...
f15544:c3:m0
def __init__(self):
super().__init__()<EOL>
Does nothing, useful as a default config action.
f15544:c4:m0
def __init__(self, cl_environments=None, compile_flags=None, double_precision=None):
self._cl_environments = cl_environments<EOL>self._compile_flags = compile_flags<EOL>self._double_precision = double_precision<EOL>if self._cl_environments is None:<EOL><INDENT>self._cl_environments = get_cl_environments()<EOL><DEDENT>if self._compile_flags is None:<EOL><INDENT>self._compile_flags = get_compile_flags()<...
All information necessary for applying operations using OpenCL. Args: cl_environments (list of mot.lib.cl_environments.CLEnvironment): The list of CL environments used by this routine. If None is given we use the defaults in the current configuration. compile_flags (list...
f15544:c5:m0
@property<EOL><INDENT>def compile_flags(self):<DEDENT>
return self._compile_flags<EOL>
Get all defined compile flags.
f15544:c5:m4
def smart_device_selection():
from mot.lib.cl_environments import CLEnvironmentFactory<EOL>return CLEnvironmentFactory.smart_device_selection()<EOL>
Get a list of device environments that is suitable for use in MOT. Returns: list of CLEnvironment: List with the CL device environments.
f15545:m0
def __init__(self):
super().__init__(<EOL>'<STR_LIT>', '<STR_LIT>', [],<EOL>resource_filename('<STR_LIT>', '<STR_LIT>'))<EOL>
Calculate the cerf.
f15547:c0:m0
def __init__(self):
super().__init__(<EOL>'<STR_LIT>',<EOL>dependencies=[CerfImWOfX()])<EOL>
Calculate the imaginary error function for a real argument (special case). Compute erfi(x) = -i erf(ix), the imaginary error function.
f15547:c2:m0
def __init__(self):
super().__init__('''<STR_LIT>''')<EOL>
Compute the Probability Density Function of the Gaussian distribution.
f15548:c0:m0
def __init__(self):
super().__init__('''<STR_LIT>''')<EOL>
Compute the log of the Probability Density Function of the Gaussian distribution.
f15548:c1:m0
def __init__(self):
super().__init__('''<STR_LIT>''')<EOL>
Compute the Cumulative Distribution Function of the Gaussian distribution.
f15548:c2:m0
def __init__(self):
super().__init__('''<STR_LIT>''', dependencies=(_ndtri(),))<EOL>
Computes the inverse of the cumulative distribution function of the Gaussian distribution. This is the inverse of the Gaussian CDF.
f15548:c3:m0
def __init__(self):
super().__init__('''<STR_LIT>''', dependencies=(polevl(), p1evl()))<EOL>
Inverse of Normal distribution function. Code taken from Scipy (https://github.com/scipy/scipy/blob/master/scipy/special/cephes/NDTRI.c), 05-05-2018. Returns the argument, x, for which the area under the Gaussian probability density function (integrated from minus infinity to x) is equal to y....
f15548:c4:m0
def __init__(self):
super().__init__('''<STR_LIT>''')<EOL>
r"""Computes the Gamma probability density function using the shape and scale parameterization. This computes the gamma PDF as: .. math:: {\frac{1}{\Gamma (k)\theta ^{k}}}x^{k-1}e^{-{\frac {x}{\theta }}} With :math:`x` the desired position, :math:`k` the shape and :math:`\theta`...
f15550:c0:m0
def __init__(self):
super().__init__('''<STR_LIT>''')<EOL>
r"""Computes the log of the Gamma probability density function using the shape and scale parameterization. This computes the gamma PDF as: .. math:: \frac{-x}{\theta} + (k-1)\ln(x) - \ln(\Gamma(k)) - k * \ln(\theta) With :math:`x` the desired position, :math:`k` the shape and :m...
f15550:c1:m0
def __init__(self):
super().__init__('''<STR_LIT>''', dependencies=(igam(),))<EOL>
r"""Calculate the Cumulative Distribution Function of the Gamma function. This computes: ``lower_incomplete_gamma(k, x/theta) / gamma(k)`` With k the shape parameter, theta the scale parameter, lower_incomplete_gamma the lower incomplete gamma function and gamma the complete gamma function. ...
f15550:c2:m0
def __init__(self):
super().__init__('''<STR_LIT>''', dependencies=(igami(),))<EOL>
Computes the inverse of the cumulative distribution function of the Gamma distribution. This is the inverse of the Gamma CDF.
f15550:c3:m0
def __init__(self):
super().__init__('''<STR_LIT>''')<EOL>
r"""Approximate the Cumulative Distribution Function of the Gamma function. This uses the approximation from Revfeim [1] to compute the cdf for x given the shape and scale parameters. The approximation returns infinity for values near the tails of the distribution, i.e. where the cdf is near z...
f15550:c4:m0
def __init__(self):
super().__init__('''<STR_LIT>''')<EOL>
r"""Approximates the Gamma percentile point function. This uses the approximation from Revfeim [1] to compute the ppf for y given the shape and scale parameters. The approximation is not valid in the tails of the distribution, i.e. where the cdf is near zero or near one. Function argu...
f15550:c5:m0
def __init__(self):
super().__init__('''<STR_LIT>''', dependencies=(polevl(),))<EOL>
Helper function to computing the inverse gamma Copied from Scipy (https://github.com/scipy/scipy/blob/master/scipy/special/cephes/igami.c), 05-05-2018:: /* * Computation of the Incomplete Gamma Function Ratios and their Inverse * ARMIDO R. DIDONATO and ALFRED H. MORRIS, J...
f15550:c6:m0
def __init__(self):
super().__init__('''<STR_LIT>''')<EOL>
Helper function to computing the inverse gamma /* * Computation of the Incomplete Gamma Function Ratios and their Inverse * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. * ACM Transactions on Mathematical Software, Vol. 12, No. 4, * December 1986, Pages 377-393. * ...
f15550:c7:m0
def __init__(self):
super().__init__('''<STR_LIT>''', dependencies=(_find_inverse_s(), _didonato_SN()))<EOL>
Helper function to computing the inverse gamma. /* * In order to understand what's going on here, you will * need to refer to: * * Computation of the Incomplete Gamma Function Ratios and their Inverse * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. * ACM Tra...
f15550:c8:m0
def __init__(self):
super().__init__('''<STR_LIT>''', dependencies=(_igami_impl(), _igamci_impl(), _find_inverse_gamma(), igam_fac(), igam()))<EOL>
Copied from Scipy (https://github.com/scipy/scipy/blob/master/scipy/special/cephes/igami.c), 05-05-2018.
f15550:c9:m0