Return a model of the sum of N Gaussians and a constant background.
429882
def sum_of_gaussian_factory(N):
    """"""

    name = "SumNGauss%d" % N
    attr = {}

    # parameters
    for i in range(N):
        key = "amplitude_%d" % i
        attr[key] = Parameter(key)
        key = "center_%d" % i
        attr[key] = Parameter(key)
        key = "stddev_%d" % i
        attr[key] = Parameter(key)

    attr['background'] = Parameter('background', default=0.0)

    def fit_eval(self, x, *args):
        result = x * 0 + args[-1]
        for i in range(N):
            result += args[3 * i] * \
                np.exp(- 0.5 * (x - args[3 * i + 1])
                       ** 2 / args[3 * i + 2] ** 2)
        return result

    attr['evaluate'] = fit_eval

    def deriv(self, x, *args):
        d_result = np.ones(((3 * N + 1), len(x)))

        for i in range(N):
            d_result[3 * i] = (np.exp(-0.5 / args[3 * i + 2] ** 2 *
                                      (x - args[3 * i + 1]) ** 2))
            d_result[3 * i + 1] = args[3 * i] * d_result[3 * i] * \
                (x - args[3 * i + 1]) / args[3 * i + 2] ** 2
            d_result[3 * i + 2] = args[3 * i] * d_result[3 * i] * \
                (x - args[3 * i + 1]) ** 2 / args[3 * i + 2] ** 3
        return d_result

    attr['fit_deriv'] = deriv

    klass = type(name, (Fittable1DModel, ), attr)
    return klass
399906
def gaussian_points(loc=(0, 0), scale=(10, 10), n=100):
    

    arr = np.random.normal(loc, scale, (n, 2))
    return gpd.GeoSeries([shapely.geometry.Point(x, y) for (x, y) in arr])
415181
def gaussian_kernel(sigma, truncate=4.0):
    

    sigma = float(sigma)
    radius = int(truncate * sigma + 0.5)

    x, y = np.mgrid[-radius:radius + 1, -radius:radius + 1]
    sigma = sigma ** 2

    k = 2 * np.exp(-0.5 * (x ** 2 + y ** 2) / sigma)
    k = k / np.sum(k)

    return k
131026
def get_gadf(self):
        
        adam = (np.abs(self.y - np.median(self.y))).sum()
        gadf = 1 - self.adcm / adam
        return gadf
12313
def generate_gaussian_profile(seeing_fwhm):
    """"""
    FWHM_G = 2 * math.sqrt(2 * math.log(2))
    sigma = seeing_fwhm / FWHM_G
    amplitude = 1.0 / (2 * math.pi * sigma * sigma)
    seeing_model = Gaussian2D(amplitude=amplitude,
                              x_mean=0.0,
                              y_mean=0.0,
                              x_stddev=sigma,
                              y_stddev=sigma)
    return seeing_model
