--- Sparse Level 2 routines ---
436129
public static int cusparseSgemvi(
        cusparseHandle handle, 
        int transA, 
        int m, 
        int n, 
        Pointer alpha, /** host or device pointer */
        Pointer A, 
        int lda, 
        int nnz, 
        Pointer xVal, 
        Pointer xInd, 
        Pointer beta, /** host or device pointer */
        Pointer y, 
        int idxBase, 
        Pointer pBuffer)
    {
        return checkResult(cusparseSgemviNative(handle, transA, m, n, alpha, A, lda, nnz, xVal, xInd, beta, y, idxBase, pBuffer));
    }
766368
function mont_prep (t1, t2, ax, az) {
        add(t1, ax, az);
        sub(t2, ax, az);
    }
283983
def _coo_to_sparse_series(A, dense_index=False):
    
    s = Series(A.data, MultiIndex.from_arrays((A.row, A.col)))
    s = s.sort_index()
    s = s.to_sparse()  # TODO: specify kind?
    if dense_index:
        # is there a better constructor method to use here?
        i = range(A.shape[0])
        j = range(A.shape[1])
        ind = MultiIndex.from_product([i, j])
        s = s.reindex(ind)
    return s
137818
def edges_sparse(self):
        
        sparse = graph.edges_to_coo(self.edges,
                                    count=len(self.vertices))
        return sparse
91599
public static SparseMatrix from1DArray(int rows, int columns, double[] array) {
        return CRSMatrix.from1DArray(rows, columns, array);
    }
1111590
private void gather(double[] z, SparseVector v, double taui, int d) {
        // Number of entries in the lower and upper part of the original matrix
        int nl = 0, nu = 0;
        for (VectorEntry e : v) {
            if (e.index() < d)
                nl++;
            else if (e.index() > d)
                nu++;
        }
        v.zero();

        // Entries in the L part of the vector
        lower.clear();
        for (int i = 0; i < d; ++i)
            if (Math.abs(z[i]) > taui)
                lower.add(new IntDoubleEntry(i, z[i]));

        // Entries in the U part of the vector
        upper.clear();
        for (int i = d + 1; i < z.length; ++i)
            if (Math.abs(z[i]) > taui)
                upper.add(new IntDoubleEntry(i, z[i]));

        // Sort in descending order
        Collections.sort(lower);
        Collections.sort(upper);

        // Always keep the diagonal
        v.set(d, z[d]);

        // Keep at most nl+p lower entries
        for (int i = 0; i < Math.min(nl + p, lower.size()); ++i) {
            IntDoubleEntry e = lower.get(i);
            v.set(e.index, e.value);
        }

        // Keep at most nu+p upper entries
        for (int i = 0; i < Math.min(nu + p, upper.size()); ++i) {
            IntDoubleEntry e = upper.get(i);
            v.set(e.index, e.value);
        }
    }
827941
public static LinearSolverDense<DMatrixRMaj> general(int numRows , int numCols ) {
        if( numRows == numCols )
            return linear(numRows);
        else
            return leastSquares(numRows,numCols);
    }
1352783
def _zero_many(self, i, j):
    
    i, j, M, N = self._prepare_indices(i, j)

    n_samples = len(i)
    offsets = np.empty(n_samples, dtype=self.indices.dtype)
    ret = _sparsetools.csr_sample_offsets(M, N, self.indptr, self.indices,
                                          n_samples, i, j, offsets)
    if ret == 1:
        # rinse and repeat
        self.sum_duplicates()
        _sparsetools.csr_sample_offsets(M, N, self.indptr,
                                        self.indices, n_samples, i, j,
                                        offsets)

    # only assign zeros to the existing sparsity structure
    self.data[list(offsets[offsets > -1])] = 0
