How to use the scipy.sparse.csc_matrix function in scipy

To help you get started, we’ve selected a few scipy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github flatironinstitute / CaImAn / caiman / source_extraction / cnmf / online_cnmf.py View on Github external
for rp in range(len(self.estimates.ind_new)*2):
                                out.write(vid_frame)

                        cv2.imshow('frame', vid_frame)
                        for rp in range(len(self.estimates.ind_new)*2):
                            cv2.imshow('frame', vid_frame)
                        if cv2.waitKey(1) & 0xFF == ord('q'):
                            break
                    t += 1
                    t_online.append(time() - t_frame_start)
        
            self.Ab_epoch.append(self.estimates.Ab.copy())

        if self.params.get('online', 'normalize'):
            self.estimates.Ab /= 1./self.img_norm.reshape(-1, order='F')[:,np.newaxis]
            self.estimates.Ab = csc_matrix(self.estimates.Ab)
        self.estimates.A, self.estimates.b = self.estimates.Ab[:, self.params.get('init', 'nb'):], self.estimates.Ab[:, :self.params.get('init', 'nb')].toarray()
        self.estimates.C, self.estimates.f = self.estimates.C_on[self.params.get('init', 'nb'):self.M, t - t //
                         epochs:t], self.estimates.C_on[:self.params.get('init', 'nb'), t - t // epochs:t]
        noisyC = self.estimates.noisyC[self.params.get('init', 'nb'):self.M, t - t // epochs:t]
        self.estimates.YrA = noisyC - self.estimates.C
        if self.estimates.OASISinstances is not None:
            self.estimates.bl = [osi.b for osi in self.estimates.OASISinstances]
            self.estimates.S = np.stack([osi.s for osi in self.estimates.OASISinstances])
            self.estimates.S = self.estimates.S[:, t - t // epochs:t]
        else:
            self.estimates.bl = [0] * self.estimates.C.shape[0]
            self.estimates.S = np.zeros_like(self.estimates.C)
        if self.params.get('online', 'ds_factor') > 1:
            dims = Y_.shape[1:]
            self.estimates.A = hstack([coo_matrix(cv2.resize(self.estimates.A[:, i].reshape(self.dims, order='F').toarray(),
                                                            dims[::-1]).reshape(-1, order='F')[:,None]) for i in range(self.N)], format='csc')
github oxfordcontrol / osqp / tests / python / performance_profile_maros.py View on Github external
def load_maros_meszaros_problem(f):
    # Load file
    m = spio.loadmat(f)

    # Convert matrices
    Q = m['Q'].astype(float)
    c = m['c'].T.flatten().astype(float)
    Aeq = m['A'].astype(float)
    beq = m['ru'].T.flatten().astype(float)
    lb = m['lb'].T.flatten().astype(float)
    ub = m['ub'].T.flatten().astype(float)
    nx = Q.shape[0]
    Aineq = spspa.csc_matrix(np.zeros((1, nx)))
    bineq = np.array([0.0])

    # Define problem
    p = qp.quadprogProblem(Q, c, Aeq, beq, Aineq, bineq, lb, ub)

    return p
github pmgbergen / porepy / test / integration / test_elliptic_interface_laws.py View on Github external
g_s.grid_num = 1
    g_m.grid_num = 2
    g_full.grid_num = 3

    gb = pp.GridBucket()
    gb_full = pp.GridBucket()
    gb.add_nodes([g_s, g_m])
    gb_full.add_nodes([g_full])

    contact_s = np.where(g_s.face_centers[0] > 1 - 1e-10)[0]
    contact_m = np.where(g_m.face_centers[0] < 1 + 1e-10)[0]
    data = np.ones(contact_s.size, dtype=np.bool)

    shape = (g_s.num_faces, g_m.num_faces)
    slave_master = sps.csc_matrix((data, (contact_m, contact_s)), shape=shape)

    mortar_grid, _, _ = pp.grids.partition.extract_subgrid(g_s, contact_s, faces=True)

    gb.add_edge([g_s, g_m], slave_master)

    gb.assign_node_ordering()
    gb_full.assign_node_ordering()

    # Slave and master is defined by the node number.
    # In python 3.5 the node-nombering does not follow the one given in gb.add_edge
    # I guess also the face_face mapping given on the edge also should change,
    # but this is not used
    g_1, _ = gb.nodes_of_edge([g_s, g_m])
    if g_1.grid_num == 2:
        g_m = g_s
        g_s = g_1
github PreferredAI / cornac / cornac / eval_strategies / split.py View on Github external
def evaluate(self, model, metrics):
        # Organize metrics into "rating" and "ranking" for efficiency purposes
        ranking_metrics = metrics['ranking']
        rating_metrics = metrics['rating']

        if not self.split_ran:
            self.run()

        model.fit(self.data_train)
        print("Starting evaluation")
        res_per_u = sp.csc_matrix((self.data_test.shape[0],
                             len(ranking_metrics)+len(rating_metrics) + 1))  # this matrix will contain the evaluation results for each user

        # evaluation is done user by user to avoid memory errors on large datasets.
        # loops are inefficent in python, this part should be re-implement in cython or c/c++"""
        nb_processed_users = 0
        for u in range(self.data_test.shape[0]):
            if not np.sum(self.data_test_bin[u, :]):  # users with 0 heldout items should not be consider in the evaluation
                nb_processed_users += 1
            else:
                known_items = which_(self.data_train[u, :].todense().A1, ">",0)
                if len(ranking_metrics):
                    u_rank_list = model.rank(user_id=u, known_items = known_items)
                if len(rating_metrics):
                    u_pred_scores = model.score(user_index=u, item_indexes = None)

                # computing the diffirent metrics
github oxfordcontrol / osqp_benchmarks / problem_classes / lasso.py View on Github external
def _generate_qp_problem(self):
        '''
        Generate QP problem
        '''

        # Construct the problem
        #       minimize	y' * y + lambda * 1' * t
        #       subject to  y = Ax - b
        #                   -t <= x <= t
        P = spa.block_diag((spa.csc_matrix((self.n, self.n)),
                            2*spa.eye(self.m),
                            spa.csc_matrix((self.n, self.n))), format='csc')
        q = np.append(np.zeros(self.m + self.n),
                      self.lambda_param * np.ones(self.n))
        In = spa.eye(self.n)
        Onm = spa.csc_matrix((self.n, self.m))
        A = spa.vstack([spa.hstack([self.Ad, -spa.eye(self.m),
                                    spa.csc_matrix((self.m, self.n))]),
                        spa.hstack([In, Onm, -In]),
                        spa.hstack([In, Onm, In])]).tocsc()
        l = np.hstack([self.bd, -np.inf * np.ones(self.n), np.zeros(self.n)])
        u = np.hstack([self.bd, np.zeros(self.n), np.inf * np.ones(self.n)])

        problem = {}
        problem['P'] = P
        problem['q'] = q
github SanPen / GridCal / src / GridCal / ThirdParty / pulp / pulp_extra.py View on Github external
CSC matrix-vector or CSC matrix-matrix dot product (A x b)
    :param mat: CSC sparse matrix (A)
    :param arr: dense vector or matrix of object type (b)
    :return: vector or matrix result of the product
    """
    n_rows, n_cols = mat.shape

    # check dimensional compatibility
    assert (n_cols == arr.shape[0])

    # check that the sparse matrix is indeed of CSC format
    if mat.format == 'csc':
        mat_2 = mat
    else:
        # convert the matrix to CSC sparse
        mat_2 = csc_matrix(mat)

    if len(arr.shape) == 1:
        """
        Uni-dimensional sparse matrix - vector product
        """
        res = np.zeros(n_rows, dtype=arr.dtype)
        for i in range(n_cols):
            for ii in range(mat_2.indptr[i], mat_2.indptr[i + 1]):
                j = mat_2.indices[ii]  # row index
                res[j] += mat_2.data[ii] * arr[i]  # C.data[ii] is equivalent to C[i, j]
    else:
        """
        Multi-dimensional sparse matrix - matrix product
        """
        cols_vec = arr.shape[1]
        res = np.zeros((n_rows, cols_vec), dtype=arr.dtype)
github Parallel-in-Time / pySDC / pySDC / implementations / problem_classes / AdvectionEquation_1D_FD.py View on Github external
elif order == 6:
                A[0, N - 3] = stencil[0]
                A[0, N - 2] = stencil[1]
                A[0, N - 1] = stencil[2]
                A[1, N - 2] = stencil[0]
                A[1, N - 1] = stencil[1]
                A[2, N - 1] = stencil[0]
                A[N - 3, 0] = stencil[6]
                A[N - 2, 0] = stencil[5]
                A[N - 2, 1] = stencil[6]
                A[N - 1, 0] = stencil[4]
                A[N - 1, 1] = stencil[5]
                A[N - 1, 2] = stencil[6]

            A = c* coeff * (1.0 / dx) * A
            return sp.csc_matrix(A)

        else:

            if order == 1:
                stencil = [-1.0, 1.0]
                coeff = 1.0
                zero_pos = 2

            elif order == 2:
                stencil = [1.0, -4.0, 3.0]
                coeff = 1.0 / 2.0
                zero_pos = 3

            elif order == 3:
                stencil = [1.0, -6.0, 3.0, 2.0]
                coeff = 1.0 / 6.0
github cvxgrp / diffcp / diffcp / cone_program.py View on Github external
(`dA`, `db`, `dc`), the result of applying the adjoint to the
            perturbations; the sparsity pattern of `dA` matches that of `A`.
        """
        dw = -(x @ dx + y @ dy + s @ ds)
        dz = np.concatenate(
            [dx, D_proj_dual_cone.rmatvec(dy + ds) - ds, np.array([dw])])

        if np.allclose(dz, 0):
            r = np.zeros(dz.shape)
        elif mode == "dense":
            r = _diffcp._solve_adjoint_derivative_dense(M, MT, dz)
        else:
            r = _diffcp.lsqr(MT, dz).solution

        values = pi_z[cols] * r[rows + n] - pi_z[n + rows] * r[cols]
        dA = sparse.csc_matrix((values, (rows, cols)), shape=A.shape)
        db = pi_z[n:n + m] * r[-1] - pi_z[-1] * r[n:n + m]
        dc = pi_z[:n] * r[-1] - pi_z[-1] * r[:n]

        return dA, db, dc
github dmitriy-serdyuk / twinnet-asr / libs / Theano / theano / sparse / opt.py View on Github external
def perform(self, node, inputs, outputs):
        (a_val, a_ind, a_ptr, a_nrows, b) = inputs
        (out,) = outputs
        a = scipy.sparse.csc_matrix((a_val, a_ind, a_ptr),
                                    (a_nrows, b.shape[0]),
                                    copy=False)
        # out[0] = a.dot(b)
        out[0] = theano._asarray(a * b, dtype=node.outputs[0].type.dtype)
        assert _is_dense(out[0])  # scipy 0.7 automatically converts to dense
github PreferredAI / cornac / cornac / models / pcrl / pcrl.py View on Github external
digaG_s.data = sc.special.digamma(digaG_s.data)

            Lt = digaG_s - logG_r
            Lt.data = np.exp(Lt.data)

            del logG_r
            del digaG_s

            Lt = Lt.todense()

            ## Update user related parameters 
            G_s = a + np.multiply(Lt, ((X / (Lt * Lb.T + eps)) * Lb))
            G_r = np.repeat(np.sum(L_s / L_r, 0), n, axis=0) + a

            G_s = sp.csc_matrix(G_s)
            G_r = sp.csc_matrix(G_r)

        Tk = np.repeat(np.sum(G_s / G_r, 0), self.batch_size, axis=0)
        Zik = np.multiply(Lb, ((X.T / (Lb * Lt.T + eps)) * Lt))
        # End of learning

        res = {'Z': G_s / G_r, 'G_s': G_s, 'G_r': G_r, 'W': L_s / L_r, 'Lt': Lt, 'Lb': Lb,
               'Zik': np.array(Zik, dtype='float32'), 'Tk': np.array(Tk, dtype='float32')}

        return res