17299
def spm(x, model, y=None, n_samples=None, dx_min=-0.1,
        dx_max=0.1, n_dxs=5, dy_min=-0.1, dy_max=0.1, n_dys=5,
        angle_min=-30, angle_max=30, n_angles=31, black_border_size=0):
  
  if y is None:
    preds = model.get_probs(x)
    # Using model predictions as ground truth to avoid label leaking
    preds_max = reduce_max(preds, 1, keepdims=True)
    y = tf.to_float(tf.equal(preds, preds_max))
    y = tf.stop_gradient(y)
    del preds
  y = y / reduce_sum(y, 1, keepdims=True)

  # Define the range of transformations
  dxs = np.linspace(dx_min, dx_max, n_dxs)
  dys = np.linspace(dy_min, dy_max, n_dys)
  angles = np.linspace(angle_min, angle_max, n_angles)

  if n_samples is None:
    import itertools
    transforms = list(itertools.product(*[dxs, dys, angles]))
  else:
    sampled_dxs = np.random.choice(dxs, n_samples)
    sampled_dys = np.random.choice(dys, n_samples)
    sampled_angles = np.random.choice(angles, n_samples)
    transforms = zip(sampled_dxs, sampled_dys, sampled_angles)
  transformed_ims = parallel_apply_transformations(
      x, transforms, black_border_size)

  def _compute_xent(x):
    preds = model.get_logits(x)
    return tf.nn.softmax_cross_entropy_with_logits_v2(
        labels=y, logits=preds)

  all_xents = tf.map_fn(
      _compute_xent,
      transformed_ims,
      parallel_iterations=1)  # Must be 1 to avoid keras race conditions

  # Return the adv_x with worst accuracy

  # all_xents is n_total_samples x batch_size (SB)
  all_xents = tf.stack(all_xents)  # SB

  # We want the worst case sample, with the largest xent_loss
  worst_sample_idx = tf.argmax(all_xents, axis=0)  # B

  batch_size = tf.shape(x)[0]
  keys = tf.stack([
      tf.range(batch_size, dtype=tf.int32),
      tf.cast(worst_sample_idx, tf.int32)
  ], axis=1)
  transformed_ims_bshwc = tf.einsum('sbhwc->bshwc', transformed_ims)
  after_lookup = tf.gather_nd(transformed_ims_bshwc, keys)  # BHWC
  return after_lookup
880909
function Gaussian(parms) {
      if (parms == null) {
        parms = {};
      }
      if (parms.pi !== void 0) {
        this.pi = parms["pi"];
        this.tau = parms["tau"];
      } else if (parms.mu !== void 0) {
        this.pi = pow(parms["sigma"], -2);
        this.tau = this.pi * parms["mu"];
      } else {
        this.pi = 0;
        this.tau = 0;
      }
      if (isNaN(this.pi) || isNaN(this.tau)) {
        throw new Error("Gaussian parms can not be NaN");
      }
    }
707269
def circular_gaussian_kernel(sd,radius):
    
    i,j = np.mgrid[-radius:radius+1,-radius:radius+1].astype(float) / radius
    mask = i**2 + j**2 <= 1
    i = i * radius / sd
    j = j * radius / sd

    kernel = np.zeros((2*radius+1,2*radius+1))
    kernel[mask] = np.e ** (-(i[mask]**2+j[mask]**2) /
                            (2 * sd **2))
    #
    # Normalize the kernel so that there is no net effect on a uniform image
    #
    kernel = kernel / np.sum(kernel)
    return kernel
1028992
def numbaGaussian2d(psf, sy, sx):
    '''
    
    '''
    ps0, ps1 = psf.shape
    c0,c1 = ps0//2, ps1//2
    ssx = 2*sx**2
    ssy = 2*sy**2
    for i in range(ps0):
        for j in range(ps1):
            psf[i,j]=exp( -( (i-c0)**2/ssy
                            +(j-c1)**2/ssx) )
    psf/=psf.sum()
230637
def GaussianBlur(X, ksize_width, ksize_height, sigma_x, sigma_y):
    
    return image_transform(
        X,
        cv2.GaussianBlur,
        ksize=(ksize_width, ksize_height),
        sigmaX=sigma_x,
        sigmaY=sigma_y
    )
621622
def _M2(Xvar, Yvar, mask_X=None, mask_Y=None, xsum=0, xconst=0, ysum=0, yconst=0, weights=None, diag_only=False):
    
    if mask_X is None and mask_Y is None:
        return _M2_dense(Xvar, Yvar, weights=weights, diag_only=diag_only)
    else:
        # Check if one of the masks is not None, modify it and also adjust the constant columns:
        if mask_X is None:
            mask_X = np.ones(Xvar.shape[1], dtype=np.bool)
            xconst = np.ones(0, dtype=float)
        if mask_Y is None:
            mask_Y = np.ones(Yvar.shape[1], dtype=np.bool)
            yconst = np.ones(0, dtype=float)
    if _is_zero(xsum) and _is_zero(ysum) or _is_zero(xconst) and _is_zero(yconst):
        return _M2_sparse(Xvar, mask_X, Yvar, mask_Y, weights=weights)
    else:
        return _M2_const(Xvar, mask_X, xsum[mask_X], xconst, Yvar, mask_Y, ysum[mask_Y], yconst, weights=weights)