748162
private void accum_all2(Chunk chks[], Chunk wrks, int nh[], int[] rows) {
      final DHistogram hcs[][] = _hcs;
      // Local temp arrays, no atomic updates.
      int    bins[] = new int   [nbins];
      double sums[] = new double[nbins];
      double ssqs[] = new double[nbins];
      // For All Columns
      for( int c=0; c<_ncols; c++) { // for all columns
        Chunk chk = chks[c];
        // For All NIDs
        for( int n=0; n<hcs.length; n++ ) {
          final DRealHistogram rh = ((DRealHistogram)hcs[n][c]);
          if( rh==null ) continue; // Ignore untracked columns in this split
          final int lo = n==0 ? 0 : nh[n-1];
          final int hi = nh[n];
          float min = rh._min2;
          float max = rh._maxIn;
          // While most of the time we are limited to nbins, we allow more bins
          // in a few cases (top-level splits have few total bins across all
          // the (few) splits) so it's safe to bin more; also categoricals want
          // to split one bin-per-level no matter how many levels).
          if( rh._bins.length >= bins.length ) { // Grow bins if needed
            bins = new int   [rh._bins.length];
            sums = new double[rh._bins.length];
            ssqs = new double[rh._bins.length];
          }

          // Gather all the data for this set of rows, for 1 column and 1 split/NID
          // Gather min/max, sums and sum-squares.
          for( int xrow=lo; xrow<hi; xrow++ ) {
            int row = rows[xrow];
            float col_data = (float)chk.at0(row);
            if( col_data < min ) min = col_data;
            if( col_data > max ) max = col_data;
            int b = rh.bin(col_data); // Compute bin# via linear interpolation
            bins[b]++;                // Bump count in bin
            double resp = wrks.at0(row);
            sums[b] += resp;
            ssqs[b] += resp*resp;
          }

          // Add all the data into the Histogram (atomically add)
          rh.setMin(min);       // Track actual lower/upper bound per-bin
          rh.setMax(max);
          for( int b=0; b<rh._bins.length; b++ ) { // Bump counts in bins
            if( bins[b] != 0 ) { Utils.AtomicIntArray.add(rh._bins,b,bins[b]); bins[b]=0; }
            if( ssqs[b] != 0 ) { rh.incr1(b,sums[b],ssqs[b]); sums[b]=ssqs[b]=0; }
          }
        }
      }
    }
616238
private static void enlargeTables(float[][] data, int[][] rowIndex, int cols, int currentRow, int currentCol) {
        while (data[currentRow].length < currentCol + cols) {
            if(data[currentRow].length == SPARSE_MATRIX_DIM) {
                currentCol = 0;
                cols -= (data[currentRow].length - currentCol);
                currentRow++;
                data[currentRow] = malloc4f(ALLOCATED_ARRAY_LEN);
                rowIndex[currentRow] = malloc4(ALLOCATED_ARRAY_LEN);
            } else {
                int newLen = (int) Math.min((long) data[currentRow].length << 1L, (long) SPARSE_MATRIX_DIM);
                data[currentRow] = Arrays.copyOf(data[currentRow], newLen);
                rowIndex[currentRow] = Arrays.copyOf(rowIndex[currentRow], newLen);
            }
        }
    }
172170
private void indexSparse(DBIDRef ref, SparseNumberVector obj) {
    double len = 0.;
    for(int iter = obj.iter(); obj.iterValid(iter); iter = obj.iterAdvance(iter)) {
      final int dim = obj.iterDim(iter);
      final double val = obj.iterDoubleValue(iter);
      if(val == 0. || val != val) {
        continue;
      }
      len += val * val;
      getOrCreateColumn(dim).add(val, ref);
    }
    length.put(ref, len);
  }
