Compute a centered distance matrix given a matrix.
428995
def _distance_matrix_generic(x, centering, exponent=1):
    """"""
    _check_valid_dcov_exponent(exponent)

    x = _transform_to_2d(x)

    # Calculate distance matrices
    a = distances.pairwise_distances(x, exponent=exponent)

    # Double centering
    a = centering(a, out=a)

    return a
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
966043
def matrix_from_edges(edges):
    ''''''
    max_col = 0
    cols = []
    rows = []
    vals = []
    if type(edges) is defaultdict:
        edge_list = []
        for i, neighbors in edges.items():
            for j in neighbors:
                if i <= j:
                    edge_list.append((i,j))
        edges = edge_list
    for i, edge in enumerate(edges):
        s, t = edge[0], edge[1]
        weight = 1 if len(edge) == 2 else edge[2]
        cols.append(min(s,t))
        cols.append(max(s,t))
        rows.append(i)
        rows.append(i)
        vals.append(weight)
        vals.append(-weight)
        if cols[-1] > max_col:
            max_col = cols[-1]
    return coo_matrix((vals, (rows, cols)), shape=(rows[-1]+1, max_col+1))
1253169
def get_neighbors(distance_matrix, source, eps):
    

    return [dest for dest, distance in enumerate(distance_matrix[source]) if distance < eps]
607712
private double distance(double[] center, double[] center2) {
		double d = 0D;
		for (int i = 0; i < center.length; i++) {
			d += Math.pow((center[i] - center2[i]), 2);
		}
		return Math.sqrt(d);
	}
278387
def matrix2lha(M):
    """"""
    l = []
    ind = np.indices(M.shape).reshape(M.ndim, M.size).T
    for i in ind:
        l.append([j+1 for j in i] + [M[tuple(i)]])
    return l
853731
def normalize_sparse(M, norm="frag", order=1, iterations=3):
    

    try:
        from scipy.sparse import csr_matrix
    except ImportError as e:
        print(str(e))
        print("I am peforming dense normalization by default.")
        return normalize_dense(M.todense())
    r = csr_matrix(M)
    if norm == "SCN":
        for _ in range(1, iterations):
            row_sums = np.array(r.sum(axis=1)).flatten()
            col_sums = np.array(r.sum(axis=0)).flatten()
            row_indices, col_indices = r.nonzero()
            r.data /= row_sums[row_indices] * col_sums[col_indices]

    elif norm == "global":
        try:
            from scipy.sparse import linalg
            r = linalg.norm(M, ord=order)
        except (ImportError, AttributeError) as e:
            print(str(e))
            print("I can't import linalg tools for sparse matrices.")
            print("Please upgrade your scipy version to 0.16.0.")

    elif callable(norm):
        r = norm(M)

    else:
        print("Unknown norm. Returning input as fallback")

    return r
395842
def distance(self, other):
        
        return np.linalg.norm(other.coords - self.coords)
1306466
def _compute(self):
        """"""
        # X Labels
        if self.horizontal:
            self._x_pos = [
                x / (self._len - 1) for x in range(self._len)
            ][::-1] if self._len != 1 else [.5]  # Center if only one value
        else:
            self._x_pos = [
                x / (self._len - 1) for x in range(self._len)
            ] if self._len != 1 else [.5]  # Center if only one value

        self._points(self._x_pos)

        if self.include_x_axis:
            # Y Label
            self._box.ymin = min(self._min or 0, 0)
            self._box.ymax = max(self._max or 0, 0)
        else:
            self._box.ymin = self._min
            self._box.ymax = self._max
139787
def minimum_distance2(hull_a, center_a, hull_b, center_b):
    '''
    '''
    if hull_a.shape[0] < 3 or hull_b.shape[0] < 3:
        return slow_minimum_distance2(hull_a, hull_b)
    else:
        return faster_minimum_distance2(hull_a, center_a, hull_b, center_b)
1065017
def generateDistanceMatrix(width, height):
	
	
	# Determine the coordinates of the exact centre of the window
	originX = width / 2
	originY = height / 2
	
	# Generate the distance matrix
	distances = zerosFactory((height,width), dtype=np.float)
	for index, val in np.ndenumerate(distances):
		y,x = index
		distances[(y,x)] = math.sqrt( math.pow(x - originX, 2) + math.pow(y - originY, 2) )
	
	return distances
1000743
def imag(self):
        """"""
        return matrix(self.tt.imag(), n=self.n, m=self.m)
985302
def _energy_distance_from_distance_matrices(
        distance_xx, distance_yy, distance_xy):
    """"""
    return (2 * np.mean(distance_xy) - np.mean(distance_xx) -
            np.mean(distance_yy))
227425
protected static void initializeDistanceMatrix(MatrixParadigm mat, DistanceQuery<?> dq, Linkage linkage) {
    final DBIDArrayIter ix = mat.ix, iy = mat.iy;
    final double[] matrix = mat.matrix;
    final boolean issquare = dq.getDistanceFunction().isSquared();
    FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("Distance matrix computation", matrix.length, LOG) : null;
    int pos = 0;
    for(ix.seek(0); ix.valid(); ix.advance()) {
      final int x = ix.getOffset();
      assert (pos == MatrixParadigm.triangleSize(x));
      for(iy.seek(0); iy.getOffset() < x; iy.advance()) {
        matrix[pos++] = linkage.initial(dq.distance(ix, iy), issquare);
      }
      if(prog != null) {
        prog.setProcessed(pos, LOG);
      }
    }
    // Avoid logging errors in case scratch space was too large:
    if(prog != null) {
      prog.setProcessed(matrix.length, LOG);
    }
    LOG.ensureCompleted(prog);
  }
673889
def _hor_matrix(self, C, P):
        
        S = (P - C).unit                        # unit vector C -> P
        return Matrix(1, 0, 0, 1, -C.x, -C.y) * Matrix(S.x, -S.y, S.y, S.x, 0, 0)
400752
def spectral_embedding(self, n):
        
        coords = spectral_embedding(self._affinity, n)
        return CoordinateMatrix(normalise_rows(coords))
1131398
def cross_product_matrix(vec):
    """"""
    return np.array([[0, -vec[2], vec[1]],
                     [vec[2], 0, -vec[0]],
                     [-vec[1], vec[0], 0]])