code stringlengths 1 18.2k |
|---|
return_std=False, **kwargs) std = None if self.num_dim == 1: univariate_envelope_plot( X, mean, std, ax=ax, base_alpha=base_alpha, envelopes=envelopes, **plot_kwargs ) elif self.num_dim == 2: if ax is None: f = plt.figure() ax = f.add_subplot(111, projection='3d') elif ax == 'gca': ax = plt.gca() if 'linewidths' not in... |
std, alpha=base_alpha / i, **kwargs) ax.plot_trisurf(X1, X2, mean + std, alpha=base_alpha / i, **kwargs) if return_prediction: if full_output: return (ax, out) elif return_std: return (ax, out['mean'], out['std']) else: return (ax, out['mean']) else: return ax |
def draw_sample(self, Xstar, n=0, num_samp=1, rand_vars=None, rand_type='standard normal', diag_factor=1e3, method='cholesky', num_eig=None, mean=None, cov=None, modify_sign=None, **kwargs): """Draw a sample evaluated at the given points `Xstar`. Note that this function draws samples from the GP given the current value... |
to draw random samples from MCMC output, use the `return_samples` and `full_output` keywords to :py:meth:`predict`. Parameters ---------- Xstar : array, (`M`, `D`) `M` test input values of dimension `D`. n : array, (`M`, `D`) or scalar, non-negative int, optional Derivative order to evaluate at. Default is 0 (evaluate ... |
in the sample. Default is False (no noise in samples). num_samp : Positive int, optional Number of samples to draw. Default is 1. Cannot be used in conjunction with `rand_vars`: If you pass both `num_samp` and `rand_vars`, `num_samp` will be silently ignored. rand_vars : array, (`M`, `P`), optional Vector of random var... |
where :math:`K=LL^T`. If None, values will be produced using :py:func:`numpy.random.multivariate_normal`. This allows you to use pseudo/quasi random numbers generated by an external routine. Note that, when `method` is 'eig', the eigenvalues are in *ascending* order. Default is None (use :py:func:`multivariate_normal` ... |
1) normal distribution (this is the default) * 'uniform': Uniform distribution on [0, 1). In this case the required Gaussian variables are produced with inversion. diag_factor : float, optional Number (times machine epsilon) added to the diagonal of the covariance matrix prior to computing its Cholesky decomposition. T... |
not be positive definite. If you are getting errors from :py:func:`scipy.linalg.cholesky`, try increasing this an order of magnitude at a time. This parameter only has an effect when using rand_vars. Default value is 1e3. method : {'cholesky', 'eig'}, optional Method to use for constructing the matrix square root. Defa... |
:math:`K=LL^T`, use :math:`L` as the matrix square root. * 'eig': Perform an eigenvalue decomposition on the covariance matrix: :math:`K=Q \\Lambda Q^{-1}`, use :math:`Q\\Lambda^{1/2}` as the matrix square root. num_eig : int or None, optional Number of eigenvalues to compute. Can range from 1 to `M` (the number of tes... |
eigenvalues). This keyword only has an effect if `method` is 'eig'. mean : array, (`M`,), optional If you have pre-computed the mean and covariance matrix, then you can simply pass them in with the `mean` and `cov` keywords to save on having to call :py:meth:`predict`. cov : array, (`M`, `M`), optional If you have pre-... |
pass them in with the `mean` and `cov` keywords to save on having to call :py:meth:`predict`. modify_sign : {None, 'left value', 'right value', 'left slope', 'right slope', 'left concavity', 'right concavity'}, optional If None (the default), the eigenvectors as returned by :py:func:`scipy.linalg.eigh` are used without... |
of the following: * 'left value': forces the first value of each eigenvector to be positive. * 'right value': forces the last value of each eigenvector to be positive. * 'left slope': forces the slope to be positive at the start of each eigenvector. * 'right slope': forces the slope to be positive at the end of each ei... |
second derivative to be positive at the start of each eigenvector. * 'right concavity': forces the second derivative to be positive at the end of each eigenvector. **kwargs : optional kwargs All extra keyword arguments are passed to :py:meth:`predict` when evaluating the mean and covariance matrix of the GP. Returns --... |
points. Raises ------ ValueError If rand_type or method is invalid. """ # All of the input processing for Xstar and n will be done in here: if mean is None or cov is None: out = self.predict(Xstar, n=n, full_output=True, **kwargs) mean = out['mean'] cov = out['cov'] if rand_vars is None and method != 'eig': try: return... |
self.verbose: warnings.warn( "Failure when drawing from MVN! Falling back on eig. " "Exception was:\n%s" % (e,), RuntimeWarning ) method = 'eig' if num_eig is None or num_eig > len(mean): num_eig = len(mean) elif num_eig < 1: num_eig = 1 if rand_vars is None: rand_vars = numpy.random.standard_normal((num_eig, num_samp)... |
options are: %s." % (rand_type, valid_types,) ) if rand_type == 'uniform': rand_vars = scipy.stats.norm.ppf(rand_vars) if method == 'cholesky': L = scipy.linalg.cholesky( cov + diag_factor * sys.float_info.epsilon * scipy.eye(cov.shape[0]), lower=True, check_finite=False ) elif method == 'eig': # TODO: Add support for ... |
scipy.eye(cov.shape[0]), eigvals=(len(mean) - 1 - (num_eig - 1), len(mean) - 1) ) if modify_sign is not None: if modify_sign == 'left value': modify_mask = (Q[0, :] < 0.0) elif modify_sign == 'right value': modify_mask = (Q[-1, :] < 0.0) elif modify_sign == 'left slope': modify_mask = ((Q[1, :] - Q[0, :]) < 0.0) elif m... |
:]) < 0.0) elif modify_sign == 'left concavity': modify_mask = ((Q[2, :] - 2 * Q[1, :] + Q[0, :]) < 0.0) elif modify_sign == 'right concavity': modify_mask = ((Q[-1, :] - 2 * Q[-2, :] + Q[-3, :]) < 0.0) else: raise ValueError( "modify_sign %s not recognized!" % (modify_sign,) ) Q[:, modify_mask] *= -1.0 Lam_1_2 = scipy... |
%s not recognized!" % (method,)) return scipy.atleast_2d(mean).T + L.dot(rand_vars[:num_eig, :]) |
def update_hyperparameters(self, new_params, hyper_deriv_handling='default', exit_on_bounds=True, inf_on_error=True): r"""Update the kernel's hyperparameters to the new parameters. This will call :py:meth:`compute_K_L_alpha_ll` to update the state accordingly. Note that if this method crashes and the `hyper_deriv_handl... |
optional Determines what to compute and return. If 'default' and :py:attr:`use_hyper_deriv` is True then the negative log-posterior and the negative gradient of the log-posterior with respect to the hyperparameters is returned. If 'default' and :py:attr:`use_hyper_deriv` is False or 'value' then only the negative log-p... |
: bool, optional If True, the method will automatically exit if the hyperparameters are impossible given the hyperprior, without trying to update the internal state. This is useful during MCMC sampling and optimization. Default is True (don't perform update for impossible hyperparameters). inf_on_error : bool, optional... |
update the Gaussian process. Default is True (catch errors and return infinity). Returns ------- -1*ll : float The updated log posterior. -1*ll_deriv : array of float, (`num_params`,) The gradient of the log posterior. Only returned if :py:attr:`use_hyper_deriv` is True or `hyper_deriv_handling` is set to 'deriv'. """ ... |
self.noise_k.set_hyperparams( new_params[len(self.k.free_params):len(self.k.free_params) + len(self.noise_k.free_params)] ) if self.mu is not None: self.mu.set_hyperparams( new_params[len(self.k.free_params) + len(self.noise_k.free_params):] ) self.K_up_to_date = False try: if exit_on_bounds: if scipy.isinf(self.hyperp... |
hyper_deriv_handling == 'default': return (scipy.inf, scipy.zeros(len(self.free_params))) elif hyper_deriv_handling == 'deriv': return scipy.zeros(len(self.free_params)) else: return scipy.inf else: self.use_hyper_deriv = use_hyper_deriv raise e self.use_hyper_deriv = use_hyper_deriv if use_hyper_deriv and hyper_deriv_... |
def compute_K_L_alpha_ll(self): r"""Compute `K`, `L`, `alpha` and log-likelihood according to the first part of Algorithm 2.1 in R&W. Computes `K` and the noise portion of `K` using :py:meth:`compute_Kij`, computes `L` using :py:func:`scipy.linalg.cholesky`, then computes `alpha` as `L.T\\(L\\y)`. Only does the computa... |
None, self.n, None, noise=False) # If the noise kernel is meant to be strictly diagonal, it should # yield a diagonal noise_K: if isinstance(self.noise_k, ZeroKernel): self.noise_K = scipy.zeros((self.X.shape[0], self.X.shape[0])) elif isinstance(self.noise_k, DiagonalNoiseKernel): self.noise_K = self.noise_k.params[0]... |
K + noise_K K_tot = ( KnK + scipy.diag(err_y**2.0) + self.diag_factor * sys.float_info.epsilon * scipy.eye(len(y)) ) self.L = scipy.linalg.cholesky(K_tot, lower=True) # Need to make the mean-subtracted y that appears in the expression # for alpha: if self.mu is not None: mu_alph = self.mu(self.X, self.n) if self.T is n... |
True), scipy.atleast_2d(y_alph).T) self.ll = ( -0.5 * scipy.atleast_2d(y_alph).dot(self.alpha) - scipy.log(scipy.diag(self.L)).sum() - 0.5 * len(y) * scipy.log(2.0 * scipy.pi) )[0, 0] # Apply hyperpriors: self.ll += self.hyperprior(self.params) if self.use_hyper_deriv: warnings.warn("Use of hyperparameter derivatives i... |
one loop: if isinstance(self.noise_k, ZeroKernel): knk = self.k elif isinstance(self.noise_k, DiagonalNoiseKernel): knk = self.k # Handle DiagonalNoiseKernel specially: if not self.noise_k.fixed_params[0]: dK_dtheta_i = 2.0 * self.noise_k.params[0] * scipy.eye(len(y)) self.ll_deriv[len(self.k.free_params)] = 0.5 * ( se... |
and noise kernel: for i, pi in enumerate(free_param_idxs): dK_dtheta_i = self.compute_Kij( self.X, None, self.n, None, k=knk, hyper_deriv=pi ) if self.T is not None: dK_dtheta_i = self.T.dot(dK_dtheta_i).dot(self.T.T) self.ll_deriv[i] = 0.5 * ( self.alpha.T.dot(dK_dtheta_i.dot(self.alpha)) - scipy.trace(scipy.linalg.ch... |
pi in enumerate(free_param_idxs): dmu_dtheta_i = scipy.atleast_2d(self.mu(self.X, self.n, hyper_deriv=pi)).T if self.T is not None: dmu_dtheta_i = self.T.dot(dmu_dtheta_i) self.ll_deriv[i + len(knk.free_params)] = dmu_dtheta_i.T.dot(self.alpha) # Handle the hyperprior: # Get the indices of the free params in self.param... |
def compute_Kij(self, Xi, Xj, ni, nj, noise=False, hyper_deriv=None, k=None): r"""Compute covariance matrix between datasets `Xi` and `Xj`. Specify the orders of derivatives at each location with the `ni`, `nj` arrays. The `include_noise` flag is passed to the covariance kernel to indicate whether noise is to be includ... |
is formed. Note that type and dimension checking is NOT performed, as it is assumed the data are from inside the instance and have hence been sanitized by :py:meth:`add_data`. Parameters ---------- Xi : array, (`M`, `D`) `M` input values of dimension `D`. Xj : array, (`P`, `D`) `P` input values of dimension `D`. ni : a... |
respect to the `Xi` coordinates. nj : array, (`P`, `D`), non-negative integers `P` derivative orders with respect to the `Xj` coordinates. noise : bool, optional If True, uses the noise kernel, otherwise uses the regular kernel. Default is False (use regular kernel). hyper_deriv : None or non-negative int, optional Ind... |
derivatives are taken. Default is None (no hyperparameter derivatives). k : :py:class:`~gptools.kernel.core.Kernel` instance, optional The covariance kernel to used. Overrides `noise` if present. Returns ------- Kij : array, (`M`, `P`) Covariance matrix between `Xi` and `Xj`. """ if k is None: if not noise: k = self.k ... |
else: symmetric = False # TODO: This technically doesn't take advantage of the symmetric case. # Might be worth trying to do that at some point, but this is vastly # superior to the double for loop implementation for which using # symmetry is easy. Xi_tile = scipy.repeat(Xi, Xj.shape[0], axis=0) ni_tile = scipy.repeat(... |
1)) Kij = k( Xi_tile, Xj_tile, ni_tile, nj_tile, hyper_deriv=hyper_deriv, symmetric=symmetric ) Kij = scipy.reshape(Kij, (Xi.shape[0], -1)) return Kij |
def compute_ll_matrix(self, bounds, num_pts): """Compute the log likelihood over the (free) parameter space. Parameters ---------- bounds : 2-tuple or list of 2-tuples with length equal to the number of free parameters Bounds on the range to use for each of the parameters. If a single 2-tuple is given, it will be used ... |
with length equal to the number of free parameters If a single int is given, it will be used for each of the parameters. Returns ------- ll_vals : :py:class:`Array` The log likelihood for each of the parameter possibilities. param_vals : List of :py:class:`Array` The parameter values used. """ present_free_params = sel... |
shape (n, 2)!") # If bounds is a single tuple, repeat it for each free parameter: if bounds.shape[0] == 1: bounds = scipy.tile(bounds, (len(present_free_params), 1)) # If num_pts is a single value, use it for all of the parameters: try: iter(num_pts) except TypeError: num_pts = num_pts * scipy.ones(bounds.shape[0], dty... |
match the number of free parameters!" ) # Form arrays to evaluate parameters over: param_vals = [] for k in xrange(0, len(present_free_params)): param_vals.append(scipy.linspace(bounds[k, 0], bounds[k, 1], num_pts[k])) ll_vals = self._compute_ll_matrix(0, param_vals, num_pts) # Reset the parameters to what they were be... |
def _compute_ll_matrix(self, idx, param_vals, num_pts): """Recursive helper function for compute_ll_matrix. Parameters ---------- idx : int The index of the parameter for this layer of the recursion to work on. `idx` == len(`num_pts`) is the base case that terminates the recursion. param_vals : List of :py:class:`Array... |
of recursion. num_pts : :py:class:`Array` The numbers of points for each parameter. Returns ------- vals : :py:class:`Array` The log likelihood for each of the parameter possibilities at lower levels. """ if idx >= len(num_pts): # Base case: All entries in param_vals should be scalars: return -1.0 * self.update_hyperpa... |
scipy.zeros(num_pts[idx:], dtype=float) for k in xrange(0, len(param_vals[idx])): specific_param_vals = list(param_vals) specific_param_vals[idx] = param_vals[idx][k] vals[k] = self._compute_ll_matrix( idx + 1, specific_param_vals, num_pts ) return vals |
def sample_hyperparameter_posterior(self, nwalkers=200, nsamp=500, burn=0, thin=1, num_proc=None, sampler=None, plot_posterior=False, plot_chains=False, sampler_type='ensemble', ntemps=20, sampler_a=2.0, **plot_kwargs): """Produce samples from the posterior for the hyperparameters using MCMC. Returns the sampler create... |
use in the sampler. Should be on the order of several hundred. Default is 200. nsamp : int, optional Number of samples (per walker) to take. Default is 500. burn : int, optional This keyword only has an effect on the corner plot produced when `plot_posterior` is True and the flattened chain plot produced when `plot_cha... |
:py:meth:`compute_from_MCMC`. The number of samples to discard at the beginning of the chain. Default is 0. thin : int, optional This keyword only has an effect on the corner plot produced when `plot_posterior` is True and the flattened chain plot produced when `plot_chains` is True. To perform computations with thinni... |
None, optional Number of processors to use. If None, all available processors are used. Default is None (use all available processors). sampler : :py:class:`Sampler` instance The sampler to use. If the sampler already has samples, the most recent sample will be used as the starting point. Otherwise a random sample from... |
plot of the posterior for the hyperparameters will be generated. Default is False. plot_chains : bool, optional If True, a plot showing the history and autocorrelation of the chains will be produced. sampler_type : str, optional The type of sampler to use. Valid options are "ensemble" (affine- invariant ensemble sample... |
with the parallel-tempered ensemble sampler. sampler_a : float, optional Scale of the proposal distribution. plot_kwargs : additional keywords, optional Extra arguments to pass to :py:func:`~gptools.utils.plot_sampler`. """ if num_proc is None: num_proc = multiprocessing.cpu_count() # Needed for emcee to do it right: i... |
_ComputeLnProbEval(self), threads=num_proc, a=sampler_a ) elif sampler_type == 'pt': # TODO: Finish this! raise NotImplementedError("PTSampler not done yet!") sampler = emcee.PTSampler( ntemps, nwalkers, ndim, logl, logp ) else: raise NotImplementedError( "Sampler type %s not supported!" % (sampler_type,) ) else: sampl... |
= sampler.chain[:, -1, :] sampler.run_mcmc(theta0, nsamp) if plot_posterior or plot_chains: flat_trace = sampler.chain[:, burn::thin, :] flat_trace = flat_trace.reshape((-1, flat_trace.shape[2])) if plot_posterior and plot_chains: plot_sampler( sampler, labels=['$%s$' % (l,) for l in self.free_param_names], burn=burn, ... |
k + 1) # a.acorr( # sampler.flatchain[:, k], # maxlags=100, # detrend=plt.mlab.detrend_mean # ) # a.set_xlabel('lag') # a.set_title('$%s$ autocorrelation' % (self.free_param_names[k],)) a = f.add_subplot(ndim, 1, 0 * ndim + k + 1) for chain in sampler.chain[:, :, k]: a.plot(chain) a.set_xlabel('sample') a.set_ylabel('$... |
# a.plot(flat_trace[:, k]) # a.set_xlabel('sample') # a.set_ylabel('$%s$' % (self.free_param_names[k],)) # a.set_title('$%s$ flattened, burned and thinned chain' % (self.free_param_names[k],)) # Print a summary of the sampler: print("MCMC parameter summary:") print("param\tmean\t95% posterior interval") mean, ci_l, ci_... |
def compute_from_MCMC(self, X, n=0, return_mean=True, return_std=True, return_cov=False, return_samples=False, return_mean_func=False, num_samples=1, noise=False, samp_kwargs={}, sampler=None, flat_trace=None, burn=0, thin=1, **kwargs): """Compute desired quantities from MCMC samples of the hyperparameter posterior. Th... |
samples), in that order. Samples will be the raw output of :py:meth:`draw_sample`, so you will need to remember to convert to an array and flatten if you want to work with a single sample. Parameters ---------- X : array-like (`M`,) or (`M`, `num_dim`) The values to evaluate the Gaussian process at. n : non-negative in... |
For num_dim=1, this must be an int. For num_dim=2, this must be a list of ints of length 2. Default is 0 (don't take derivative). return_mean : bool, optional If True, the mean will be computed at each hyperparameter sample. Default is True (compute mean). return_std : bool, optional If True, the standard deviation wil... |
(compute stddev). return_cov : bool, optional If True, the covariance matrix will be computed at each hyperparameter sample. Default is True (compute stddev). return_samples : bool, optional If True, random sample(s) will be computed at each hyperparameter sample. Default is False (do not compute samples). num_samples ... |
If True, noise is included in the predictions and samples. Default is False (do not include noise). samp_kwargs : dict, optional If `return_sample` is True, the contents of this dictionary will be passed as kwargs to :py:meth:`draw_sample`. sampler : :py:class:`Sampler` instance or None, optional :py:class:`Sampler` in... |
will be created with :py:meth:`sample_hyperparameter_posterior`. In this case, all extra kwargs will be passed on, allowing you to set the number of samples, etc. Default is None (create sampler). flat_trace : array-like (`nsamp`, `ndim`) or None, optional Flattened trace with samples of the free hyperparameters. If pr... |
specify arbitrary values you wish to evaluate the curve at. Note that this WILL be thinned and burned according to the following two kwargs. "Flat" refers to the fact that you must have combined all chains into a single one. Default is None (use `sampler`). burn : int, optional The number of samples to discard at the b... |
thin : int, optional Every `thin`-th sample is kept. Default is 1. num_proc : int, optional The number of processors to use for evaluation. This is used both when calling the sampler and when evaluating the Gaussian process. If None, the number of available processors will be used. If zero, evaluation will proceed in p... |
extra optional kwargs All additional kwargs are passed to :py:meth:`sample_hyperparameter_posterior`. Returns ------- out : dict A dictionary having some or all of the fields 'mean', 'std', 'cov' and 'samp'. Each entry is a list of array-like. The length of this list is equal to the number of hyperparameter samples use... |
(`M`, `M`) samp (`M`, `num_samples`) ==== ==================== """ output_transform = kwargs.pop('output_transform', None) if flat_trace is None: if sampler is None: sampler = self.sample_hyperparameter_posterior(burn=burn, **kwargs) # If we create the sampler, we need to make sure we clean up its pool: try: sampler.po... |
else: flat_trace = flat_trace[burn::thin, :] num_proc = kwargs.get('num_proc', multiprocessing.cpu_count()) if num_proc > 1: pool = InterruptiblePool(processes=num_proc) map_fun = pool.map else: map_fun = map try: res = map_fun( _ComputeGPWrapper( self, X, n, return_mean, return_std, return_cov, return_samples, return_... |
not None] if return_std: out['std'] = [r['std'] for r in res if r is not None] if return_cov: out['cov'] = [r['cov'] for r in res if r is not None] if return_samples: out['samp'] = [r['samp'] for r in res if r is not None] if return_mean_func and self.mu is not None: out['mean_func'] = [r['mean_func'] for r in res if r... |
= [r['cov_func'] for r in res if r is not None] out['std_func'] = [r['std_func'] for r in res if r is not None] out['mean_without_func'] = [r['mean_without_func'] for r in res if r is not None] out['cov_without_func'] = [r['cov_without_func'] for r in res if r is not None] out['std_without_func'] = [r['std_without_func... |
def compute_l_from_MCMC(self, X, n=0, sampler=None, flat_trace=None, burn=0, thin=1, **kwargs): """Compute desired quantities from MCMC samples of the hyperparameter posterior. The return will be a list with a number of rows equal to the number of hyperparameter samples. The columns will contain the covariance length s... |
: non-negative int or list, optional The order of derivative to compute. For num_dim=1, this must be an int. For num_dim=2, this must be a list of ints of length 2. Default is 0 (don't take derivative). sampler : :py:class:`Sampler` instance or None, optional :py:class:`Sampler` instance that has already been run to th... |
will be created with :py:meth:`sample_hyperparameter_posterior`. In this case, all extra kwargs will be passed on, allowing you to set the number of samples, etc. Default is None (create sampler). flat_trace : array-like (`nsamp`, `ndim`) or None, optional Flattened trace with samples of the free hyperparameters. If pr... |
specify arbitrary values you wish to evaluate the curve at. Note that this WILL be thinned and burned according to the following two kwargs. "Flat" refers to the fact that you must have combined all chains into a single one. Default is None (use `sampler`). burn : int, optional The number of samples to discard at the b... |
thin : int, optional Every `thin`-th sample is kept. Default is 1. num_proc : int, optional The number of processors to use for evaluation. This is used both when calling the sampler and when evaluating the Gaussian process. If None, the number of available processors will be used. If zero, evaluation will proceed in p... |
extra optional kwargs All additional kwargs are passed to :py:meth:`sample_hyperparameter_posterior`. Returns ------- out : array of float Length scale function at the indicated points. """ if flat_trace is None: if sampler is None: sampler = self.sample_hyperparameter_posterior(burn=burn, **kwargs) # If we create the ... |
one thread is used. pass flat_trace = sampler.chain[:, burn::thin, :] flat_trace = flat_trace.reshape((-1, flat_trace.shape[2])) else: flat_trace = flat_trace[burn::thin, :] num_proc = kwargs.get('num_proc', multiprocessing.cpu_count()) if num_proc > 1: pool = InterruptiblePool(processes=num_proc) try: res = pool.map(_... |
def predict_MCMC(self, X, ddof=1, full_MC=False, rejection_func=None, **kwargs): """Make a prediction using MCMC samples. This is essentially a convenient wrapper of :py:meth:`compute_from_MCMC`, designed to act more or less interchangeably with :py:meth:`predict`. Computes the mean of the GP posterior marginalized ove... |
the hyperparameters. If `return_cov` is True, uses the law of total covariance to compute the entire covariance of the GP posterior marginalized over the hyperparameters. If both `return_cov` and `return_std` are True, then both the covariance matrix and standard deviation array will be returned. Parameters ---------- ... |
optional The degree of freedom correction to use when computing the variance. Default is 1 (standard Bessel correction for unbiased estimate). return_std : bool, optional If True, the standard deviation is also computed. Default is True. full_MC : bool, optional Set to True to compute the mean and covariance matrix usi... |
full_output is True. Default is False (don't use full sampling). rejection_func : callable, optional Any samples where this function evaluates False will be rejected, where it evaluates True they will be kept. Default is None (no rejection). Only has an effect if `full_MC` is True. ddof : int, optional **kwargs : optio... |
kwargs.get('return_std', True) return_cov = kwargs.get('return_cov', False) if full_MC: kwargs['return_mean'] = False kwargs['return_std'] = False kwargs['return_cov'] = False kwargs['return_samples'] = True else: kwargs['return_mean'] = True return_samples = kwargs.get('return_samples', True) res = self.compute_from_M... |
samples!") samps = scipy.asarray(good_samps, dtype=float).T mean = scipy.mean(samps, axis=1) cov = scipy.cov(samps, rowvar=1, ddof=ddof) std = scipy.sqrt(scipy.diagonal(cov)) else: means = scipy.asarray(res['mean']) mean = scipy.mean(means, axis=0) # TODO: Allow use of robust estimators! if 'cov' in res: covs = scipy.a... |
ddof=ddof)) if 'mean_func' in res: mean_funcs = scipy.asarray(res['mean_func']) cov_funcs = scipy.asarray(res['cov_func']) mean_func = scipy.mean(mean_funcs, axis=0) cov_func = scipy.mean(cov_funcs, axis=0) + scipy.cov(mean_funcs, rowvar=0, ddof=ddof) std_func = scipy.sqrt(scipy.diagonal(cov_func)) mean_without_funcs =... |
out['std_without_func'] = std_without_func out['mean'] = mean if return_samples: out['samp'] = samps if return_std or return_cov: out['std'] = std if return_cov: out['cov'] = cov return out |
def build_parser(): "Build an argparse argument parser to parse the command line." parser = argparse.ArgumentParser( description="""Coursera OAuth2 client CLI. This tool helps users of the Coursera App Platform to programmatically access Coursera APIs.""", epilog="""Please file bugs on github at: https://github.com/cou... |
We support multiple subcommands. These subcommands have their own # subparsers. Each subcommand should set a default value for the 'func' # option. We then call the parsed 'func' function, and execution carries on # from there. subparsers = parser.add_subparsers() commands.config.parser(subparsers) commands.version.par... |
def main(): "Boots up the command line tool" logging.captureWarnings(True) args = build_parser().parse_args() # Configure logging args.setup_logging(args) # Dispatch into the appropriate subcommand function. try: return args.func(args) except SystemExit: raise except: logging.exception('Problem when running command. So... |
def sponsor_menu( root_menu, menu="sponsors", label=_("Sponsors"), sponsors_item=_("Our sponsors"), packages_item=_("Sponsorship packages")): """Add sponsor menu links.""" root_menu.add_menu(menu, label, items=[]) for sponsor in ( Sponsor.objects.all() .order_by('packages', 'order', 'id') .prefetch_related('packages'))... |
reverse("wafer_sponsors"), menu) if packages_item: with menu_logger(logger, "sponsorship package page link"): root_menu.add_item( packages_item, reverse("wafer_sponsorship_packages"), menu) |
def objectatrib(instance, atrib): ''' this filter is going to be useful to execute an object method or get an object attribute dynamically. this method is going to take into account the atrib param can contains underscores ''' atrib = atrib.replace("__", ".") atribs = [] atribs = atrib.split(".") obj = instance for atr... |
= getattr(obj, atrib)() except Exception: result = getattr(obj, atrib) obj = result return result |
def as_widget(self, widget=None, attrs=None, only_initial=False): """ Renders the field. """ attrs = attrs or {} attrs.update(self.form.get_widget_attrs(self)) if hasattr(self.field, 'widget_css_classes'): css_classes = self.field.widget_css_classes else: css_classes = getattr(self.form, 'widget_css_classes', None) if ... |
def convert_widgets(self): """ During form initialization, some widgets have to be replaced by a counterpart suitable to be rendered the AngularJS way. """ for field in self.base_fields.values(): try: new_widget = field.get_converted_widget() except AttributeError: pass else: if new_widget: field.widget = new_widget |
def epochdate(timestamp): ''' Convet an epoch date to a tuple in format ("yyyy-mm-dd","hh:mm:ss") Example: "1023456427" -> ("2002-06-07","15:27:07") Parameters: - `timestamp`: date in epoch format ''' dt = datetime.fromtimestamp(float(timestamp)).timetuple() fecha = "{0:d}-{1:02d}-{2:02d}".format(dt.tm_year, dt.tm_mon,... |
def model_inspect(obj): ''' Analize itself looking for special information, right now it returns: - Application name - Model name ''' # Prepare the information object info = {} if hasattr(obj, '_meta'): info['verbose_name'] = getattr(obj._meta, 'verbose_name', None) else: info['verbose_name'] = None # Get info from the... |
", "").replace(">", "").replace("'", "").split(".") # Remember information info['appname'] = namesp[-3] info['modelname'] = namesp[-1] info['model'] = model # Return the info return info |
def upload_path(instance, filename): ''' This method is created to return the path to upload files. This path must be different from any other to avoid problems. ''' path_separator = "/" date_separator = "-" ext_separator = "." empty_string = "" # get the model name model_name = model_inspect(instance)['modelname'] # g... |
split_filename = filename.split(ext_separator) filename = empty_string.join(split_filename[:-1]) file_ext = split_filename[-1] new_filename = empty_string.join([filename, str(random.random()).split(ext_separator)[1]]) new_filename = ext_separator.join([new_filename, file_ext]) string_path = path_separator.join([model_n... |
def remove_getdisplay(field_name): ''' for string 'get_FIELD_NAME_display' return 'FIELD_NAME' ''' str_ini = 'get_' str_end = '_display' if str_ini == field_name[0:len(str_ini)] and str_end == field_name[(-1) * len(str_end):]: field_name = field_name[len(str_ini):(-1) * len(str_end)] return field_name |
def JSONEncoder_newdefault(kind=['uuid', 'datetime', 'time', 'decimal']): ''' JSON Encoder newdfeault is a wrapper capable of encoding several kinds Usage: from codenerix.helpers import JSONEncoder_newdefault JSONEncoder_newdefault() ''' JSONEncoder_olddefault = json.JSONEncoder.default def JSONEncoder_wrapped(self, o)... |
in kind) and isinstance(o, decimal.Decimal): return str(o) return JSONEncoder_olddefault(self, o) json.JSONEncoder.default = JSONEncoder_wrapped |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.