1069772
def gaussian_noise(in_features, out_features, device):
    
    return torch.randn((in_features, out_features), device=device), torch.randn(out_features, device=device)
811708
def _create_model(self, X, Y):
        

        # --- define kernel
        self.input_dim = X.shape[1]
        if self.kernel is None:
            kern = GPy.kern.RBF(self.input_dim, variance=1.)
        else:
            kern = self.kernel
            self.kernel = None

        # --- define model
        noise_var = Y.var()*0.01 if self.noise_var is None else self.noise_var
        self.model = GPy.models.GPRegression(X, Y, kernel=kern, noise_var=noise_var)

        # --- Define prior on the hyper-parameters for the kernel (for integrated acquisitions)
        self.model.kern.set_prior(GPy.priors.Gamma.from_EV(2.,4.))
        self.model.likelihood.variance.set_prior(GPy.priors.Gamma.from_EV(2.,4.))

        # --- Restrict variance if exact evaluations of the objective
        if self.exact_feval:
            self.model.Gaussian_noise.constrain_fixed(1e-6, warning=False)
        else:
            self.model.Gaussian_noise.constrain_positive(warning=False)
1080141
def compile(self, session=None):
        
        if not self.num_data == self.X.shape[0]:
            self.num_data = self.X.shape[0]
            self.V = Parameter(np.zeros((self.num_data, self.num_latent)))
            self.V.prior = Gaussian(0., 1.)

        return super(GPMC, self).compile(session=session)
1215584
private double gaussianUpdate(int predicate, int oid, double correctionConstant) {
        double param = params[predicate].getParameters()[oid];
        double x0 = 0.0;
        double modelValue = modelExpects[0][predicate].getParameters()[oid];
        double observedValue = observedExpects[predicate].getParameters()[oid];
        for (int i = 0; i < 50; i++) {
            double tmp = modelValue * Math.exp(correctionConstant * x0);
            double f = tmp + (param + x0) / sigma - observedValue;
            double fp = tmp * correctionConstant + 1 / sigma;
            if (fp == 0) {
                break;
            }
            double x = x0 - f / fp;
            if (Math.abs(x - x0) < 0.000001) {
                x0 = x;
                break;
            }
            x0 = x;
        }
        return x0;
    }
774414
def _build_likelihood(self):
        

        """

        # Get prior KL.
        KL = gauss_kl(self.q_mu, self.q_sqrt)

        # Get conditionals
        K = self.kern.K(self.X) + tf.eye(self.num_data, dtype=settings.float_type) * \
            settings.numerics.jitter_level
        L = tf.cholesky(K)

        fmean = tf.matmul(L, self.q_mu) + self.mean_function(self.X)  # NN,ND->ND

        q_sqrt_dnn = tf.matrix_band_part(self.q_sqrt, -1, 0)  # D x N x N

        L_tiled = tf.tile(tf.expand_dims(L, 0), tf.stack([self.num_latent, 1, 1]))

        LTA = tf.matmul(L_tiled, q_sqrt_dnn)  # D x N x N
        fvar = tf.reduce_sum(tf.square(LTA), 2)

        fvar = tf.transpose(fvar)

        # Get variational expectations.
        var_exp = self.likelihood.variational_expectations(fmean, fvar, self.Y)

        return tf.reduce_sum(var_exp) - KL
1021506
def Gaussian(x, mu, sig):
    
    return sympy.exp(-(x - mu)**2/(2*sig**2))/sympy.sqrt(2*sympy.pi*sig**2)