Guess the rank of the incomplete matrix
343388
def guess_rank(M_E):
    ''' '''
    n, m = M_E.shape
    epsilon = np.count_nonzero(M_E) / np.sqrt(m * n)
    _, S0, _ = svds_descending(M_E, min(100, max(M_E.shape) - 1))
    S0 = np.diag(S0)

    S1 = S0[:-1] - S0[1:]
    S1_ = S1 / np.mean(S1[-10:])
    r1 = 0
    lam = 0.05
    cost = [None] * len(S1_)
    while r1 <= 0:
        for idx in range(len(S1_)):
            cost[idx] = lam * max(S1_[idx:]) + idx
        i2 = np.argmin(cost)
        r1 = np.max(i2)
        lam += 0.05

    cost = [None] * (len(S0) - 1)
    for idx in range(len(S0) - 1):
        cost[idx] = (S0[idx + 1] + np.sqrt(idx * epsilon)
                     * S0[0] / epsilon) / S0[idx]
    i2 = np.argmin(cost)
    r2 = np.max(i2 + 1)
    r = max([r1, r2])

    return r
197765
def rank(self):
        """"""
        r = np.empty(self.size, np.int)
        r[self.sorter] = np.arange(self.size)
        return r
675501
private void computeGradientAndHessian(DMatrixRMaj param  )
    {
        // residuals = f(x) - y
        function.compute(param, residuals);

        computeNumericalJacobian(param,jacobian);

        CommonOps_DDRM.multTransA(jacobian, residuals, g);
        CommonOps_DDRM.multTransA(jacobian, jacobian,  H);

        CommonOps_DDRM.extractDiag(H,Hdiag);
    }
399555
def get_row_missing(xc, xd, cdiffs, index, cindices, dindices):
    
    row = np.empty(0, dtype=np.double)  # initialize empty row
    cinst1 = xc[index]  # continuous-valued features for index instance
    dinst1 = xd[index]  # discrete-valued features for index instance
    # Boolean mask locating missing values for continuous features for index instance
    can = cindices[index]
    # Boolean mask locating missing values for discrete features for index instance
    dan = dindices[index]
    tf = len(cinst1) + len(dinst1)  # total number of features.

    # Progressively compare current instance to all others. Excludes comparison with self indexed instance. (Building the distance matrix triangle).
    for j in range(index):
        dist = 0
        dinst2 = xd[j]  # discrete-valued features for compared instance
        cinst2 = xc[j]  # continuous-valued features for compared instance

        # Manage missing values in discrete features
        # Boolean mask locating missing values for discrete features for compared instance
        dbn = dindices[j]
        # indexes where there is at least one missing value in the feature between an instance pair.
        idx = np.unique(np.append(dan, dbn))
        # Number of features excluded from distance calculation due to one or two missing values within instance pair. Used to normalize distance values for comparison.
        dmc = len(idx)
        d1 = np.delete(dinst1, idx)  # delete unique missing features from index instance
        d2 = np.delete(dinst2, idx)  # delete unique missing features from compared instance

        # Manage missing values in continuous features
        # Boolean mask locating missing values for continuous features for compared instance
        cbn = cindices[j]
        # indexes where there is at least one missing value in the feature between an instance pair.
        idx = np.unique(np.append(can, cbn))
        # Number of features excluded from distance calculation due to one or two missing values within instance pair. Used to normalize distance values for comparison.
        cmc = len(idx)
        c1 = np.delete(cinst1, idx)  # delete unique missing features from index instance
        c2 = np.delete(cinst2, idx)  # delete unique missing features from compared instance
        # delete unique missing features from continuous value difference scores
        cdf = np.delete(cdiffs, idx)

        # Add discrete feature distance contributions (missing values excluded) - Hamming distance
        dist += len(d1[d1 != d2])

        # Add continuous feature distance contributions (missing values excluded) - Manhattan distance (Note that 0-1 continuous value normalization is included ~ subtraction of minimums cancel out)
        dist += np.sum(np.absolute(np.subtract(c1, c2)) / cdf)

        # Normalize distance calculation based on total number of missing values bypassed in either discrete or continuous features.
        tnmc = tf - dmc - cmc  # Total number of unique missing counted
        # Distance normalized by number of features included in distance sum (this seeks to handle missing values neutrally in distance calculation)
        dist = dist/float(tnmc)

        row = np.append(row, dist)

    return row
363072
def transition_matrix_sparse(self):
        
        P = diags([self.q[1:], self.r, self.p[0:-1]], [-1, 0, 1])
        return P
1035019
private static int[] elmhes(DenseMatrix A) {
        int n = A.nrows();
        int[] perm = new int[n];

        for (int m = 1; m < n - 1; m++) {
            double x = 0.0;
            int i = m;
            for (int j = m; j < n; j++) {
                if (Math.abs(A.get(j, m - 1)) > Math.abs(x)) {
                    x = A.get(j, m - 1);
                    i = j;
                }
            }
            perm[m] = i;
            if (i != m) {
                for (int j = m - 1; j < n; j++) {
                    double swap = A.get(i, j);
                    A.set(i, j, A.get(m, j));
                    A.set(m, j, swap);
                }
                for (int j = 0; j < n; j++) {
                    double swap = A.get(j, i);
                    A.set(j, i, A.get(j, m));
                    A.set(j, m, swap);
                }
            }
            if (x != 0.0) {
                for (i = m + 1; i < n; i++) {
                    double y = A.get(i, m - 1);
                    if (y != 0.0) {
                        y /= x;
                        A.set(i, m - 1, y);
                        for (int j = m; j < n; j++) {
                            A.sub(i, j, y * A.get(m, j));
                        }
                        for (int j = 0; j < n; j++) {
                            A.add(j, m, y * A.get(j, i));
                        }
                    }
                }
            }
        }

        return perm;
    }
