Compute the quadratic estimate of the centroid in a 2d-array.

    Args:
        data (2darray): two dimensional data array

    Returns
        center (tuple): centroid estimate on the row and column directions,
                        respectively
335512
def quadratic_2d(data):
    
    arg_data_max = np.argmax(data)
    i, j = np.unravel_index(arg_data_max, data.shape)
    z_ = data[i-1:i+2, j-1:j+2]
    # our quadratic function is defined as
    # f(x, y | a, b, c, d, e, f) := a + b * x + c * y + d * x^2 + e * xy + f * y^2
    # therefore, the best fit coeffiecients are given as
    # note that they are unique and the uncertainty in each of them (#TODO) can be
    # computed following the derivations done by Vakili & Hogg (2016) and
    # Teague & Foreman-Mackey (2018)
    try:
        a = (-z_[0,0] + 2*z_[0,1] - z_[0,2] + 2*z_[1,0] + 5*z_[1,1] + 2*z_[1,2] -
             z_[2,0] + 2*z_[2,1] - z_[2,2]) / 9
        b = (-z_[0,0] - z_[0,1] - z_[0,2] + z_[2,0] + z_[2,1] + z_[2,2]) / 6
        c = (-z_[0,0] + z_[0,2] - z_[1,0] + z_[1,2] - z_[2,0] + z_[2,2]) / 6
        d = (z_[0,0] + z_[0,1] + z_[0,2] - z_[1,0]*2 - z_[1,1]*2 - z_[1,2]*2 +
             z_[2,0] + z_[2,1] + z_[2,2])/6
        e = (z_[0,0] - z_[0,2] - z_[2,0] + z_[2,2]) * .25
        f = (z_[0,0] - 2 * z_[0,1] + z_[0,2] + z_[1,0] - 2 * z_[1,1] + z_[1,2] +
             z_[2,0] - 2 * z_[2,1] + z_[2,2]) / 6
    except IndexError:
        return (i, j)

    # see https://en.wikipedia.org/wiki/Quadratic_function
    det = 4 * d * f - e ** 2
    xm = - (2 * f * b - c * e) / det
    ym = - (2 * d * c - b * e) / det
    return (i+xm, j+ym)
416296
def center(self, axis=1):
        
        if axis == 1:
            return self.map(lambda x: x - mean(x))
        elif axis == 0:
            meanval = self.mean().toarray()
            return self.map(lambda x: x - meanval)
        else:
            raise Exception('Axis must be 0 or 1')
449585
def centerLatLon(self):
        
        # GET CENTROID FROM GSSHA GRID
        gssha_grid = self.getGrid()

        min_x, max_x, min_y, max_y = gssha_grid.bounds()
        x_ext, y_ext = transform(gssha_grid.proj,
                                 Proj(init='epsg:4326'),
                                 [min_x, max_x, min_x, max_x],
                                 [min_y, max_y, max_y, min_y],
                                 )
        return np.mean(y_ext), np.mean(x_ext)
780374
function cluster(k) {
                var Centroids = this.createCentroids(k);
                var LastDistances = Matrix$d.Zero(this.Observations.rows(), this.Observations.cols());
                var Distances = this.distanceFrom(Centroids);
                var Groups;

                while(!(LastDistances.eql(Distances))) {
                Groups = Distances.minColumnIndexes();
                LastDistances = Distances;

                var newCentroids = [];

                for(var i = 1; i <= Centroids.rows(); i++) {
                    var centroid = [];

                    for(var j = 1; j <= Centroids.cols(); j++) {
                    var sum = 0;
                    var count = 0;

                    for(var l = 1; l <= this.Observations.rows(); l++) {
                        if(Groups.e(l) == i) {
                        count++;
                        sum += this.Observations.e(l, j);
                        }
                    }

                    centroid.push(sum / count);
                    }

                    newCentroids.push(centroid);
                }

                Centroids = $M(newCentroids);
                Distances = this.distanceFrom(Centroids);
                }

                return Groups;
            }
93645
def _retain_centroids(numbers, thres):
    """"""
    numbers.sort()
    prev = -1
    ret = []
    for n in numbers:
        if prev < 0 or n - prev > thres:
            ret.append(n)
            prev = n
    return ret
862224
def data(self, data):
        
        self._assert_shape(data, self._x_indexes, self._y_indexes)
        data[data == -np.inf] = 0.0
        data[data == np.inf] = 0.0
        self._data = data
        self._min_value = np.nanmin(self.data)
        self._max_value = np.nanmax(self.data)
        self._data_x_indexes = list(range(data.shape[0]))
        self._data_y_indexes = list(range(data.shape[1]))
        self._dirty = False
1356028
def estimated_position(self):
        
        corner = {"D":self.cube["D"]["D"]}
        edge = {}
        for cubie in (corner, edge):
            for face in self.pair:
                cubie.update({face:self.cube[face][face]})
        return (Corner(**corner), Edge(**edge))
