Compute the gradient of the KL Divergence cost function with respect to
the embedding.

@param \Rubix\Tensor\Matrix $p
@param \Rubix\Tensor\Matrix $y
@param \Rubix\Tensor\Matrix $distances
@return \Rubix\Tensor\Matrix
340565
protected function gradient(Matrix $p, Matrix $y, Matrix $distances) : Matrix
    {
        $q = $distances->square()
            ->divide($this->degrees)
            ->add(1.)
            ->pow((1. + $this->degrees) / -2.);

        $qSigma = $q->sum()->multiply(2.);

        $q = $q->divide($qSigma)
            ->clipLower(EPSILON);

        $pqd = $p->subtract($q)
            ->multiply($distances);

        $c = 2. * (1. + $this->degrees) / $this->degrees;

        $gradient = [];

        foreach ($pqd->asVectors() as $i => $row) {
            $yHat = $y->rowAsVector($i)
                ->subtract($y);
            
            $gradient[] = $row->matmul($yHat)
                ->multiply($c)
                ->row(0);
        }

        return Matrix::quick($gradient);
    }
681429
public static KNN<double[]> learn(double[][] x, int[] y, int k) {
        if (x.length != y.length) {
            throw new IllegalArgumentException(String.format("The sizes of X and Y don't match: %d != %d", x.length, y.length));
        }

        if (k < 1) {
            throw new IllegalArgumentException("Illegal k = " + k);
        }

        KNNSearch<double[], double[]> knn = null;
        if (x[0].length < 10) {
            knn = new KDTree<>(x, x);
        } else {
            knn = new CoverTree<>(x, new EuclideanDistance());
        }
        
        return new KNN<>(knn, y, k);
    }
769587
public static float distance(PointF p1, PointF p2){
        return (float) Math.sqrt(Math.pow((p2.x - p1.x), 2) + Math.pow(p2.y - p1.y,2));
    }
92743
def fisher_vector_product(self, vector, kl_divergence_gradient, model):
        
        assert not vector.requires_grad, "Vector must not propagate gradient"
        dot_product = vector @ kl_divergence_gradient

        # at least one dimension spans across two contiguous subspaces
        double_gradient = torch.autograd.grad(dot_product, model.policy_parameters(), retain_graph=True)
        fvp = p2v(x.contiguous() for x in double_gradient)

        return fvp + vector * self.cg_damping
726052
public double gradient(double[] expected)
    {
        if (x_.isEmpty())
        {
            return 0.0;
        }
        buildLattice();
        forwardbackward();
        double s = 0.0;

        for (int i = 0; i < x_.size(); i++)
        {
            for (int j = 0; j < ysize_; j++)
            {
                node_.get(i).get(j).calcExpectation(expected, Z_, ysize_);
            }
        }
        for (int i = 0; i < x_.size(); i++)
        {
            List<Integer> fvector = node_.get(i).get(answer_.get(i)).fVector;
            for (int j = 0; fvector.get(j) != -1; j++)
            {
                int idx = fvector.get(j) + answer_.get(i);
                expected[idx]--;
            }
            s += node_.get(i).get(answer_.get(i)).cost; //UNIGRAM COST
            List<Path> lpath = node_.get(i).get(answer_.get(i)).lpath;
            for (Path p : lpath)
            {
                if (p.lnode.y == answer_.get(p.lnode.x))
                {
                    for (int k = 0; p.fvector.get(k) != -1; k++)
                    {
                        int idx = p.fvector.get(k) + p.lnode.y * ysize_ + p.rnode.y;
                        expected[idx]--;
                    }
                    s += p.cost;  // BIGRAM COST
                    break;
                }
            }
        }

        viterbi();
        return Z_ - s;
    }
1149822
private void findNeighbor(int p) {
        // if no neighbors available, set flag for UpdatePoint to find
        if (npoints == 1) {
            neighbor[p] = p;
            distance[p] = Float.MAX_VALUE;
            return;
        }

        // find first point unequal to p itself
        int first = 0;
        if (p == points[first]) {
            first = 1;
        }

        neighbor[p] = points[first];
        distance[p] = linkage.d(p, neighbor[p]);

        // now test whether each other point is closer
        for (int i = first + 1; i < npoints; i++) {
            int q = points[i];
            if (q != p) {
                float d = linkage.d(p, q);
                if (d < distance[p]) {
                    distance[p] = d;
                    neighbor[p] = q;
                }
            }
        }
    }
