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 func. | 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_string(<EOL>'<STR_LIT>')<EOL> | 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 function.
log_prior_func (mot.lib.cl_function.CLFunction): The log-prior function.
x0 (ndarray): the starting positions for the sampler. Should be a two dimensional matrix
with for every modeling instance (first dimension) and every parameter (second dimension) a value.
proposal_stds (ndarray): for every parameter and every modeling instance an initial proposal std.
use_random_scan (boolean): if we iterate over the parameters in a random order or in a linear order
at every sample iteration. By default we apply a system scan starting from the first dimension to the
last. With a random scan we randomize the indices every iteration.
finalize_proposal_func (mot.lib.cl_function.CLFunction): a CL function to finalize every proposal by
the sampling routine. This allows the model to change a proposal before computing the
prior or likelihood probabilities. If None, we will not use this callback.
As an example, suppose you are sampling a polar coordinate :math:`\theta` defined on
:math:`[0, 2\pi]` with a random walk Metropolis proposal distribution. This distribution might propose
positions outside of the range of :math:`\theta`. Of course the model function could deal with that by
taking the modulus of the input, but then you have to post-process the chain with the same
transformation. Instead, this function allows changing the proposal before it is put into the model
and before it will be stored in the chain.
This function should return a proposal that is equivalent (but not necessarily equal)
to the provided proposal.
Signature:
.. code-block:: c
void <func_name>(void* data, local mot_float_type* x); | 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,
ulong current_iteration,
global mot_float_type* current_position); | 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(_mcmc_method_data* method_data,
ulong current_iteration,
uint parameter_ind); | 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, self._nmr_params), dtype=np.uint64, order='<STR_LIT:C>')<EOL> | 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 is the current batch index and d is the damping factor. As an example, with a damping factor of 500,
delta reaches a scaling of 0.01 in 20 batches. At a batch size of 50 that would amount to 1000 samples.
In principal, AMWG can be used as a final MCMC algorithm if and only if the adaption is effectively zero.
That is when delta gets close enough to zero to no longer influence the proposals.
Args:
ll_func (mot.lib.cl_function.CLFunction): The log-likelihood function. See parent docs.
log_prior_func (mot.lib.cl_function.CLFunction): The log-prior function. See parent docs.
x0 (ndarray): the starting positions for the sampler. Should be a two dimensional matrix
with for every modeling instance (first dimension) and every parameter (second dimension) a value.
proposal_stds (ndarray): for every parameter and every modeling instance an initial proposal std.
target_acceptance_rate (float): the target acceptance rate between 0 and 1.
batch_size (int): the size of the batches in between which we update the parameters
damping_factor (int): how fast the adaptation moves to zero
min_val (float): the minimum value the standard deviation can take
max_val (float): the maximum value the standard deviation can take
References:
[1] Roberts GO, Rosenthal JS. Examples of adaptive MCMC. J Comput Graph Stat. 2009;18(2):349-367.
doi:10.1198/jcgs.2009.06134. | 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_means = np.zeros((self._nmr_problems, self._nmr_params),<EOL>dtype=self._cl_runtime_info.mot_float_dtype, order='<STR_LIT:C>')<EOL>self._parameter_variances = np.zeros((self._nmr_problems, self._nmr_params),<EOL>dtype=self._cl_runtime_info.mot_float_dtype, order='<STR_LIT:C>')<EOL>self._parameter_variance_update_m2s = np.zeros((self._nmr_problems, self._nmr_params),<EOL>dtype=self._cl_runtime_info.mot_float_dtype, order='<STR_LIT:C>')<EOL> | 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 proposal
distribution of the :math:`i` th component at time :math:`t` is given by:
.. math::
\sigma_i^{(t)} = \begin{cases}
\sigma_i^{(0)}, & t \leq t_s \\
2.4 * \sqrt{\mathrm{Var}(\mathbf{X}^{(0)}_i, \ldots, \mathbf{X}^{(t-1)}_i)} + 1\cdot \epsilon, & t > t_s
\end{cases}
where :math:`t_s` denotes the iteration after which the adaptation starts (we use :math:`t_s = 100`).
A small constant is necessary to prevent the standard deviation from shrinking to zero.
This adaptation algorithm has been proven to retain ergodicity, meaning it is guaranteed to converge to the
right stationary distribution [1].
Args:
ll_func (mot.lib.cl_function.CLFunction): The log-likelihood function. See parent docs.
log_prior_func (mot.lib.cl_function.CLFunction): The log-prior function. See parent docs.
x0 (ndarray): the starting positions for the sampler. Should be a two dimensional matrix
with for every modeling instance (first dimension) and every parameter (second dimension) a value.
proposal_stds (ndarray): for every parameter and every modeling instance an initial proposal std.
waiting_period (int): only start updating the proposal std. after this many draws.
scaling_factor (float): the scaling factor to use (the parameter ``s`` in the paper referenced).
epsilon (float or ndarray): small number to prevent the std. from collapsing to zero.
Can either be one value for all parameters, or one value per parameter.
References:
[1] Haario, H., Saksman, E., & Tamminen, J. (2005). Componentwise adaptation for high dimensional MCMC.
Computational Statistics, 20(2), 265-273. https://doi.org/10.1007/BF02789703 | 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.CLFunction): The log-prior function. See parent docs.
x0 (ndarray): the starting positions for the sampler. Should be a two dimensional matrix
with for every modeling instance (first dimension) and every parameter (second dimension) a value.
proposal_stds (ndarray): for every parameter and every modeling instance an initial proposal std.
References:
[1] 1. van Ravenzwaaij D, Cassey P, Brown SD. A simple introduction to Markov Chain Monte–Carlo sampling.
Psychon Bull Rev. 2016:1-12. doi:10.3758/s13423-016-1015-8. | 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>float_type = self._cl_runtime_info.mot_float_dtype<EOL>if x1.shape != x0.shape:<EOL><INDENT>self._x1 = np.require(np.tile(x1, (x0.shape[<NUM_LIT:0>], <NUM_LIT:1>)), requirements='<STR_LIT>', dtype=float_type)<EOL><DEDENT>else:<EOL><INDENT>self._x1 = np.require(np.copy(x1), requirements='<STR_LIT>', dtype=float_type)<EOL><DEDENT>self._x1_log_likelihood = np.zeros(self._nmr_problems, dtype=float_type)<EOL>self._x1_log_prior = np.zeros(self._nmr_problems, dtype=float_type)<EOL>self._finalize_proposal_func = finalize_proposal_func or SimpleCLFunction.from_string(<EOL>'<STR_LIT>')<EOL>self._initialize_likelihood_prior(self._x1, self._x1_log_likelihood, self._x1_log_prior)<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 and correlation structures. A random subset of one of two
vectors is moved around the state-space to influence one of two chains, per iteration.
Args:
ll_func (mot.lib.cl_function.CLFunction): The log-likelihood function.
log_prior_func (mot.lib.cl_function.CLFunction): The log-prior function.
x0 (ndarray): the starting positions for the sampler. Should be a two dimensional matrix
with for every modeling instance (first dimension) and every parameter (second dimension) a value.
x1 (ndarray): the second coordinate vector for every model instance. This should be of the same size as
``x0``, but then with different values. This basically defines the initial sampling space.
subset_size (int): the expected number of parameters to move in one step.
This is variable n_1 in the article [1]. If there are less parameters than the subset_size, we will
use all parameters.
walk_scale (float): the scalar of the walk move. This is parameter a_w in [1]. A reasonable range
given by [1] is [0.3, 2]
traverse_scale (float): the scalar of the traverse move. This is parameter a_t in [1]. A reasonable range
given by [1] is [2, 10]
move_probabilities (Tuple[float]): the probabilities of the four different moves supported in the
t-walk algorithm. Defaults to (0.4918, 0.4918, 0.0082, 0.0082) [1], with respectively the probability
of walk, traverse, hop, blow moves.
finalize_proposal_func (mot.lib.cl_function.CLFunction): a CL function to finalize every proposal by
the sampling routine. This allows the model to change a proposal before computing the
prior or likelihood probabilities. If None, we will not use this callback.
As an example, suppose you are sampling a polar coordinate :math:`\theta` defined on
:math:`[0, 2\pi]` with a random walk Metropolis proposal distribution. This distribution might propose
positions outside of the range of :math:`\theta`. Of course the model function could deal with that by
taking the modulus of the input, but then you have to post-process the chain with the same
transformation. Instead, this function allows changing the proposal before it is put into the model
and before it will be stored in the chain.
This function should return a proposal that is equivalent (but not necessarily equal)
to the provided proposal.
Signature:
.. code-block:: c
void <func_name>(void* data, local mot_float_type* x);
References:
[1] Christen JA, Foxy C. A general purpose sampling algorithm for continuous distributions (the t-walk).
Bayesian Anal. 2010;5(2):263-282. doi:10.1214/10-BA603. | 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(parameters.shape[<NUM_LIT:2>]) + '''<STR_LIT>''' + ll_func.get_cl_function_name() + '''<STR_LIT>''', dependencies=[ll_func])<EOL><DEDENT>return SimpleCLFunction.from_string('''<STR_LIT>''' + ll_func.get_cl_function_name() + '''<STR_LIT>''', dependencies=[ll_func])<EOL><DEDENT>kernel_data = {'<STR_LIT:data>': data,<EOL>'<STR_LIT>': Array(parameters, '<STR_LIT>', mode='<STR_LIT:r>')}<EOL>shape = parameters.shape<EOL>if len(shape) > <NUM_LIT:2>:<EOL><INDENT>kernel_data.update({<EOL>'<STR_LIT>': Zeros((shape[<NUM_LIT:0>], shape[<NUM_LIT:2>]), '<STR_LIT>'),<EOL>})<EOL><DEDENT>else:<EOL><INDENT>kernel_data.update({<EOL>'<STR_LIT>': Zeros((shape[<NUM_LIT:0>],), '<STR_LIT>'),<EOL>})<EOL><DEDENT>get_cl_function().evaluate(kernel_data, parameters.shape[<NUM_LIT:0>], use_local_reduction=True,<EOL>cl_runtime_info=cl_runtime_info)<EOL>return kernel_data['<STR_LIT>'].get_data()<EOL> | 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), the parameters must be an (d, p) array for d problems and p parameters. In the case of the
second (after sample), you must provide this function with a matrix of shape (d, p, n) with d problems,
p parameters and n samples.
Args:
ll_func (mot.lib.cl_function.CLFunction): The log-likelihood function. A CL function with the signature:
.. code-block:: c
double <func_name>(local const mot_float_type* const x, void* data);
parameters (ndarray): The parameters to use in the evaluation of the model. This is either an (d, p) matrix
or (d, p, n) matrix with d problems, p parameters and n samples.
data (mot.lib.kernel_data.KernelData): the user provided data for the ``void* data`` pointer.
cl_runtime_info (mot.configuration.CLRuntimeInfo): the runtime information
Returns:
ndarray: per problem the log likelihood, or, per problem and per sample the log likelihood. | 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,
void* data,
local mot_float_type* objective_list);
parameters (ndarray): The parameters to use in the evaluation of the model, an (d, p) matrix
with d problems and p parameters.
data (mot.lib.kernel_data.KernelData): the user provided data for the ``void* data`` pointer.
cl_runtime_info (mot.configuration.CLRuntimeInfo): the runtime information
Returns:
ndarray: vector matrix with per problem the objective function value | 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_bounds, upper_bounds, max_step_sizes)<EOL>kernel_data = {<EOL>'<STR_LIT>': Array(parameters, ctype='<STR_LIT>'),<EOL>'<STR_LIT>': Array(initial_step, ctype='<STR_LIT:float>'),<EOL>'<STR_LIT>': Zeros((nmr_voxels, nmr_derivatives), '<STR_LIT>'),<EOL>'<STR_LIT>': Zeros((nmr_voxels, nmr_derivatives), '<STR_LIT>'),<EOL>'<STR_LIT>': LocalMemory('<STR_LIT>', nmr_params),<EOL>'<STR_LIT:data>': data,<EOL>'<STR_LIT>': LocalMemory('<STR_LIT>', nmr_steps + (nmr_steps - <NUM_LIT:1>) + nmr_steps)<EOL>}<EOL>hessian_kernel = SimpleCLFunction.from_string('''<STR_LIT>''' + str(nmr_params) + '''<STR_LIT>''' + objective_func.get_cl_function_name() + '''<STR_LIT>''' + str(nmr_params) + '''<STR_LIT>''' + str(nmr_params) + '''<STR_LIT>''', dependencies=[objective_func,<EOL>_get_numdiff_hessian_element_func(objective_func, nmr_steps, step_ratio)])<EOL>hessian_kernel.evaluate(kernel_data, nmr_voxels, use_local_reduction=True, cl_runtime_info=cl_runtime_info)<EOL>return kernel_data['<STR_LIT>'].get_data()<EOL> | 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 Wynn epsilon extrapolation
on top of the Richardson extrapolated results. If more steps are left, we return the estimate with the lowest error,
taking into account outliers using a median filter.
The Hessian is evaluated at the steps:
.. math::
\quad ((f(x + d_j e_j + d_k e_k) - f(x + d_j e_j - d_k e_k)) -
(f(x - d_j e_j + d_k e_k) - f(x - d_j e_j - d_k e_k)) /
(4 d_j d_k)
where :math:`e_j` is a vector where element :math:`j` is one and the rest are zero
and :math:`d_j` is a scalar spacing :math:`steps_j`.
Steps are generated according to an exponentially diminishing ratio, defined as:
steps = max_step * step_ratio**-i, i = 0,1,..,nmr_steps-1.
Where the maximum step can be provided. For example, a maximum step of 2 with a step ratio of 2, computed for
4 steps gives: [2.0, 1.0, 0.5, 0.25]. If lower and upper bounds are given, we use as maximum step size the largest
step size that fits between the Hessian point and the boundaries.
The steps define the order of the estimation, with 2 steps resulting in a O(h^2) estimate, 3 steps resulting in a
O(h^4) estimate and 4 or more steps resulting in a O(h^6) derivative estimate.
Args:
objective_func (mot.lib.cl_function.CLFunction): The function we want to differentiate.
A CL function with the signature:
.. code-block:: c
double <func_name>(local const mot_float_type* const x, void* data);
The objective function has the same signature as the minimization function in MOT. For the numerical
hessian, the ``objective_list`` parameter is ignored.
parameters (ndarray): The parameters at which to evaluate the gradient. A (d, p) matrix with d problems,
and p parameters
lower_bounds (list or None): a list of length (p,) for p parameters with the lower bounds.
Each element of the list can be a scalar or a vector (of the same length as the number
of problem instances). To disable bounds for this parameter use -np.inf.
upper_bounds (list or None): a list of length (p,) for p parameters with the upper bounds.
Each element of the list can be a scalar or a vector (of the same length as the number
of problem instances). To disable bounds for this parameter use np.inf.
step_ratio (float): the ratio at which the steps diminish.
nmr_steps (int): the number of steps we will generate. We will calculate the derivative for each of these
step sizes and extrapolate the best step size from among them. The minimum number of steps is 1.
max_step_sizes (float or ndarray or None): the maximum step size, or the maximum step size per parameter.
If None is given, we use 0.1 for all parameters. If a float is given, we use that for all parameters.
If a list is given, it should be of the same length as the number of parameters.
data (mot.lib.kernel_data.KernelData): the user provided data for the ``void* data`` pointer.
cl_runtime_info (mot.configuration.CLRuntimeInfo): the runtime information
Returns:
ndarray: per problem instance a vector with the upper triangular elements of the Hessian matrix.
This array can hold NaN's, for elements where the Hessian failed to approximate. | 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_find_best_step_func()<EOL>])<EOL> | 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>''' + objective_func.get_cl_function_name() + '''<STR_LIT>'''), SimpleCLFunction.from_string('''<STR_LIT>''' + objective_func.get_cl_function_name() + '''<STR_LIT>''')])<EOL> | 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_sizes)<EOL>for ind in range(parameters.shape[<NUM_LIT:1>]):<EOL><INDENT>minimum_allowed_step = np.minimum(np.abs(parameters[:, ind] - lower_bounds[ind]),<EOL>np.abs(upper_bounds[ind] - parameters[:, ind]))<EOL>initial_step[:, ind] = np.minimum(minimum_allowed_step, max_step_sizes[ind])<EOL><DEDENT>return initial_step / <NUM_LIT><EOL> | 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.
lower_bounds (list): lower bounds
upper_bounds (list): upper bounds
max_step_sizes (list or None): the maximum step size, or the maximum step size per parameter. Defaults to 0.1
Returns:
ndarray: for every problem instance the vector with the initial step size for each parameter. | 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 a dictionary with for every parameter a matrix with shape (d, n) or, finally,
a generator function that yields sample arrays of shape (p, n).
batch_size_generator (MultiVariateESSBatchSizeGenerator): the batch size generator, tells us how many
batches and of which size we use in estimating the minimum ESS.
Returns:
ndarray: the multivariate ESS per problem | 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 carlo standard error (which in turn is, by default, estimated using a batch means estimator).
Args:
samples (ndarray, dict or generator): either a 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 that yields sample arrays of shape (p, n).
method (str): one of 'autocorrelation' or 'standard_error' defaults to 'standard_error'.
If 'autocorrelation' is chosen we apply the function: :func:`estimate_univariate_ess_autocorrelation`,
if 'standard_error` is choosen we apply the function: :func:`estimate_univariate_ess_standard_error`.
**kwargs: passed to the chosen compute method
Returns:
ndarray: a matrix of size (d, p) with for every problem and every parameter an ESS.
References:
* Flegal, J.M., Haran, M., and Jones, G.L. (2008). "Markov chain Monte Carlo: Can We
Trust the Third Significant Figure?". Statistical Science, 23, p. 250-260.
* Marc S. Meketon and Bruce Schmeiser. 1984. Overlapping batch means: something for nothing?.
In Proceedings of the 16th conference on Winter simulation (WSC '84), Sallie Sheppard (Ed.).
IEEE Press, Piscataway, NJ, USA, 226-230. | 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 samples_generator():<EOL><INDENT>for ind in range(samples.shape[<NUM_LIT:0>]):<EOL><INDENT>yield samples[ind]<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>samples_generator = samples<EOL><DEDENT>return samples_generator<EOL> | 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 that yields sample arrays of shape (p, n).
Returns:
generator: a generator that yields a matrix of size (p, n) for every problem in the input. | 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 works for lags :math:`k < n` where :math:`n` is the number of samples in
the chain.
Args:
chain (ndarray): the vector with the samples
lag (int): the lag to use in the autocorrelation computation
Returns:
float: the autocorrelation with the given lag | 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) - lag] * normalized_chain[lag:], dtype=np.float64)<EOL>if lag % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>if previous_accoeff + auto_correlation_coeff <= <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT><DEDENT>auto_corr_sum += auto_correlation_coeff<EOL>previous_accoeff = auto_correlation_coeff<EOL><DEDENT>return auto_corr_sum / np.var(chain, dtype=np.float64)<EOL> | 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 + 2 * \sum_{k=1}^{m}{\rho_{k}}
Where :math:`\rho_{k}` is estimated as:
.. math::
\hat{\rho}_{k} = \frac{E[(X_{t} - \mu)(X_{t + k} - \mu)]}{\sigma^{2}}
Args:
chain (ndarray): the vector with the samples
max_lag (int): the maximum lag to use in the autocorrelation computation. If not given we use:
:math:`min(n/3, 1000)`. | 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::
ESS(X) = \frac{n}{\tau} = \frac{n}{1 + 2 * \sum_{k=1}^{m}{\rho_{k}}}
where :math:`\rho_{k}` is estimated as:
.. math::
\hat{\rho}_{k} = \frac{E[(X_{t} - \mu)(X_{t + k} - \mu)]}{\sigma^{2}}
References:
* Kass, R. E., Carlin, B. P., Gelman, A., and Neal, R. (1998)
Markov chain Monte Carlo in practice: A roundtable discussion. The American Statistician, 52, 93--100.
* Robert, C. P. and Casella, G. (2004) Monte Carlo Statistical Methods. New York: Springer.
* Geyer, C. J. (1992) Practical Markov chain Monte Carlo. Statistical Science, 7, 473--483.
Args:
chain (ndarray): the chain for which to calculate the ESS, assumes a vector of length ``n`` samples
max_lag (int): the maximum lag used in the variance calculations. If not given defaults to
:math:`min(n/3, 1000)`.
Returns:
float: the estimated ESS | 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 is, by default, estimated using a batch means estimator).
Args:
chain (ndarray): the Markov chain
batch_size_generator (UniVariateESSBatchSizeGenerator): the method that generates that batch sizes
we will use. Per default it uses the :class:`SquareRootSingleBatch` method.
compute_method (ComputeMonteCarloStandardError): the method used to compute the standard error.
By default we will use the :class:`BatchMeansMCSE` method
Returns:
float: the estimated ESS | 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 the number of free parameters.
Args:
nmr_params (int): the number of free parameters in the model
alpha (float): the level of confidence of the confidence region. For example, an alpha of 0.05 means
that we want to be in a 95% confidence region.
epsilon (float): the level of precision in our multivariate ESS estimate.
An epsilon of 0.05 means that we expect that the Monte Carlo error is 5% of the uncertainty in
the target distribution.
Returns:
float: the minimum multivariate Effective Sample Size that one should aim for in MCMC sample to
obtain the desired confidence region with the desired precision.
References:
Vats D, Flegal J, Jones G (2016). Multivariate Output Analysis for Markov Chain Monte Carlo.
arXiv:1512.07713v2 [math.ST] | 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), slightly restructured to give :math:`\epsilon` back instead
of the minimum ESS.
.. math::
\epsilon = \sqrt{\frac{2^{2/p}\pi}{(p\Gamma(p/2))^{2/p}} \frac{\chi^{2}_{1-\alpha,p}}{\widehat{ESS}}}
Where :math:`p` is the number of free parameters and ESS is the multivariate ESS from your samples.
Args:
nmr_params (int): the number of free parameters in the model
multi_variate_ess (int): the number of iid samples you obtained in your sample results.
alpha (float): the level of confidence of the confidence region. For example, an alpha of 0.05 means
that we want to be in a 95% confidence region.
Returns:
float: the minimum multivariate Effective Sample Size that one should aim for in MCMC sample to
obtain the desired confidence region with the desired precision.
References:
Vats D, Flegal J, Jones G (2016). Multivariate Output Analysis for Markov Chain Monte Carlo.
arXiv:1512.07713v2 [math.ST] | 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_offsets):<EOL><INDENT>batches = np.reshape(samples[:, np.array(offset + np.arange(<NUM_LIT:0>, nmr_batches * batch_size), dtype=np.int)].T,<EOL>[batch_size, nmr_batches, nmr_params], order='<STR_LIT:F>')<EOL>batch_means = np.squeeze(np.mean(batches, axis=<NUM_LIT:0>, dtype=np.float64))<EOL>Z = batch_means - sample_means<EOL>for x, y in itertools.product(range(nmr_params), range(nmr_params)):<EOL><INDENT>sigma[x, y] += np.sum(Z[:, x] * Z[:, y])<EOL><DEDENT><DEDENT>return sigma * batch_size / (nmr_batches - <NUM_LIT:1>) / nmr_offsets<EOL> | 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})}
Where :math:`Y` are our samples and :math:`\Lambda` is the covariance matrix of the samples.
This implementation computes the :math:`\Sigma` matrix using a Batch Mean estimator using the given batch size.
The batch size has to be :math:`1 \le b_n \le n` and a typical value is either :math:`\lfloor n^{1/2} \rfloor`
for slow mixing chains or :math:`\lfloor n^{1/3} \rfloor` for reasonable mixing chains.
If the length of the chain is longer than the sum of the length of all the batches, this implementation
calculates :math:`\Sigma` for every offset and returns the average of those offsets.
Args:
samples (ndarray): the samples for which we compute the sigma matrix. Expects an (p, n) array with
p the number of parameters and n the sample size
batch_size (int): the batch size used in the approximation of the correlation covariance
Returns:
ndarray: an pxp array with p the number of parameters in the samples.
References:
Vats D, Flegal J, Jones G (2016). Multivariate Output Analysis for Markov Chain Monte Carlo.
arXiv:1512.07713v2 [math.ST] | 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)<EOL>sigma_estimates = np.zeros((nmr_params, nmr_params, nmr_batches))<EOL>for i in range(<NUM_LIT:0>, nmr_batches):<EOL><INDENT>sigma = estimate_multivariate_ess_sigma(samples, int(batch_sizes[i]))<EOL>ess = chain_length * (det_lambda**(<NUM_LIT:1.0> / nmr_params) / det(sigma)**(<NUM_LIT:1.0> / nmr_params))<EOL>ess_estimates[i] = ess<EOL>sigma_estimates[..., i] = sigma<EOL><DEDENT>ess_estimates = np.nan_to_num(ess_estimates)<EOL>if nmr_batches > <NUM_LIT:1>:<EOL><INDENT>idx = np.argmin(ess_estimates)<EOL><DEDENT>else:<EOL><INDENT>idx = <NUM_LIT:0><EOL><DEDENT>if full_output:<EOL><INDENT>return ess_estimates[idx], sigma_estimates[..., idx], batch_sizes[idx]<EOL><DEDENT>return ess_estimates[idx]<EOL> | 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 parameters, :math:`\Lambda` is the covariance
matrix of the parameters and :math:`\Sigma` captures the covariance structure in the target together with
the covariance due to correlated samples. :math:`\Sigma` is estimated using
:func:`estimate_multivariate_ess_sigma`.
In the case of NaN in any part of the computation the ESS is set to 0.
To compute the multivariate ESS for multiple problems, please use :func:`multivariate_ess`.
Args:
samples (ndarray): an pxn matrix with for p parameters and n samples.
batch_size_generator (MultiVariateESSBatchSizeGenerator): the batch size generator, tells us how many
batches and of which size we use for estimating the minimum ESS. Defaults to :class:`SquareRootSingleBatch`
full_output (boolean): set to True to return the estimated :math:`\Sigma` and the optimal batch size.
Returns:
float or tuple: when full_output is set to True we return a tuple with the estimated multivariate ESS,
the estimated :math:`\Sigma` matrix and the optimal batch size. When full_output is False (the default)
we only return the ESS.
References:
Vats D, Flegal J, Jones G (2016). Multivariate Output Analysis for Markov Chain Monte Carlo.
arXiv:1512.07713v2 [math.ST] | 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): the method that generates that batch sizes
we will use. Per default it uses the :class:`SquareRootSingleBatch` method.
compute_method (ComputeMonteCarloStandardError): the method used to compute the standard error.
By default we will use the :class:`BatchMeansMCSE` method | 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 length of the chain
Returns:
list: the batches of the given sizes we will test in the ESS calculations | 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 batches of the given sizes we will test in the ESS calculations | 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(\lfloor x/max(20,p) \rfloor, \lfloor \sqrt{n} \rfloor) \Big]
where :math:`n` is the chain length and :math:`p` is the number of parameters.
Args:
nmr_batches (int): the number of linearly spaced batches we will generate. | 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 for this parameter declaration | 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(upper_bounds or np.ones(x0.shape[<NUM_LIT:1>]) * np.inf)<EOL>if method == '<STR_LIT>':<EOL><INDENT>return _minimize_powell(func, x0, cl_runtime_info, lower_bounds, upper_bounds,<EOL>constraints_func=constraints_func, data=data, options=options)<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return _minimize_nmsimplex(func, x0, cl_runtime_info, lower_bounds, upper_bounds,<EOL>constraints_func=constraints_func, data=data, options=options)<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return _minimize_levenberg_marquardt(func, x0, nmr_observations, cl_runtime_info, lower_bounds, upper_bounds,<EOL>constraints_func=constraints_func, data=data, options=options)<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return _minimize_subplex(func, x0, cl_runtime_info, lower_bounds, upper_bounds,<EOL>constraints_func=constraints_func, data=data, options=options)<EOL><DEDENT>raise ValueError('<STR_LIT>'.format(method))<EOL> | 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 new objective function, :math:`f(x)` is the old objective function, :math:`g_i` are
the boundary functions defined as :math:`g_i(x) \leq 0` and :math:`\mu` is the penalty weight.
The penalty weight is by default :math:`\mu = 1e20` and can be set
using the ``options`` dictionary as ``penalty_weight``.
Args:
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,
void* data,
local mot_float_type* objective_list);
The objective list needs to be filled when the provided pointer is not null. It should contain
the function values for each observation. This list is used by non-linear least-squares routines,
and will be squared by the least-square optimizer. This is only used by the ``Levenberg-Marquardt`` routine.
x0 (ndarray): Initial guess. Array of real elements of size (n, p), for 'n' problems and 'p'
independent variables.
data (mot.lib.kernel_data.KernelData): the kernel data we will load. This is returned to the likelihood function
as the ``void* data`` pointer.
method (str): Type of solver. Should be one of:
- 'Levenberg-Marquardt'
- 'Nelder-Mead'
- 'Powell'
- 'Subplex'
If not given, defaults to 'Powell'.
lower_bounds (tuple): per parameter a lower bound, if given, the optimizer ensures ``a <= x`` with
a the lower bound and x the parameter. If not given, -infinity is assumed for all parameters.
Each tuple element can either be a scalar or a vector. If a vector is given the first dimension length
should match that of the parameters.
upper_bounds (tuple): per parameter an upper bound, if given, the optimizer ensures ``x >= b`` with
b the upper bound and x the parameter. If not given, +infinity is assumed for all parameters.
Each tuple element can either be a scalar or a vector. If a vector is given the first dimension length
should match that of the parameters.
constraints_func (mot.optimize.base.ConstraintFunction): function to compute (inequality) constraints.
Should hold a CL function with the signature:
.. code-block:: c
void <func_name>(local const mot_float_type* const x,
void* data,
local mot_float_type* constraints);
Where ``constraints_values`` is filled as:
.. code-block:: c
constraints[i] = g_i(x)
That is, for each constraint function :math:`g_i`, formulated as :math:`g_i(x) <= 0`, we should return
the function value of :math:`g_i`.
nmr_observations (int): the number of observations returned by the optimization function.
This is only needed for the ``Levenberg-Marquardt`` method.
cl_runtime_info (mot.configuration.CLRuntimeInfo): the CL runtime information
options (dict): A dictionary of solver options. All methods accept the following generic options:
- patience (int): Maximum number of iterations to perform.
- penalty_weight (float): the weight of the penalty term for the boundary conditions
Returns:
mot.optimize.base.OptimizeResults:
The optimization result represented as a ``OptimizeResult`` object.
Important attributes are: ``x`` the solution array. | 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>', address_space='<STR_LIT>')<EOL> | 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 <func_name>(local const mot_float_type* const x,
void* data,
local mot_float_type* objective_list);
The objective list needs to be filled when the provided pointer is not null. It should contain
the function values for each observation. This list is used by non-linear least-squares routines,
and will be squared by the least-square optimizer. This is only used by the ``Levenberg-Marquardt`` routine.
x0 (ndarray): Initial guess. Array of real elements of size (n, p), for 'n' problems and 'p'
independent variables.
nmr_observations (int): the number of observations returned by the optimization function.
**kwargs: see :func:`minimize`. | 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.5>, '<STR_LIT>': <NUM_LIT:0.1>,<EOL>'<STR_LIT>': True}<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return {'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT:1>, '<STR_LIT>': <NUM_LIT:30>}<EOL><DEDENT>elif method == '<STR_LIT>':<EOL><INDENT>return {'<STR_LIT>': <NUM_LIT:10>,<EOL>'<STR_LIT>': <NUM_LIT:100>,<EOL>'<STR_LIT>': <NUM_LIT:1.0>, '<STR_LIT>': <NUM_LIT:0.5>, '<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT:0.5>, '<STR_LIT>': <NUM_LIT:1.0>, '<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT>,<EOL>'<STR_LIT>': True,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL><DEDENT>raise ValueError('<STR_LIT>'.format(method))<EOL> | 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]<EOL><DEDENT><DEDENT>return result<EOL> | 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
Returns:
dict: the resulting options dictionary | 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>''' + func.get_cl_function_name() + '''<STR_LIT>''', dependencies=[func, penalty_func])<EOL>optimizer_func = Powell(eval_func, nmr_parameters, **_clean_options('<STR_LIT>', options))<EOL>kernel_data = {'<STR_LIT>': Array(x0, ctype='<STR_LIT>', mode='<STR_LIT>'),<EOL>'<STR_LIT:data>': Struct({'<STR_LIT:data>': data,<EOL>'<STR_LIT>': lower_bounds,<EOL>'<STR_LIT>': upper_bounds,<EOL>'<STR_LIT>': penalty_data}, '<STR_LIT>')}<EOL>kernel_data.update(optimizer_func.get_kernel_data())<EOL>return_code = optimizer_func.evaluate(<EOL>kernel_data, nmr_problems,<EOL>use_local_reduction=all(env.is_gpu for env in cl_runtime_info.cl_environments),<EOL>cl_runtime_info=cl_runtime_info)<EOL>return OptimizeResults({'<STR_LIT:x>': kernel_data['<STR_LIT>'].get_data(),<EOL>'<STR_LIT:status>': return_code})<EOL> | 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 patience as for the Powell algorithm itself. | 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>''' + func.get_cl_function_name() + '''<STR_LIT>''', dependencies=[func, penalty_func])<EOL>optimizer_func = NMSimplex('<STR_LIT>', nmr_parameters, dependencies=[eval_func],<EOL>**_clean_options('<STR_LIT>', options))<EOL>kernel_data = {'<STR_LIT>': Array(x0, ctype='<STR_LIT>', mode='<STR_LIT>'),<EOL>'<STR_LIT:data>': Struct({'<STR_LIT:data>': data,<EOL>'<STR_LIT>': lower_bounds,<EOL>'<STR_LIT>': upper_bounds,<EOL>'<STR_LIT>': penalty_data}, '<STR_LIT>')}<EOL>kernel_data.update(optimizer_func.get_kernel_data())<EOL>return_code = optimizer_func.evaluate(<EOL>kernel_data, nmr_problems,<EOL>use_local_reduction=all(env.is_gpu for env in cl_runtime_info.cl_environments),<EOL>cl_runtime_info=cl_runtime_info)<EOL>return OptimizeResults({'<STR_LIT:x>': kernel_data['<STR_LIT>'].get_data(),<EOL>'<STR_LIT:status>': return_code})<EOL> | 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 set the maximum number of iterations to patience*(number_of_parameters+1)
scale (double): the scale of the initial simplex, default 1.0
alpha (double): reflection coefficient, default 1.0
beta (double): contraction coefficient, default 0.5
gamma (double); expansion coefficient, default 2.0
delta (double); shrinkage coefficient, default 0.5
adaptive_scales (boolean): if set to True we use adaptive scales instead of the default scale values.
This sets the scales to:
.. code-block:: python
n = <# parameters>
alpha = 1
beta = 0.75 - 1.0 / (2 * n)
gamma = 1 + 2.0 / n
delta = 1 - 1.0 / n
Following the paper [1]
References:
[1] Gao F, Han L. Implementing the Nelder-Mead simplex algorithm with adaptive parameters.
Comput Optim Appl. 2012;51(1):259-277. doi:10.1007/s10589-010-9329-3. | 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>''' + func.get_cl_function_name() + '''<STR_LIT>''', dependencies=[func, penalty_func])<EOL>optimizer_func = Subplex(eval_func, nmr_parameters, **_clean_options('<STR_LIT>', options))<EOL>kernel_data = {'<STR_LIT>': Array(x0, ctype='<STR_LIT>', mode='<STR_LIT>'),<EOL>'<STR_LIT:data>': Struct({'<STR_LIT:data>': data,<EOL>'<STR_LIT>': lower_bounds,<EOL>'<STR_LIT>': upper_bounds,<EOL>'<STR_LIT>': penalty_data}, '<STR_LIT>')}<EOL>kernel_data.update(optimizer_func.get_kernel_data())<EOL>return_code = optimizer_func.evaluate(<EOL>kernel_data, nmr_problems,<EOL>use_local_reduction=all(env.is_gpu for env in cl_runtime_info.cl_environments),<EOL>cl_runtime_info=cl_runtime_info)<EOL>return OptimizeResults({'<STR_LIT:x>': kernel_data['<STR_LIT>'].get_data(),<EOL>'<STR_LIT:status>': return_code})<EOL> | 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-block:: python
alpha > 0
0 < beta < 1
gamma > 1
gamma > alpha
0 < delta < 1
Options:
patience (int): Used to set the maximum number of iterations to patience*(number_of_parameters+1)
patience_nmsimplex (int): The maximum patience for each subspace search.
For each subspace search we set the number of iterations to patience*(number_of_parameters_subspace+1)
scale (double): the scale of the initial simplex, default 1.0
alpha (double): reflection coefficient, default 1.0
beta (double): contraction coefficient, default 0.5
gamma (double); expansion coefficient, default 2.0
delta (double); shrinkage coefficient, default 0.5
psi (double): subplex specific, simplex reduction coefficient, default 0.001.
omega (double): subplex specific, scaling reduction coefficient, default 0.01
min_subspace_length (int): the minimum subspace length, defaults to min(2, n).
This should hold: (1 <= min_s_d <= max_s_d <= n and min_s_d*ceil(n/nsmax_s_dmax) <= n)
max_subspace_length (int): the maximum subspace length, defaults to min(5, n).
This should hold: (1 <= min_s_d <= max_s_d <= n and min_s_d*ceil(n/max_s_d) <= n)
adaptive_scales (boolean): if set to True we use adaptive scales instead of the default scale values.
This sets the scales to:
.. code-block:: python
n = <# parameters>
alpha = 1
beta = 0.75 - 1.0 / (2 * n)
gamma = 1 + 2.0 / n
delta = 1 - 1.0 / n
References:
[1] Gao F, Han L. Implementing the Nelder-Mead simplex algorithm with adaptive parameters.
Comput Optim Appl. 2012;51(1):259-277. doi:10.1007/s10589-010-9329-3. | 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_function_name() + '''<STR_LIT>'''), SimpleCLFunction.from_string('''<STR_LIT>''' + str(nmr_observations) + '''<STR_LIT>''' + eval_func.get_cl_function_name() + '''<STR_LIT>''' + eval_func.get_cl_function_name() + '''<STR_LIT>'''), SimpleCLFunction.from_string('''<STR_LIT>''' + str(nmr_observations) + '''<STR_LIT>''' + eval_func.get_cl_function_name() + '''<STR_LIT>''' + eval_func.get_cl_function_name() + '''<STR_LIT>''')])<EOL> | 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): the number of observations (the length of the function vector).
Returns:
mot.lib.cl_function.CLFunction: CL function for numerically estimating the Jacobian. | 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_func)<EOL>data_requirements['<STR_LIT>'] = LocalMemory('<STR_LIT>', nmr_constraints)<EOL>constraints_code = '''<STR_LIT>''' + constraints_func.get_cl_function_name() + '''<STR_LIT>''' + str(nmr_constraints) + '''<STR_LIT>'''<EOL><DEDENT>data = Struct(data_requirements, '<STR_LIT>')<EOL>func = SimpleCLFunction.from_string('''<STR_LIT>''' + str(nmr_parameters) + '''<STR_LIT>''' + constraints_code + '''<STR_LIT>''', dependencies=dependencies)<EOL>return data, func<EOL> | 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 compute (inequality) constraints.
Should hold a CL function with the signature:
.. code-block:: c
void <func_name>(local const mot_float_type* const x,
void* data,
local mot_float_type* constraint_values);
Where ``constraints_values`` is filled as:
.. code-block:: c
constraint_values[i] = g_i(x)
That is, for each constraint function :math:`g_i`, formulated as :math:`g_i(x) <= 0`, we should return
the function value of :math:`g_i`.
Returns:
tuple: Struct and SimpleCLFunction, the required data for the penalty function and the penalty function itself. | 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): the difference degrees of freedom in the std calculation. See numpy. | 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:1>]),<EOL>'<STR_LIT>': Scalar(low),<EOL>'<STR_LIT>': Scalar(high),<EOL>}<EOL>cl_func.evaluate(data, samples.shape[<NUM_LIT:0>])<EOL>return data['<STR_LIT>'].get_data(), data['<STR_LIT>'].get_data()<EOL><DEDENT>if len(samples.shape) == <NUM_LIT:1>:<EOL><INDENT>mean, std = run_cl(samples[None, :])<EOL>return mean[<NUM_LIT:0>], std[<NUM_LIT:0>]<EOL><DEDENT>return run_cl(samples)<EOL> | 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 point
low (float): The minimum wrap point | 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><INDENT>lower_bound = lower_bounds[ind]<EOL><DEDENT>if is_scalar(upper_bounds):<EOL><INDENT>upper_bound = upper_bounds<EOL><DEDENT>else:<EOL><INDENT>upper_bound = upper_bounds[ind]<EOL><DEDENT>yield (samples[ind], lower_bound, upper_bound)<EOL><DEDENT><DEDENT>results = np.array(multiprocess_mapping(_TruncatedNormalFitter(), item_generator()))<EOL>return results[:, <NUM_LIT:0>], results[:, <NUM_LIT:1>]<EOL> | 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 fit the truncated Gaussian on all
values. If two dimensional, we calculate the truncated Gaussian for every set of samples over the
first dimension.
lower_bounds (ndarray or float): the lower bound, either a scalar or a lower bound per problem (first index of
samples)
upper_bounds (ndarray or float): the upper bound, either a scalar or an upper bound per problem (first index of
samples)
Returns:
mean, std: the mean and std of the fitted truncated Gaussian | 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><DEDENT><DEDENT>return np.array(list(multiprocess_mapping(_ComputeGaussianOverlap(lower, upper), point_iterator())))<EOL> | 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 will compute the overlap for each element in the first dimension.
Args:
means_0 (ndarray): the set of means of the first distribution
stds_0 (ndarray): the set of stds of the fist distribution
means_1 (ndarray): the set of means of the second distribution
stds_1 (ndarray): the set of stds of the second distribution
lower (float): the lower limit of the integration. If not set we set it to -inf.
upper (float): the upper limit of the integration. If not set we set it to +inf. | 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>': np.nan_to_num(mean_deviance + pd_2004),<EOL>'<STR_LIT>': np.nan_to_num(mean_deviance + <NUM_LIT:2> * pd_2002)}<EOL> | 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 cases differ in how they calculate model complexity, i.e. the effective number of parameters
in the model. In all cases the model with the smallest DIC is preferred.
All these DIC methods measure fitness using the deviance, which is, for a likelihood :math:`p(y | \theta)`
defined as:
.. math::
D(\theta) = -2\log p(y|\theta)
From this, the posterior mean deviance,
.. math::
\bar{D} = \mathbb{E}_{\theta}[D(\theta)]
is then used as a measure of how well the model fits the data.
The complexity, or measure of effective number of parameters, can be measured in see ways, see
Spiegelhalter et al. (2002), Gelman et al (2004) and Ando (2011). The first method calculated the parameter
deviance as:
.. math::
:nowrap:
\begin{align}
p_{D} &= \mathbb{E}_{\theta}[D(\theta)] - D(\mathbb{E}[\theta)]) \\
&= \bar{D} - D(\bar{\theta})
\end{align}
i.e. posterior mean deviance minus the deviance evaluated at the posterior mean of the parameters.
The second method calculated :math:`p_{D}` as:
.. math::
p_{D} = p_{V} = \frac{1}{2}\hat{var}(D(\theta))
i.e. half the variance of the deviance is used as an estimate of the number of free parameters in the model.
The third method calculates the parameter deviance as:
.. math::
p_{D} = 2 \cdot (\bar{D} - D(\bar{\theta}))
That is, twice the complexity of that of the first method.
Finally, the DIC is (for all cases) defined as:
.. math::
DIC = \bar{D} + p_{D}
Args:
mean_posterior_lls (ndarray): a 1d matrix containing the log likelihood for the average posterior
point estimate. That is, the single log likelihood of the average parameters.
ll_per_sample (ndarray): a (d, n) array with for d problems the n log likelihoods.
This is the log likelihood per sample.
Returns:
dict: a dictionary containing the ``DIC_2002``, the ``DIC_2004`` and the ``DIC_Ando_2011`` information
criterion maps. | 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 * scaling_factor,<EOL>samples * scaling_factor),<EOL>method='<STR_LIT>',<EOL>jac=_TruncatedNormalFitter.truncated_normal_ll_gradient,<EOL>bounds=[(lower_bound * scaling_factor, upper_bound * scaling_factor), (<NUM_LIT:0>, None)]<EOL>)<EOL>return result.x / scaling_factor<EOL> | 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 dimension list of data points for which we want to calculate the likelihood
Returns:
float: the negative log likelihood of observing the given data under the given parameters.
This is meant to be used in minimization routines. | 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, high, data)])<EOL> | 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 (ndarray): the one dimension list of data points for which we want to calculate the likelihood
Returns:
tuple: the gradient of the log likelihood given as a tuple with (mean, std) | 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 dimension list of data points for which we want to calculate the likelihood
Returns:
float: the partial derivative evaluated at the given point | 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 (ndarray): the one dimension list of data points for which we want to calculate the likelihood
Returns:
float: the partial derivative evaluated at the given point | 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 CLEnvironment): the new list of CL environments.
Raises:
ValueError: if the list of environments is empty | 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.parameter_functions.proposal_updates.ProposalUpdate: the new proposal update function
to use by default if no specific one is provided. | 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 manually need to store the old
configuraration. | 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 or not | 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()<EOL><DEDENT>if self._double_precision is None:<EOL><INDENT>self._double_precision = use_double_precision()<EOL><DEDENT> | 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): the list of compile flags to use during analysis.
double_precision (boolean): if we apply the computations in double precision or in single float precision.
By default we go for single float precision. | 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.
For small arguments 0 < y < exp(-2), the program computes z = sqrt( -2.0 * log(y) ); then the approximation is
x = z - log(z)/z - (1/z) P(1/z) / Q(1/z). There are two rational functions P/Q, one for 0 < y < exp(-32)
and the other for y up to exp(-2). For larger arguments,
w = y - 0.5, and x/sqrt(2pi) = w + w**3 R(w**2)/S(w**2)). | 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` the scale. | 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 :math:`\theta` the scale. | 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.
Function arguments:
* shape: the shape parameter of the gamma distribution (often denoted :math:`k`)
* scale: the scale parameter of the gamma distribution (often denoted :math:`\theta`) | 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
zero or near one.
Function arguments:
* x: the value at which to approximate the cdf
* shape: the shape parameter of the gamma distribution (often denoted :math:`k`)
* scale: the scale parameter of the gamma distribution (often denoted :math:`\theta`)
References:
1. Revfeim, K. J. A. (1991). Approximation for the cumulative and inverse gamma distribution.
Statistica Neerlandica, 45(3), 327–331. | 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 arguments:
* y: the value at which to approximate the ppf
* shape: the shape parameter of the gamma distribution (often denoted :math:`k`)
* scale: the scale parameter of the gamma distribution (often denoted :math:`\theta`)
References:
1. Revfeim, K. J. A. (1991). Approximation for the cumulative and inverse gamma distribution.
Statistica Neerlandica, 45(3), 327–331. | 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, JR.
* ACM Transactions on Mathematical Software, Vol. 12, No. 4,
* December 1986, Pages 377-393.
*
* See equation 32.
*/ | 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.
*
* See equation 34.
*/
Copied from Scipy (https://github.com/scipy/scipy/blob/master/scipy/special/cephes/igami.c), 05-05-2018. | 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 Transactions on Mathematical Software, Vol. 12, No. 4,
* December 1986, Pages 377-393.
*/
Copied from Scipy (https://github.com/scipy/scipy/blob/master/scipy/special/cephes/igami.c), 05-05-2018. | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.