875574
public static double[] rowMeans(double[][] data) {
        double[] x = new double[data.length];

        for (int i = 0; i < x.length; i++) {
            x[i] = mean(data[i]);
        }

        return x;
    }
883858
def kurtosis(data):
    

    if not data:
        raise StatisticsError('kurtosis requires at least one data point')

    size = len(data)
    sd = stdev(data) ** 4

    if not sd:
        return 0.0

    mn = mean(data)
    return sum(map(lambda x: ((x - mn) ** 4 / sd), data)) / size - 3
1041939
private static int[] seed(SparseDataset data, int k) {
        int n = data.size();

        int[] y = new int[n];
        SparseArray centroid = data.get(Math.randomInt(n)).x;

        double[] D = new double[n];
        for (int i = 0; i < n; i++) {
            D[i] = Double.MAX_VALUE;
        }

        // pick the next center
        for (int i = 1; i < k; i++) {
            for (int j = 0; j < n; j++) {
                double dist = Math.JensenShannonDivergence(data.get(j).x, centroid);
                if (dist < D[j]) {
                    D[j] = dist;
                    y[j] = i - 1;
                }
            }

            double cutoff = Math.random() * Math.sum(D);
            double cost = 0.0;
            int index = 0;
            for (; index < n; index++) {
                cost += D[index];
                if (cost >= cutoff) {
                    break;
                }
            }

            centroid = data.get(index).x;
        }

        for (int j = 0; j < n; j++) {
            // compute the distance between this sample and the current center
            double dist = Math.JensenShannonDivergence(data.get(j).x, centroid);
            if (dist < D[j]) {
                D[j] = dist;
                y[j] = k - 1;
            }
        }

        return y;
    }
512107
def centerOfMass(self):
        
        cmf = vtk.vtkCenterOfMass()
        cmf.SetInputData(self.polydata(True))
        cmf.Update()
        c = cmf.GetCenter()
        return np.array(c)
1091508
def getP2(self):
        
        return Point(self.center[0] + self.radius,
                     self.center[1] + self.radius)
1248055
def center(self) -> Point2:
        
        assert self
        pos = Point2(
            (
                sum([unit.position.x for unit in self]) / self.amount,
                sum([unit.position.y for unit in self]) / self.amount,
            )
        )
        return pos
1332731
def centering_centroid(data, xi, yi, box, nloop=10, toldist=1e-3,
                       maxdist=10.0):
    '''
        
    '''

    # Store original center
    cxy = (xi, yi)
    origin = (xi, yi)
    # initial background
    back = 0.0

    if nloop == 0:
        return xi, yi, 0.0, 0, 'not recentering'

    for i in range(nloop):
        nxy, back = _centering_centroid_loop_xy(data, cxy, box)
        # _logger.debug('new center is %s', ncenter)
        # if we are to far away from the initial point, break
        dst = distance.euclidean(origin, nxy)
        if dst > maxdist:
            msg = 'maximum distance (%5.2f) from origin reached' % maxdist
            return cxy[0], cxy[1], back, 2, msg

        # check convergence
        dst = distance.euclidean(nxy, cxy)
        if dst < toldist:
            return nxy[0], nxy[1], back, 1, 'converged in iteration %i' % i
        else:
            cxy = nxy

    return nxy[0], nxy[1], back, 3, 'not converged in %i iterations' % nloop
795936
def set_centralized_sparse(self, A):
        
        if self.myid != 0:
            return

        A = A.tocoo()
        n = A.shape[0]
        assert A.shape == (n, n), "Expected a square matrix."
        self.set_shape(n)
        self.set_centralized_assembled(A.row+1, A.col+1, A.data)
1263805
def estimate_row_scales(
            self,
            X_centered,
            column_scales):
        
        n_rows, n_cols = X_centered.shape
        column_scales = np.asarray(column_scales)
        if len(column_scales) != n_cols:
            raise ValueError("Expected length %d but got shape %s" % (
                n_cols, column_scales))
        row_variances = np.nanmean(
            X_centered ** 2 / (column_scales ** 2).reshape((1, n_cols)),
            axis=1)
        row_variances[row_variances == 0] = 1.0
        assert len(row_variances) == n_rows, "%d != %d" % (
            len(row_variances),
            n_rows)
        return np.sqrt(row_variances)
253408
def _update_mean_coords(self, dig, N, centers_sum, **paircoords):
        
        if N is None or centers_sum is None: return

        N.flat[:] += utils.bincount(dig, 1., minlength=N.size)
        for i, dim in enumerate(self.dims):
            size = centers_sum[i].size
            centers_sum[i].flat[:] += utils.bincount(dig, paircoords[dim], minlength=size)