Python numpy.block() Examples

The following are 30 code examples of numpy.block(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: _classes.py    From harold with MIT License 6 votes vote down vote up
def concatenate_state_matrices(G):
    """
    Takes a State() model as input and returns the A, B, C, D matrices
    combined into a full matrix. For static gain models, the feedthrough
    matrix D is returned.

    Parameters
    ----------
    G : State

    Returns
    -------
    M : ndarray
    """
    if not isinstance(G, State):
        raise ValueError('concatenate_state_matrices() works on state '
                         'representations, but I found \"{0}\" object '
                         'instead.'.format(type(G).__name__))
    if G._isgain:
        return G.d

    return np.block([[G.a, G.b], [G.c, G.d]]) 
Example #2
Source File: photonics.py    From nevergrad with MIT License 6 votes vote down vote up
def creneau(k0: float, a0: float, pol: float, e1: float, e2: float, a: float, n: int, x0: float) -> tp.Tuple[np.ndarray, np.ndarray]:
    nmod = int(n / 2)
    alpha = np.diag(a0 + 2 * np.pi * np.arange(-nmod, nmod + 1))
    if pol == 0:
        M = alpha * alpha - k0 * k0 * marche(e1, e2, a, n, x0)
        L, E = np.linalg.eig(M)
        L = np.sqrt(-L + 0j)
        L = (1 - 2 * (np.imag(L) < -1e-15)) * L
        P = np.block([[E], [np.matmul(E, np.diag(L))]])
    else:
        U = marche(1 / e1, 1 / e2, a, n, x0)
        T = np.linalg.inv(U)
        M = (
            np.matmul(
                np.matmul(np.matmul(T, alpha), np.linalg.inv(marche(e1, e2, a, n, x0))),
                alpha,
            )
            - k0 * k0 * T
        )
        L, E = np.linalg.eig(M)
        L = np.sqrt(-L + 0j)
        L = (1 - 2 * (np.imag(L) < -1e-15)) * L
        P = np.block([[E], [np.matmul(np.matmul(U, E), np.diag(L))]])
    return P, L 
Example #3
Source File: photonics.py    From nevergrad with MIT License 6 votes vote down vote up
def cascade(T: np.ndarray, U: np.ndarray) -> np.ndarray:
    n = int(T.shape[1] / 2)
    J = np.linalg.inv(np.eye(n) - np.matmul(U[0:n, 0:n], T[n : 2 * n, n : 2 * n]))
    K = np.linalg.inv(np.eye(n) - np.matmul(T[n : 2 * n, n : 2 * n], U[0:n, 0:n]))
    S = np.block(
        [
            [
                T[0:n, 0:n]
                + np.matmul(
                    np.matmul(np.matmul(T[0:n, n : 2 * n], J), U[0:n, 0:n]),
                    T[n : 2 * n, 0:n],
                ),
                np.matmul(np.matmul(T[0:n, n : 2 * n], J), U[0:n, n : 2 * n]),
            ],
            [
                np.matmul(np.matmul(U[n : 2 * n, 0:n], K), T[n : 2 * n, 0:n]),
                U[n : 2 * n, n : 2 * n]
                + np.matmul(
                    np.matmul(np.matmul(U[n : 2 * n, 0:n], K), T[n : 2 * n, n : 2 * n]),
                    U[0:n, n : 2 * n],
                ),
            ],
        ]
    )
    return S  # type: ignore 
Example #4
Source File: test_shape_base.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_block_complicated(self):
        # a bit more complicated
        one_2d = np.array([[1, 1, 1]])
        two_2d = np.array([[2, 2, 2]])
        three_2d = np.array([[3, 3, 3, 3, 3, 3]])
        four_1d = np.array([4, 4, 4, 4, 4, 4])
        five_0d = np.array(5)
        six_1d = np.array([6, 6, 6, 6, 6])
        zero_2d = np.zeros((2, 6))

        expected = np.array([[1, 1, 1, 2, 2, 2],
                             [3, 3, 3, 3, 3, 3],
                             [4, 4, 4, 4, 4, 4],
                             [5, 6, 6, 6, 6, 6],
                             [0, 0, 0, 0, 0, 0],
                             [0, 0, 0, 0, 0, 0]])

        result = block([[one_2d, two_2d],
                        [three_2d],
                        [four_1d],
                        [five_0d, six_1d],
                        [zero_2d]])
        assert_equal(result, expected) 
Example #5
Source File: common_slow.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def eri_mknj(self, item, *args):
        """
        Retrieves ERI block using 'mknj' notation.
        Args:
            item (str): a 4-character string of 'mknj' letters;
            *args: other arguments passed to `get_block_ov_notation`;

        Returns:
            The corresponding block of ERI (matrix with paired dimensions).
        """
        if len(item) != 4 or not isinstance(item, str) or set(item) != set('mknj'):
            raise ValueError("Unknown item: {}".format(repr(item)))

        item = mknj2i(item)
        n_ov = ''.join('o' if i % 2 == 0 else 'v' for i in item)
        args = tuple(
            tuple(arg[i] for i in item)
            for arg in args
        )
        result = self.eri_ov(n_ov, *args).transpose(*numpy.argsort(item))
        i, j, k, l = result.shape
        result = result.reshape((i * j, k * l))
        return result 
Example #6
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def test_block_complicated(self):
        # a bit more complicated
        one_2d = np.array([[1, 1, 1]])
        two_2d = np.array([[2, 2, 2]])
        three_2d = np.array([[3, 3, 3, 3, 3, 3]])
        four_1d = np.array([4, 4, 4, 4, 4, 4])
        five_0d = np.array(5)
        six_1d = np.array([6, 6, 6, 6, 6])
        zero_2d = np.zeros((2, 6))

        expected = np.array([[1, 1, 1, 2, 2, 2],
                             [3, 3, 3, 3, 3, 3],
                             [4, 4, 4, 4, 4, 4],
                             [5, 6, 6, 6, 6, 6],
                             [0, 0, 0, 0, 0, 0],
                             [0, 0, 0, 0, 0, 0]])

        result = block([[one_2d, two_2d],
                        [three_2d],
                        [four_1d],
                        [five_0d, six_1d],
                        [zero_2d]])
        assert_equal(result, expected) 
Example #7
Source File: krhf_slow_supercell.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def eri_mknj(self, item, pairs_row=None, pairs_column=None):
        """
        Retrieves the merged ERI block using 'mknj' notation with all k-indexes.
        Args:
            item (str): a 4-character string of 'mknj' letters;
            pairs_row (Iterable): iterator for pairs of row k-points (first index in the output matrix);
            pairs_column (Iterable): iterator for pairs of column k-points (second index in the output matrix);

        Returns:
            The corresponding block of ERI (phys notation).
        """
        if pairs_row is None:
            pairs_row = product(range(len(self.model.kpts)), range(len(self.model.kpts)))
        if pairs_column is None:
            pairs_column = product(range(len(self.model.kpts)), range(len(self.model.kpts)))
        # Second index has to support re-iterations
        pairs_column = tuple(pairs_column)
        result = []
        for k1, k2 in pairs_row:
            result.append([])
            for k3, k4 in pairs_column:
                result[-1].append(self.eri_mknj_k(item, (k1, k2, k3, k4)))

        r = numpy.block(result)
        return r / len(self.model.kpts) 
Example #8
Source File: test_shape_base.py    From pySINDy with MIT License 6 votes vote down vote up
def test_block_complicated(self):
        # a bit more complicated
        one_2d = np.array([[1, 1, 1]])
        two_2d = np.array([[2, 2, 2]])
        three_2d = np.array([[3, 3, 3, 3, 3, 3]])
        four_1d = np.array([4, 4, 4, 4, 4, 4])
        five_0d = np.array(5)
        six_1d = np.array([6, 6, 6, 6, 6])
        zero_2d = np.zeros((2, 6))

        expected = np.array([[1, 1, 1, 2, 2, 2],
                             [3, 3, 3, 3, 3, 3],
                             [4, 4, 4, 4, 4, 4],
                             [5, 6, 6, 6, 6, 6],
                             [0, 0, 0, 0, 0, 0],
                             [0, 0, 0, 0, 0, 0]])

        result = block([[one_2d, two_2d],
                        [three_2d],
                        [four_1d],
                        [five_0d, six_1d],
                        [zero_2d]])
        assert_equal(result, expected) 
Example #9
Source File: krhf_slow.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def tdhf_primary_form(self, k):
        """
        A primary form of TDHF matrixes (full).
        Args:
            k (tuple, int): momentum transfer: either a pair of k-point indexes specifying the momentum transfer
            vector or a single integer with the second index assuming the first index being zero;

        Returns:
            Output type: "full", and the corresponding matrix.
        """
        r1, r2, c1, c2 = get_block_k_ix(self, k)
        d1 = self.tdhf_diag(r1)
        d2 = self.tdhf_diag(r2)
        a = d1 + 2 * self["knmj", r1, c1] - self["knjm", r1, c1]
        b = 2 * self["kjmn", r1, c2] - self["kjnm", r1, c2]
        a_ = d2 + 2 * self["mjkn", r2, c2] - self["mjnk", r2, c2]
        b_ = 2 * self["mnkj", r2, c1] - self["mnjk", r2, c1]
        return "full", numpy.block([[a, b], [-b_, -a_]]) 
Example #10
Source File: krhf_slow.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def eri_mknj(self, item, pair_row, pair_column):
        """
        Retrieves the merged ERI block using 'mknj' notation with pairs of k-indexes (k1, k1, k2, k2).
        Args:
            item (str): a 4-character string of 'mknj' letters;
            pair_row (Iterable): a k-point pair `k2 = pair_row[k1]` for each k1 (row indexes in the final matrix);
            pair_column (Iterable): a k-point pair `k4 = pair_row[k3]` for each k3 (column indexes in the final matrix);

        Returns:
            The corresponding block of ERI (phys notation).
        """
        return super(PhysERI, self).eri_mknj(
            item,
            pairs_row=enumerate(pair_row),
            pairs_column=enumerate(pair_column),
        ) 
Example #11
Source File: krhf_slow.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def get_k_ix(self, item, like):
        """
        Retrieves block indexes: row and column.
        Args:
            item (str): a string of 'mknj' letters;
            like (tuple): a 2-tuple with sample pair of k-points;

        Returns:
            Row and column indexes of a sub-block with conserving momentum.
        """
        item_i = numpy.argsort(mknj2i(item))
        item_code = ''.join("++--"[i] for i in item_i)
        if item_code[0] == item_code[1]:
            kc = self.kconserv  # ++-- --++
        elif item_code[0] == item_code[2]:
            kc = self.kconserv.swapaxes(1, 2)  # +-+- -+-+
        elif item_code[1] == item_code[2]:
            kc = self.kconserv.transpose(2, 0, 1)  # +--+ -++-
        else:
            raise RuntimeError("Unknown case: {}".format(item_code))

        y = kc[like]
        x = kc[0, y[0]]

        return x, y 
Example #12
Source File: test_shape_base.py    From pySINDy with MIT License 5 votes vote down vote up
def test_block_with_1d_arrays_multiple_rows(self):
        a = np.array([1, 2, 3])
        b = np.array([2, 3, 4])
        expected = np.array([[1, 2, 3, 2, 3, 4],
                             [1, 2, 3, 2, 3, 4]])
        result = block([[a, b], [a, b]])
        assert_equal(expected, result) 
Example #13
Source File: test_shape_base.py    From pySINDy with MIT License 5 votes vote down vote up
def test_nested(self):
        one = np.array([1, 1, 1])
        two = np.array([[2, 2, 2], [2, 2, 2], [2, 2, 2]])
        three = np.array([3, 3, 3])
        four = np.array([4, 4, 4])
        five = np.array(5)
        six = np.array([6, 6, 6, 6, 6])
        zero = np.zeros((2, 6))

        result = np.block([
            [
                np.block([
                   [one],
                   [three],
                   [four]
                ]),
                two
            ],
            [five, six],
            [zero]
        ])
        expected = np.array([[1, 1, 1, 2, 2, 2],
                             [3, 3, 3, 2, 2, 2],
                             [4, 4, 4, 2, 2, 2],
                             [5, 6, 6, 6, 6, 6],
                             [0, 0, 0, 0, 0, 0],
                             [0, 0, 0, 0, 0, 0]])

        assert_equal(result, expected) 
Example #14
Source File: kernels.py    From CatLearn with GNU General Public License v3.0 5 votes vote down vote up
def gaussian_xxp_gradients(m1, m2, kwidth, k):
    """Gradient for k(x, x').

    Parameters
    ----------
    m1 : array
        Feature matrix.
    m2 : array
        Feature matrix typically associated with the test data.
    kwidth : list
        List of lengthscales for the gaussian kernel.
    k : array
        Upper left portion of the overall covariance matrix.
    """
    size_m1 = np.shape(m1)
    size_m2 = np.shape(m2)
    kgd_tilde = np.zeros((size_m1[0], size_m2[0] * size_m2[1]))
    invsqkwidth = kwidth**(-2)
    for i in range(size_m1[0]):
        kgd_tilde_i = -((invsqkwidth * (m2[:, :] - m1[i, :]) *
                         k[i, :].reshape(size_m2[0], 1)).reshape(
                             1, size_m2[0] * size_m2[1])
                        )
        kgd_tilde[i, :] = kgd_tilde_i

    return np.block([k, kgd_tilde]) 
Example #15
Source File: kernels.py    From CatLearn with GNU General Public License v3.0 5 votes vote down vote up
def gaussian_xx_gradients(m1, kwidth, k):
    """Gradient for k(x, x).

    Parameters
    ----------
    m1 : array
        Feature matrix.
    kwidth : list
        List of lengthscales for the gaussian kernel.
    k : array
        Upper left portion of the overall covariance matrix.
    """
    size = np.shape(m1)
    big_kgd = np.zeros((size[0], size[0] * size[1]))
    big_kdd = np.zeros((size[0] * size[1], size[0] * size[1]))
    invsqkwidth = kwidth**(-2)
    I_m = np.identity(size[1]) * invsqkwidth
    for i in range(size[0]):
        ldist = (invsqkwidth * (m1[:, :] - m1[i, :]))
        big_kgd_i = ((ldist).T * k[i]).T
        big_kgd[:, (size[1] * i):(size[1] + size[1] * i)] = big_kgd_i
        if size[1] <= 30:  # Broadcasting requires large memory.
            k_dd = ((I_m - (ldist[:, None, :] * ldist[:, :, None])) *
                    (k[i, None, None].T)).reshape(-1, size[1])
            big_kdd[:, size[1] * i:size[1] + size[1] * i] = k_dd
        elif size[1] > 30:  # Loop when large number of features.
            for j in range(i, size[0]):
                k_dd = (I_m - np.outer(ldist[j], ldist[j].T)) * k[i, j]
                big_kdd[i * size[1]:(i + 1) * size[1],
                        j * size[1]:(j + 1) * size[1]] = k_dd
                if j != i:
                    big_kdd[j * size[1]:(j + 1) * size[1],
                            i * size[1]:(i + 1) * size[1]] = k_dd.T

    return np.block([[k, big_kgd], [np.transpose(big_kgd), big_kdd]]) 
Example #16
Source File: test_shape_base.py    From pySINDy with MIT License 5 votes vote down vote up
def test_block_with_1d_arrays_column_wise(self):
        # # # 1-D vectors are treated as row arrays
        a_1d = np.array([1, 2, 3])
        b_1d = np.array([2, 3, 4])
        expected = np.array([[1, 2, 3],
                             [2, 3, 4]])
        result = block([[a_1d], [b_1d]])
        assert_equal(expected, result) 
Example #17
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_different_ndims_depths(self):
        a = 1.
        b = 2 * np.ones((1, 2))
        c = 3 * np.ones((1, 2, 3))

        result = np.block([[a, b], [c]])
        expected = np.array([[[1., 2., 2.],
                              [3., 3., 3.],
                              [3., 3., 3.]]])

        assert_equal(result, expected) 
Example #18
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_different_ndims(self):
        a = 1.
        b = 2 * np.ones((1, 2))
        c = 3 * np.ones((1, 1, 3))

        result = np.block([a, b, c])
        expected = np.array([[[1., 2., 2., 3., 3., 3.]]])

        assert_equal(result, expected) 
Example #19
Source File: clifford.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def destabilizer(self):
        """Return the destabilizer block of the StabilizerTable."""
        return StabilizerTable(self._table[0:self.num_qubits]) 
Example #20
Source File: test_shape_base.py    From pySINDy with MIT License 5 votes vote down vote up
def test_block_with_mismatched_shape(self):
        a = np.array([0, 0])
        b = np.eye(2)
        assert_raises(ValueError, np.block, [a, b])
        assert_raises(ValueError, np.block, [b, a]) 
Example #21
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_tuple(self):
        assert_raises_regex(TypeError, 'tuple', np.block, ([1, 2], [3, 4]))
        assert_raises_regex(TypeError, 'tuple', np.block, [(1, 2), (3, 4)]) 
Example #22
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_empty_lists(self):
        assert_raises_regex(ValueError, 'empty', np.block, [])
        assert_raises_regex(ValueError, 'empty', np.block, [[]])
        assert_raises_regex(ValueError, 'empty', np.block, [[1], []]) 
Example #23
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_no_lists(self):
        assert_equal(np.block(1),         np.array(1))
        assert_equal(np.block(np.eye(3)), np.eye(3)) 
Example #24
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_block_with_mismatched_shape(self):
        a = np.array([0, 0])
        b = np.eye(2)
        assert_raises(ValueError, np.block, [a, b])
        assert_raises(ValueError, np.block, [b, a]) 
Example #25
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_nested(self):
        one = np.array([1, 1, 1])
        two = np.array([[2, 2, 2], [2, 2, 2], [2, 2, 2]])
        three = np.array([3, 3, 3])
        four = np.array([4, 4, 4])
        five = np.array(5)
        six = np.array([6, 6, 6, 6, 6])
        zero = np.zeros((2, 6))

        result = np.block([
            [
                np.block([
                   [one],
                   [three],
                   [four]
                ]),
                two
            ],
            [five, six],
            [zero]
        ])
        expected = np.array([[1, 1, 1, 2, 2, 2],
                             [3, 3, 3, 2, 2, 2],
                             [4, 4, 4, 2, 2, 2],
                             [5, 6, 6, 6, 6, 6],
                             [0, 0, 0, 0, 0, 0],
                             [0, 0, 0, 0, 0, 0]])

        assert_equal(result, expected) 
Example #26
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_block_with_1d_arrays_column_wise(self):
        # # # 1-D vectors are treated as row arrays
        a_1d = np.array([1, 2, 3])
        b_1d = np.array([2, 3, 4])
        expected = np.array([[1, 2, 3],
                             [2, 3, 4]])
        result = block([[a_1d], [b_1d]])
        assert_equal(expected, result) 
Example #27
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_block_with_1d_arrays_multiple_rows(self):
        a = np.array([1, 2, 3])
        b = np.array([2, 3, 4])
        expected = np.array([[1, 2, 3, 2, 3, 4],
                             [1, 2, 3, 2, 3, 4]])
        result = block([[a, b], [a, b]])
        assert_equal(expected, result) 
Example #28
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_block_with_1d_arrays_row_wise(self):
        # # # 1-D vectors are treated as row arrays
        a = np.array([1, 2, 3])
        b = np.array([2, 3, 4])
        expected = np.array([1, 2, 3, 2, 3, 4])
        result = block([a, b])
        assert_equal(expected, result) 
Example #29
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_block_simple_column_wise(self):
        a_2d = np.ones((2, 2))
        b_2d = 2 * a_2d
        expected = np.array([[1, 1],
                             [1, 1],
                             [2, 2],
                             [2, 2]])
        result = block([[a_2d], [b_2d]])
        assert_equal(expected, result) 
Example #30
Source File: test_shape_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_block_simple_row_wise(self):
        a_2d = np.ones((2, 2))
        b_2d = 2 * a_2d
        desired = np.array([[1, 1, 2, 2],
                            [1, 1, 2, 2]])
        result = block([a_2d, b_2d])
        assert_equal(desired, result)