Пример #1
0
    def to_sparse(self) -> _csr_matrix:
        r"""Returns the sparse matrix representation of the operator. Note that,
        in general, the size of the matrix is exponential in the number of quantum
        numbers, and this operation should thus only be performed for
        low-dimensional Hilbert spaces or sufficiently sparse operators.

        This method requires an indexable Hilbert space.

        Returns:
            The sparse matrix representation of the operator.
        """
        concrete_op = self.collect()
        hilb = self.hilbert

        x = hilb.all_states()

        sections = np.empty(x.shape[0], dtype=np.int32)
        x_prime, mels = concrete_op.get_conn_flattened(x, sections)

        numbers = hilb.states_to_numbers(x_prime)

        sections1 = np.empty(sections.size + 1, dtype=np.int32)
        sections1[1:] = sections
        sections1[0] = 0

        ## eliminate duplicates from numbers
        # rows_indices = compute_row_indices(hilb.states_to_numbers(x), sections1)

        return _csr_matrix(
            (mels, numbers, sections1),
            shape=(self.hilbert.n_states, self.hilbert.n_states),
        )
Пример #2
0
    def to_sparse(self):
        r"""Returns the sparse matrix representation of the operator. Note that,
            in general, the size of the matrix is exponential in the number of quantum
            numbers, and this operation should thus only be performed for
            low-dimensional Hilbert spaces or sufficiently sparse operators.

            This method requires an indexable Hilbert space.

            Returns:
                scipy.sparse.csr_matrix: The sparse matrix representation of the operator.
        """
        hilb = self.hilbert

        x = hilb.all_states()

        sections = _np.empty(x.shape[0], dtype=_np.int32)
        x_prime, mels = self.get_conn_flattened(x, sections)

        numbers = hilb.states_to_numbers(x_prime)

        sections1 = _np.empty(sections.size + 1, dtype=_np.int32)
        sections1[1:] = sections
        sections1[0] = 0

        return _csr_matrix((mels, numbers, sections1))
Пример #3
0
def _hadamard_mat(n: int, k: int, sparse: bool = False):
    if n is None:
        raise ValueError("Wire count cannot be `None`")
    H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
    acc = sp._csr_matrix([[1]])
    for j in range(n):
        acc = sp.kron(acc, H if j == k else sp.eye(2), format="csr")
    return acc if sparse else acc.toarray()
Пример #4
0
def _phase_mat(n: int, k: int, theta: float, sparse: bool = False):
    if n is None:
        raise ValueError("Wire count cannot be `None`")
    P = np.array([[1, 0], [0, np.exp(1j * theta)]])
    acc = sp._csr_matrix([[1]])
    for j in range(n):
        acc = sp.kron(acc, P if j == k else sp.eye(2), format="csr")
    return acc if sparse else acc.toarray()
Пример #5
0
def _cnot_mat(n: int, k1: int, k2: int, sparse: bool = False):
    assert k1 != k2
    if n is None:
        raise ValueError("Wire count cannot be `None`")
    X = sp._csr_matrix((2**n, 2**n), dtype=complex) if sparse \
            else np.zeros((2**n, 2**n), dtype=complex)
    for k in range(2**n):
        B = int_to_bitlist(k, n)
        B[k2] = (B[k1] + B[k2]) % 2
        b = bitlist_to_int(B)
        X[b, k] = 1
    return X
Пример #6
0
def _sdf_to_csr(sdf, dtype=_np.float64):
    cols, rows, datas = [], [], []
    for col, name in enumerate(sdf):
        s = sdf[name]
        row = s.sp_index.to_int_index().indices
        cols.append(_np.repeat(col, len(row)))
        rows.append(row)
        datas.append(s.sp_values.astype(dtype, copy=False))

    cols = _np.concatenate(cols)
    rows = _np.concatenate(rows)
    datas = _np.concatenate(datas)
    return _csr_matrix((datas, (rows, cols)), shape=sdf.shape)
