Compute the Gaussian kernel (search the width for given perplexity.
556898
private double[][] expd(double[][] D, double perplexity, double tol) {
        int n          = D.length;
        double[][] P   = new double[n][n];
        double[] DiSum = Math.rowSums(D);

        int nprocs = MulticoreExecutor.getThreadPoolSize();
        int chunk = n / nprocs;
        List<PerplexityTask> tasks = new ArrayList<>();
        for (int i = 0; i < nprocs; i++) {
            int start = i * chunk;
            int end = i == nprocs-1 ? n : (i+1) * chunk;
            PerplexityTask task = new PerplexityTask(start, end, D, P, DiSum, perplexity, tol);
            tasks.add(task);
        }

        try {
            MulticoreExecutor.run(tasks);
        } catch (Exception e) {
            logger.error("t-SNE Gaussian kernel width search task fails: {}", e);
        }

        return P;
    }
743362
def gaussian2d(xy, sx, sy, mx=0, my=0, rho=0, amp=1, offs=0):
    '''
    
    '''
    x,y = xy
    return offs+amp*( 
        1/(2*np.pi*sx*sy*(1-(rho**2))**0.5) *
         np.exp( (-1/(2*(1-rho**2))) *
                 (
                    ( (x-mx)**2/sx**2 )
                  + ( (y-my)**2/sy**2 )
                  - ( ( 2*rho*(x-mx)*(y-my)) / (sx*sy) )
                  )
                )
         )
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
992713
def gaussian(x,  a, b, c, d=0):
    '''
    
    '''
    return a * np.exp(  -(((x-b)**2 )/ (2*(c**2)))  ) + d
736935
def get_fc_dimensions(self, strides, kernel_sizes):
    """"""
    output_height, output_width, _ = self.hparams.problem.frame_shape
    output_steps = self.hparams.video_num_target_frames
    output_shape = np.array([output_steps, output_height, output_width])
    for curr_stride, kernel_size in zip(strides, kernel_sizes):
      output_shape = self.expected_output_shape(
          output_shape, np.array(curr_stride), 1, kernel_size)
    return np.prod(output_shape) * self.hparams.num_discriminator_filters * 8
1226488
def gaussian(self, x, p):
        
        y = (1.0 / (p[1] * np.sqrt(2 * np.pi)) *
             np.exp(-(x - p[0]) ** 2 / (2 * p[1] ** 2))) * p[2]
        return y
231217
private static void gaussian(float a[][],
	                             int index[]) {
		int n = index.length;
		float c[] = new float[n];
		// Initialize the index
		for (int i = 0; i < n; ++i) {
			index[i] = i;
		}
		// Find the rescaling factors, one from each row
		for (int i = 0; i < n; ++i){
			float c1 = 0;
			for (int j = 0; j < n; ++j){
				float c0 = Math.abs(a[i][j]);
				if (c0 > c1) {
					c1 = c0;
				}
			}
			c[i] = c1;
		}
		// Search the pivoting element from each column
		int k = 0;
		for (int j = 0; j < n - 1; ++j){
			float pi1 = 0;
			for (int i = j; i < n; ++i){
				float pi0 = Math.abs(a[index[i]][j]);
				pi0 /= c[index[i]];
				if (pi0 > pi1) {

					pi1 = pi0;
					k = i;
				}
			}
			// Interchange rows according to the pivoting order
			int itmp = index[j];
			index[j] = index[k];
			index[k] = itmp;
			for (int i = j + 1; i < n; ++i){
				float pj = a[index[i]][j] / a[index[j]][j];
				// Record pivoting ratios below the diagonal
				a[index[i]][j] = pj;

				// Modify other elements accordingly
				for (int l = j + 1; l < n; ++l){
					a[index[i]][l] -= pj * a[index[j]][l];
				}
			}
		}
	}
1054975
def compute(self):
        """"""
        self.smooth_result = run_freidman_supsmu(self.x, self.y)
        self._store_unsorted_results(self.smooth_result, numpy.zeros(len(self.smooth_result)))
856820
def _create_pairwise_gaussian_2d(sx, sy, shape):
    
    feat_size = 2
    feats = np.zeros((feat_size, shape[0], shape[1]), dtype=np.float32)
    for i in range(shape[0]):
        for j in range(shape[1]):
            feats[0, i, j] = i / sx
            feats[1, i, j] = j / sy
    return feats.reshape([feat_size, -1])
396902
def _embedding_kernel_pca(matrix, dimensions=3, affinity_matrix=None,
                          sigma=1):
    
    if affinity_matrix is None:
        aff = rbf(matrix, sigma)
    else:
        aff = affinity_matrix
    kpca = sklearn.decomposition.KernelPCA(kernel='precomputed',
                                           n_components=dimensions)
    return kpca.fit_transform(aff)
452701
public Pair<INDArray, Double> computeGaussianKernel(INDArray distances, double beta, int k) {
        // Compute Gaussian kernel row
        INDArray currP = Nd4j.create(k);
        for (int m = 0; m < k; m++)
            currP.putScalar(m, FastMath.exp(-beta * distances.getDouble(m + 1)));

        double sum = currP.sum(Integer.MAX_VALUE).getDouble(0);
        double h = 0.0;
        for (int m = 0; m < k; m++)
            h += beta * (distances.getDouble(m + 1) * currP.getDouble(m));

        h = (h / sum) + FastMath.log(sum);

        return new Pair<>(currP, h);
    }
1332648
def _nominal_kernel(x, y, out):
    """"""
    for i in range(x.shape[0]):
        for j in range(y.shape[0]):
            out[i, j] += (x[i, :] == y[j, :]).sum()

    return out
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
181984
def fit_gaussian(x, y, yerr, p0):
    
    try:
        popt, pcov = curve_fit(gaussian, x, y, sigma=yerr, p0=p0, absolute_sigma=True)
    except RuntimeError:
        return [0],[0]
    return popt, pcov
151374
public static function gaussian(int $m, int $n) : self
    {
        if ($m < 1 or $n < 1) {
            throw new InvalidArgumentException('Dimensionality must be'
                . ' greater than 0 on all axes.');
        }

        $a = $extras = [];

        for ($i = 0; $i < $m; $i++) {
            $row = [];
            
            if (!empty($extras)) {
                $row[] = array_pop($extras);
            }

            for ($j = count($row); $j < $n; $j += 2) {
                $r1 = rand(0, PHP_INT_MAX) / PHP_INT_MAX;
                $r2 = rand(0, PHP_INT_MAX) / PHP_INT_MAX;

                $r = sqrt(-2. * log($r1));

                $row[] = $r * sin($r2 * self::TWO_PI);
                $row[] = $r * cos($r2 * self::TWO_PI);
            }

            if (count($row) > $n) {
                $extras[] = array_pop($row);
            }

            $a[] = $row;
        }

        return self::quick($a);
    }
690396
def gaussian_filter(data, sigma):
    
    if np.isscalar(sigma):
        sigma = (sigma,) * data.ndim

    baseline = data.mean()
    filtered = data - baseline
    for ax in range(data.ndim):
        s = float(sigma[ax])
        if s == 0:
            continue

        # generate 1D gaussian kernel
        ksize = int(s * 6)
        x = np.arange(-ksize, ksize)
        kernel = np.exp(-x**2 / (2*s**2))
        kshape = [1, ] * data.ndim
        kshape[ax] = len(kernel)
        kernel = kernel.reshape(kshape)

        # convolve as product of FFTs
        shape = data.shape[ax] + ksize
        scale = 1.0 / (abs(s) * (2*np.pi)**0.5)
        filtered = scale * np.fft.irfft(np.fft.rfft(filtered, shape, axis=ax) *
                                        np.fft.rfft(kernel, shape, axis=ax),
                                        axis=ax)

        # clip off extra data
        sl = [slice(None)] * data.ndim
        sl[ax] = slice(filtered.shape[ax]-data.shape[ax], None, None)
        filtered = filtered[sl]
    return filtered + baseline
111797
def _init_random_gaussians(self, X):
        """"""

        n_samples = np.shape(X)[0]
        self.priors = (1 / self.k) * np.ones(self.k)
        for _ in range(self.k):
            params = {}
            params["mean"] = X[np.random.choice(range(n_samples))]
            params["cov"] = calculate_covariance_matrix(X)
            self.parameters.append(params)