608190
def vector(p1, p2):
    
    return None if len(p1) != len(p2) else np.array([p2[i] - p1[i] for i in xrange(len(p1))])
1361179
function distance(p1, p2) {
        return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) +
                         (p1.y - p2.y) * (p1.y - p2.y));
    }
179950
def hessfunc(self, p):
        
        self._set_stochastics(p)
        for i in xrange(self.len):

            di = self.diff(i)
            self.hess[i, i] = self.diff(i, 2)

            if i < self.len - 1:

                for j in xrange(i + 1, self.len):
                    dij = self.diff2(i, j)

                    self.hess[i, j] = dij
                    self.hess[j, i] = dij

        return -1. * self.hess
1356225
public static final double distance(Point p1, Point p2)
    {
        return Math.hypot(p1.getX() - p2.getX(), p1.getY() - p2.getY());
    }
989980
def _dcorr(y, n2, A, dcov2_xx):
    
    # Pairwise Euclidean distances
    b = squareform(pdist(y, metric='euclidean'))
    # Double centering
    B = b - b.mean(axis=0)[None, :] - b.mean(axis=1)[:, None] + b.mean()
    # Compute squared distance covariances
    dcov2_yy = np.vdot(B, B) / n2
    dcov2_xy = np.vdot(A, B) / n2
    return np.sqrt(dcov2_xy) / np.sqrt(np.sqrt(dcov2_xx) * np.sqrt(dcov2_yy))
476383
public static float pointRectDistanceSq (IRectangle r, IPoint p) {
        Point p2 = closestInteriorPoint(r, p);
        return Points.distanceSq(p.x(), p.y(), p2.x, p2.y);
    }
459589
def ppca(Y, Q, iterations=100):
    
    from numpy.ma import dot as madot
    N, D = Y.shape
    # Initialise W randomly
    W = np.random.randn(D, Q) * 1e-3
    Y = np.ma.masked_invalid(Y, copy=0)
    mu = Y.mean(0)
    Ycentered = Y - mu
    try:
        for _ in range(iterations):
            exp_x = np.asarray_chkfinite(np.linalg.solve(W.T.dot(W), madot(W.T, Ycentered.T))).T
            W = np.asarray_chkfinite(np.linalg.solve(exp_x.T.dot(exp_x), madot(exp_x.T, Ycentered))).T
    except np.linalg.linalg.LinAlgError:
        #"converged"
        pass
    return np.asarray_chkfinite(exp_x), np.asarray_chkfinite(W)
374355
public static float pointSegDistSq (float px, float py,
                                        float x1, float y1, float x2, float y2) {
        // A = (x2 - x1, y2 - y1)
        // P = (px - x1, py - y1)
        x2 -= x1; // A = (x2, y2)
        y2 -= y1;
        px -= x1; // P = (px, py)
        py -= y1;
        float dist;
        if (px * x2 + py * y2 <= 0.0) { // P*A
            dist = px * px + py * py;
        } else {
            px = x2 - px; // P = A - P = (x2 - px, y2 - py)
            py = y2 - py;
            if (px * x2 + py * y2 <= 0.0) { // P*A
                dist = px * px + py * py;
            } else {
                dist = px * y2 - py * x2;
                dist = dist * dist / (x2 * x2 + y2 * y2); // pxA/|A|
            }
        }
        if (dist < 0) {
            dist = 0;
        }
        return dist;
    }
37241
public static double distanceSquared(Point p1, Point p2)
	{
		double x = p2.x - p1.x;
		double y = p2.y - p1.y;
		double z = p2.z - p1.z;
		return x * x + y * y + z * z;
	}
1241300
def logloss(y, p):
    

    p[p < EPS] = EPS
    p[p > 1 - EPS] = 1 - EPS
    return log_loss(y, p)
656195
def prox_yline(y, step):
    """"""
    if not np.isscalar(y):
        y= y[0]
    if y > -0.75:
        return np.array([-0.75])
    else:
        return np.array([y])