Пример #7
0
def _xymodN_mat(n: int, k: int, q: int, x: int, N: int, sparse: bool = False):
    assert 2**q >= N
    assert k + q - 1 < n
    X = sp._csr_matrix((2**n, 2**n), dtype=complex) if sparse \
            else np.zeros((2**n, 2**n), dtype=complex)
    for i in range(2**n):
        I = i2b(i, n)
        j = b2i(I[k:k + q])
        if j < N:
            J = (j * x) % N
        else:
            J = j
        X[b2i(I[:k] + i2b(J, q) + I[k + q:]), i] = 1.0 + 0.0j
    return X
Пример #8
0
def _multiple_regression_with_penalty(dep_var,
                                      ind_vars,
                                      data,
                                      weights=None,
                                      penalty=0.0,
                                      constant=False,
                                      use_sparse=True,
                                      solver='auto'):

    DS_FLAG = False
    if isinstance(data, _Table):
        DS_FLAG = True
        data = data.to_df()
    if isinstance(ind_vars, tuple):
        ind_vars = list(ind_vars)
    if not isinstance(ind_vars, list):
        ind_vars = [ind_vars]

    X = data[ind_vars].values
    y = data[dep_var].values

    if weights is not None:
        w = data[weights].values.astype(float)
        w /= w.sum()

        X, y, w = X[w > 0], y[w > 0], w[w > 0]
    else:
        w = None

        mask = ~_np.isnan(y)
        X = X[mask, :]
        y = y[mask]

    if _np.min(w) == 0.:
        raise ValueError("weight is 0")

    if use_sparse:
        X = _csr_matrix(X)

    model = _linear_model.Ridge(alpha=penalty,
                                fit_intercept=constant,
                                copy_X=False,
                                solver=solver)
    model.fit(X, y, sample_weight=w)

    coefs = _pd.Series({var: coef for var, coef in zip(ind_vars, model.coef_)})
    coefs['Intercept'] = model.intercept_
    if DS_FLAG:
        coefs = coefs.to_dict()
    return coefs
Пример #9
0
def _cxymodN_mat(n: int,
                 k1: int,
                 k2: int,
                 q: int,
                 x: int,
                 N: int,
                 sparse: bool = False):
    assert 2**q >= N
    assert k2 + q - 1 < n
    assert k1 < k2 or k1 >= k2 + q
    X = sp._csr_matrix((2**n, 2**n), dtype=complex) if sparse \
            else np.zeros((2**n, 2**n), dtype=complex)
    for i in range(2**n):
        I = i2b(i, n)
        j = b2i(I[k2:k2 + q])
        if j < N and I[k1] == "1":
            J = (j * x) % N
        else:
            J = j
        X[b2i(I[:k2] + i2b(J, q) + I[k2 + q:]), i] = 1.0 + 0.0j
    return X
Пример #10
0
def _multiple_regression_with_penalty(dep_var,
                                      ind_vars,
                                      data,
                                      weights=None,
                                      penalty=0.,
                                      constant=False,
                                      use_sparse=True):

    DS_FLAG = False
    if isinstance(data, _ds.Table):
        DS_FLAG = True
        data = data.to_df()
    if not isinstance(ind_vars, list):
        ind_vars = [ind_vars]

    if use_sparse:
        data = data.to_sparse(fill_value=0)

    X = data[ind_vars].values
    y = data[dep_var].to_dense().values
    m, n = X.shape

    if weights is not None:
        w = data[weights].to_dense().values.astype(float)

    if use_sparse:
        X = _csr_matrix(X)

    model = _linear_model.Ridge(alpha=penalty,
                                fit_intercept=constant,
                                copy_X=False)
    model.fit(X, y, sample_weight=w)

    coefs = _pd.Series({var: coef for var, coef in zip(ind_vars, model.coef_)})
    if DS_FLAG:
        coefs = coefs.to_dict()
    return coefs