1246933
public static void tred2(int n, double v[][], double d[], double e[]) {

    //  This is derived from the Algol procedures tred2 by
    //  Bowdler, Martin, Reinsch, and Wilkinson, Handbook for
    //  Auto. Comp., Vol.ii-Linear Algebra, and the corresponding
    //  Fortran subroutine in EISPACK.

    System.arraycopy(v[n - 1], 0, d, 0, n);

    // Householder reduction to tridiagonal form.

    for (int i = n - 1; i > 0; i--) {

      // Scale to avoid under/overflow.

      double scale = 0.0;
      double h = 0.0;
      for (int k = 0; k < i; k++) {
        scale = scale + Math.abs(d[k]);
      }
      if (scale == 0.0) {
        e[i] = d[i - 1];
        for (int j = 0; j < i; j++) {
          d[j] = v[i - 1][j];
          v[i][j] = 0.0;
          v[j][i] = 0.0;
        }
      } else {

        h = householderIteration(i, scale, v, d, e);

      }
      d[i] = h;
    }

    // Accumulate transformations.
    accumulateTransformations(n, v, d);

    e[0] = 0.0;
  }
1370740
float computeObjective(SparseMatrix v, SparseMatrix w, SparseMatrix h) {
		SparseMatrix matrixWH = w.mutiplyMatrix(h);
		SparseMatrix diff = v.clone();
		diff.minus(matrixWH);
		return diff.l2Norm();

	}
1163099
def generate_evenly_distributed_data_sparse(dim = 2000,
                                            num_active = 40,
                                            num_samples = 1000):
  
  indices = [numpy.random.choice(dim, size = num_active, replace = False)
      for _ in range(num_samples)]
  data = SM32()

  data.reshape(0, dim)
  for row in indices:
    data.addRowNZ(row, [1]*num_active)

  # data.reshape(num_samples, dim)
  # for sample, datapoint in enumerate(indices):
  #   for index in datapoint:
  #     data[sample, index] = 1.

  return data
108532
def _arith_method_SPARSE_ARRAY(cls, op, special):
    
    op_name = _get_op_name(op, special)

    def wrapper(self, other):
        from pandas.core.arrays.sparse.array import (
            SparseArray, _sparse_array_op, _wrap_result, _get_fill)
        if isinstance(other, np.ndarray):
            if len(self) != len(other):
                raise AssertionError("length mismatch: {self} vs. {other}"
                                     .format(self=len(self), other=len(other)))
            if not isinstance(other, SparseArray):
                dtype = getattr(other, 'dtype', None)
                other = SparseArray(other, fill_value=self.fill_value,
                                    dtype=dtype)
            return _sparse_array_op(self, other, op, op_name)
        elif is_scalar(other):
            with np.errstate(all='ignore'):
                fill = op(_get_fill(self), np.asarray(other))
                result = op(self.sp_values, other)

            return _wrap_result(op_name, result, self.sp_index, fill)
        else:  # pragma: no cover
            raise TypeError('operation with {other} not supported'
                            .format(other=type(other)))

    wrapper.__name__ = op_name
    return wrapper
621622
def _M2(Xvar, Yvar, mask_X=None, mask_Y=None, xsum=0, xconst=0, ysum=0, yconst=0, weights=None, diag_only=False):
    
    if mask_X is None and mask_Y is None:
        return _M2_dense(Xvar, Yvar, weights=weights, diag_only=diag_only)
    else:
        # Check if one of the masks is not None, modify it and also adjust the constant columns:
        if mask_X is None:
            mask_X = np.ones(Xvar.shape[1], dtype=np.bool)
            xconst = np.ones(0, dtype=float)
        if mask_Y is None:
            mask_Y = np.ones(Yvar.shape[1], dtype=np.bool)
            yconst = np.ones(0, dtype=float)
    if _is_zero(xsum) and _is_zero(ysum) or _is_zero(xconst) and _is_zero(yconst):
        return _M2_sparse(Xvar, mask_X, Yvar, mask_Y, weights=weights)
    else:
        return _M2_const(Xvar, mask_X, xsum[mask_X], xconst, Yvar, mask_Y, ysum[mask_Y], yconst, weights=weights)
733081
public static SparseTensor fromUnorderedKeyValuesNoCopy(int[] dimensionNumbers,
      int[] dimensionSizes, long[] keyNums, double[] values) {
    ArrayUtils.sortKeyValuePairs(keyNums, values, 0, keyNums.length);
    return new SparseTensor(dimensionNumbers, dimensionSizes, keyNums, values);
  }