Represent k1, k2 in a Joint Sparse Form
487010
public static function getJSF($k1, $k2)
    {
        $jsf = array( array(), array() );
        $k1 = $k1->_clone();
        $k2 = $k2->_clone();
        $d1 = 0;
        $d2 = 0;

        while( $k1->cmpn(-$d1) > 0 || $k2->cmpn(-$d2) > 0 )
        {
            // First phase
            $m14 = ($k1->andln(3) + $d1) & 3;
            $m24 = ($k2->andln(3) + $d2) & 3;
            if( $m14 === 3 )
                $m14 = -1;
            if( $m24 === 3 )
                $m24 = -1;

            $u1 = 0;
            if( ($m14 & 1) !== 0 )
            {
                $m8 = ($k1->andln(7) + $d1) & 7;
                $u1 = ( ($m8 === 3 || $m8 === 5) && $m24 === 2 ) ? -$m14 : $m14;
            }
            array_push($jsf[0], $u1);

            $u2 = 0;
            if( ($m24 & 1) !== 0 )
            {
                $m8 = ($k2->andln(7) + $d2) & 7;
                $u2 = ( ($m8 === 3 || $m8 === 5) && $m14 === 2 ) ? -$m24 : $m24;
            }
            array_push($jsf[1], $u2);

            // Second phase
            if( (2 * $d1) === ($u1 + 1) )
                $d1 = 1 - $d1;
            if( (2 * $d2) === ($u2 + 1) )
                $d2 = 1 - $d2;
            $k1->iushrn(1);
            $k2->iushrn(1);
        }

        return $jsf;
    }
218408
def kld(d1, d2):
    
    d1, d2 = flatten(d1), flatten(d2)
    return entropy(d1, d2, 2.0)
109209
def posterior_covariance_between_points(self, X1, X2):
        
        return self.posterior.covariance_between_points(self.kern, self.X, X1, X2)
602784
def scalar_projection(v1, v2):
    '''
    '''
    return np.dot(v1, v2) / np.linalg.norm(v2)
170950
def _K_computations(self, X, X2=None):
        """"""
        self._lengthscales=self.mapping.f(X)
        self._lengthscales2=np.square(self._lengthscales)
        if X2==None:
            self._lengthscales_two = self._lengthscales
            self._lengthscales_two2 = self._lengthscales2
            Xsquare = np.square(X).sum(1)
            self._K_dist2 = -2.*tdot(X) + Xsquare[:, None] + Xsquare[None, :]
        else:
            self._lengthscales_two = self.mapping.f(X2)
            self._lengthscales_two2 = np.square(self._lengthscales_two)
            self._K_dist2 = -2.*np.dot(X, X2.T) + np.square(X).sum(1)[:, None] + np.square(X2).sum(1)[None, :]
        self._w2 = self._lengthscales2 + self._lengthscales_two2.T
        prod_length = self._lengthscales*self._lengthscales_two.T
        self._K_exponential = np.exp(-self._K_dist2/self._w2)
        self._K_dvar = np.sign(prod_length)*(2*np.abs(prod_length)/self._w2)**(self.input_dim/2.)*np.exp(-self._K_dist2/self._w2)
609344
function connectedComponents_sparse(cells) {
  var vertices  = unique(normalize(skeleton(cells, 0)))
    , labels    = new UnionFind(vertices.length)
  for(var i=0; i<cells.length; ++i) {
    var c = cells[i]
    for(var j=0; j<c.length; ++j) {
      var vj = findCell(vertices, [c[j]])
      for(var k=j+1; k<c.length; ++k) {
        labels.link(vj, findCell(vertices, [c[k]]))
      }
    }
  }
  var components        = []
    , component_labels  = labels.ranks
  for(var i=0; i<component_labels.length; ++i) {
    component_labels[i] = -1
  }
  for(var i=0; i<cells.length; ++i) {
    var l = labels.find(findCell(vertices, [cells[i][0]]));
    if(component_labels[l] < 0) {
      component_labels[l] = components.length
      components.push([cells[i].slice(0)])
    } else {
      components[component_labels[l]].push(cells[i].slice(0))
    }
  }
  return components
}
852988
def is_sparse_vector(x):
    
    return sp.issparse(x) and len(x.shape) == 2 and x.shape[0] == 1