1233496
def matrix_chain_mult(M):
    
    opt, arg = matrix_mult_opt_order(M)
    return _apply_order(M, arg, 0, len(M)-1)
565238
def get_tau_matrix(self):
        
        num_edges = len(self.edges)
        tau = np.empty([num_edges, num_edges])

        for i in range(num_edges):
            edge = self.edges[i]
            for j in edge.neighbors:
                if self.level == 1:
                    left_u = self.u_matrix[:, edge.L]
                    right_u = self.u_matrix[:, edge.R]

                else:
                    left_parent, right_parent = edge.parents
                    left_u, right_u = Edge.get_conditional_uni(left_parent, right_parent)

                tau[i, j], pvalue = scipy.stats.kendalltau(left_u, right_u)

        return tau
776996
def rank(self):
        
        rank = re.findall(r'\d+', self._rank)
        if len(rank) == 0:
            return None
        return rank[0]
187326
def sort_matrix(a,n=0):
    
    a = _n.array(a)
    return a[:,a[n,:].argsort()]
434337
function hingeLoss(p, weights) {
  const [label, features] = p;
  const grad = [];
  let dotProd = 0;

  for (let i = 0; i < features.length; i++)
    dotProd += (features[i] || 0) * (weights[i] || 0);

  if (label * dotProd < 1)
    for (let i = 0; i < features.length; i++)
      grad[i] = -label * (features[i] || 0);
  else
    for (let i = 0; i < features.length; i++)
      grad[i] = 0;

  return grad;
}
16087
def cut_matrix(self, n):
        """"""
        cm = np.zeros((n, n))

        for part in self.partition:
            from_, to = self.direction.order(part.mechanism, part.purview)
            # All indices external to this part
            external = tuple(set(self.indices) - set(to))
            cm[np.ix_(from_, external)] = 1

        return cm
1338591
def check_precomputed_distance_matrix(X):
    
    tmp = X.copy()
    tmp[np.isinf(tmp)] = 1
    check_array(tmp)
897426
def rank(idx, dim):
    """"""
    idxm = multi_index(idx, dim)
    out = 0
    while idxm[-1:] == (0,):
        out += 1
        idxm = idxm[:-1]
    return out
610739
def randmatrix(m, n, random_seed=None):
    """"""
    val = np.sqrt(6.0 / (m + n))
    np.random.seed(random_seed)
    return np.random.uniform(-val, val, size=(m, n))
435553
public void gaussianElimination(int[][] matrix) {
    assert(matrix != null && matrix.length > 0 && matrix[0].length > 0
           && matrix.length < matrix[0].length);
    int height = matrix.length;
    int width = matrix[0].length;
    for (int i = 0; i < height; i++) {
      boolean pivotFound = false;
      // scan the column for a nonzero pivot and swap it to the diagonal
      for (int j = i; j < height; j++) {
        if (matrix[i][j] != 0) {
          int[] tmp = matrix[i];
          matrix[i] = matrix[j];
          matrix[j] = tmp;
          pivotFound = true;
          break;
        }
      }
      if (!pivotFound) {
        continue;
      }
      int pivot = matrix[i][i];
      for (int j = i; j < width; j++) {
        matrix[i][j] = divide(matrix[i][j], pivot);
      }
      for (int j = i + 1; j < height; j++) {
        int lead = matrix[j][i];
        for (int k = i; k < width; k++) {
          matrix[j][k] = add(matrix[j][k], multiply(lead, matrix[i][k]));
        }
      }
    }
    for (int i = height - 1; i >=0; i--) {
      for (int j = 0; j < i; j++) {
        int lead = matrix[j][i];
        for (int k = i; k < width; k++) {
          matrix[j][k] = add(matrix[j][k], multiply(lead, matrix[i][k]));
        }
      }
    }
  }
969305
public function computeMissing()
    {
        $Missing = [];
        for ($X = 0; $X <= $this->GridSizeX; $X++) {
            for ($Y = 0; $Y <= $this->GridSizeY; $Y++) {
                if ($this->Points[$X][$Y] == UNKNOWN) {
                    $Missing[] = $X . "," . $Y;
                }
            }
        }
        shuffle($Missing);

        foreach ($Missing as $Pos) {
            $Pos = preg_split("/,/", $Pos);
            $X = $Pos[0];
            $Y = $Pos[1];

            if ($this->Points[$X][$Y] == UNKNOWN) {
                $NearestNeighbor = $this->getNearestNeighbor($X, $Y);

                $Value = 0;
                $Points = 0;
                for ($Xi = $X - $NearestNeighbor; $Xi <= $X + $NearestNeighbor; $Xi++) {
                    for ($Yi = $Y - $NearestNeighbor; $Yi <= $Y + $NearestNeighbor; $Yi++) {
                        if ($Xi >= 0
                            && $Yi >= 0
                            && $Xi <= $this->GridSizeX
                            && $Yi <= $this->GridSizeY
                            && $this->Points[$Xi][$Yi] != UNKNOWN
                            && $this->Points[$Xi][$Yi] != IGNORED
                        ) {
                            $Value = $Value + $this->Points[$Xi][$Yi];
                            $Points++;
                        }
                    }
                }

                if ($Points != 0) {
                    $this->Points[$X][$Y] = $Value / $Points;
                }
            }
        }
    }