127092
def k_modes(X, n_clusters, max_iter, dissim, init, n_init, verbose, random_state, n_jobs):
    """"""
    random_state = check_random_state(random_state)
    if sparse.issparse(X):
        raise TypeError("k-modes does not support sparse data.")

    X = check_array(X, dtype=None)

    # Convert the categorical values in X to integers for speed.
    # Based on the unique values in X, we can make a mapping to achieve this.
    X, enc_map = encode_features(X)

    n_points, n_attrs = X.shape
    assert n_clusters <= n_points, "Cannot have more clusters ({}) " \
                                   "than data points ({}).".format(n_clusters, n_points)

    # Are there more n_clusters than unique rows? Then set the unique
    # rows as initial values and skip iteration.
    unique = get_unique_rows(X)
    n_unique = unique.shape[0]
    if n_unique <= n_clusters:
        max_iter = 0
        n_init = 1
        n_clusters = n_unique
        init = unique

    results = []
    seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init)
    if n_jobs == 1:
        for init_no in range(n_init):
            results.append(k_modes_single(X, n_clusters, n_points, n_attrs, max_iter,
                                          dissim, init, init_no, verbose, seeds[init_no]))
    else:
        results = Parallel(n_jobs=n_jobs, verbose=0)(
            delayed(k_modes_single)(X, n_clusters, n_points, n_attrs, max_iter,
                                    dissim, init, init_no, verbose, seed)
            for init_no, seed in enumerate(seeds))
    all_centroids, all_labels, all_costs, all_n_iters = zip(*results)

    best = np.argmin(all_costs)
    if n_init > 1 and verbose:
        print("Best run was number {}".format(best + 1))

    return all_centroids[best], enc_map, all_labels[best], \
        all_costs[best], all_n_iters[best]
285152
def _maybe_to_sparse(array):
    
    if isinstance(array, ABCSparseSeries):
        array = array.values.copy()
    return array
788700
def K_r2(self, r2):
        
        r = self._clipped_sqrt(r2)
        return self.K_r(r)
1271544
def K(self, X, X2, target):
        """"""
        if (X2 is None) or (X2 is X):
            target[np.diag_indices_from(target)] += self._Kdiag(X)
139353
def _sparse_blockify(tuples, dtype=None):
    

    new_blocks = []
    for i, names, array in tuples:
        array = _maybe_to_sparse(array)
        block = make_block(array, placement=[i])
        new_blocks.append(block)

    return new_blocks
1345552
def kernel(x1, x2, method='gaussian', sigma=1, **kwargs):
    """"""
    if method.lower() in ['gaussian', 'gauss', 'rbf']:
        K = np.exp(-dist(x1, x2) / (2 * sigma**2))
    return K
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)
702712
def solve_kkt(U_Q, d, G, A, U_S, rx, rs, rz, ry, dbg=False):
    
    nineq, nz, neq, _ = get_sizes(G, A)

    invQ_rx = torch.potrs(rx.view(-1, 1), U_Q).view(-1)
    if neq > 0:
        h = torch.cat([torch.mv(A, invQ_rx) - ry,
                       torch.mv(G, invQ_rx) + rs / d - rz], 0)
    else:
        h = torch.mv(G, invQ_rx) + rs / d - rz

    w = -torch.potrs(h.view(-1, 1), U_S).view(-1)

    g1 = -rx - torch.mv(G.t(), w[neq:])
    if neq > 0:
        g1 -= torch.mv(A.t(), w[:neq])
    g2 = -rs - w[neq:]

    dx = torch.potrs(g1.view(-1, 1), U_Q).view(-1)
    ds = g2 / d
    dz = w[neq:]
    dy = w[:neq] if neq > 0 else None

    # if np.all(np.array([x.norm() for x in [rx, rs, rz, ry]]) != 0):
    if dbg:
        import IPython
        import sys
        IPython.embed()
        sys.exit(-1)

    # if rs.norm() > 0: import IPython, sys; IPython.embed(); sys.exit(-1)
    return dx, ds, dz, dy
363072
def transition_matrix_sparse(self):
        
        P = diags([self.q[1:], self.r, self.p[0:-1]], [-1, 0, 1])
        return P
668952
def bin_kb_sparse(M, positions, length=10):
    

    try:
        from scipy.sparse import coo_matrix
    except ImportError as e:
        print(str(e))
        print("I am peforming dense normalization by default.")
        return bin_kb_dense(M.todense(), positions=positions)
    r = M.tocoo()
    unit = 10**3
    ul = unit * length
    units = positions / ul
    n = len(positions)
    indices = np.floor(units)
    row = [indices[np.floor(i)] for i in r.row / ul]
    col = [indices[np.floor(j)] for j in r.col / ul]
    binned_indices = positions[
        [i for i in range(n - 1) if np.ceil(units[i]) < np.ceil(units[i + 1])]]
    return coo_matrix((r.data, (row, col))), binned_indices