示例#1
0
    def test_multiply(self):

        # test scalar multiplication
        m = self.basic_m * 5.0
        dense_m = m.todense()

        b00 = self.block00.tocoo()
        b11 = self.block11.tocoo()
        b10 = self.block10
        scipy_m = bmat([[b00, b10.transpose()], [b10, b11]], format='coo')
        dense_scipy_m = scipy_m.todense() * 5.0

        self.assertTrue(np.allclose(dense_scipy_m, dense_m, atol=1e-3))

        m = 5.0 * self.basic_m
        dense_m = m.todense()

        self.assertTrue(np.allclose(dense_scipy_m, dense_m, atol=1e-3))

        # test matrix vector product
        m = self.basic_m
        x = BlockVector(m.bshape[1])
        for i in range(m.bshape[1]):
            x[i] = np.ones(m.col_block_sizes()[i], dtype=np.float64)
        dinopy_res = m * x
        scipy_res = scipy_m * x.flatten()

        self.assertListEqual(dinopy_res.tolist(), scipy_res.tolist())
        dinopy_res = m * x.flatten()
        scipy_res = scipy_m * x.flatten()

        self.assertListEqual(dinopy_res.tolist(), scipy_res.tolist())

        self.basic_m *= 5.0
        self.assertTrue(np.allclose(self.basic_m.todense(), dense_m, atol=1e-3))
示例#2
0
文件: utils.py 项目: CanLi1/pyomo
def compute_init_lam(nlp, x=None, lam_max=1e3):

    if x is None:
        x = nlp.x_init
    else:
        assert x.size == nlp.nx

    assert nlp.nd == 0, "only supported for equality constrained nlps for now"

    nx = nlp.nx
    nc = nlp.nc

    # create Jacobian
    jac_c = nlp.jacobian_g(x)

    # create gradient of objective
    df = nlp.grad_objective(x)

    # create KKT system
    kkt = BlockSymMatrix(2)
    kkt[0, 0] = identity(nx)
    kkt[1, 0] = jac_c

    zeros = np.zeros(nc)
    rhs = BlockVector([-df, zeros])

    flat_kkt = kkt.tocoo().tocsc()
    flat_rhs = rhs.flatten()

    sol = spsolve(flat_kkt, flat_rhs)
    return sol[nlp.nx:nlp.nx + nlp.ng]
示例#3
0
    def test__isub__(self):
        v = BlockVector(2)
        a = np.ones(5)
        b = np.zeros(9)
        v[0] = a
        v[1] = b
        v -= 5.0

        self.assertTrue(np.allclose(v[0], a - 5.0))
        self.assertTrue(np.allclose(v[1], b - 5.0))

        v = BlockVector(2)
        a = np.ones(5)
        b = np.zeros(9)
        v[0] = a
        v[1] = b

        v2 = BlockVector(2)
        v2[0] = np.ones(5)
        v2[1] = np.ones(9)

        v -= v2
        self.assertTrue(np.allclose(v[0], a - 1))
        self.assertTrue(np.allclose(v[1], b - 1))

        self.assertTrue(np.allclose(v2[0], np.ones(5)))
        self.assertTrue(np.allclose(v2[1], np.ones(9)))
示例#4
0
    def test__imul__(self):
        v = BlockVector(2)
        a = np.ones(5)
        b = np.arange(9)
        v[0] = a
        v[1] = b
        v *= 2.0

        self.assertTrue(np.allclose(v[0], a * 2.0))
        self.assertTrue(np.allclose(v[1], b * 2.0))

        v = BlockVector(2)
        a = np.ones(5)
        b = np.zeros(9)
        v[0] = a
        v[1] = b

        v2 = BlockVector(2)
        v2[0] = np.ones(5)*2
        v2[1] = np.ones(9)*2

        v *= v2
        self.assertTrue(np.allclose(v[0], a * 2))
        self.assertTrue(np.allclose(v[1], b * 2))

        self.assertTrue(np.allclose(v2[0], np.ones(5)*2))
        self.assertTrue(np.allclose(v2[1], np.ones(9)*2))
示例#5
0
    def test__iadd__(self):

        v = BlockVector(2)
        a = np.ones(5)
        b = np.zeros(9)
        v[0] = a
        v[1] = b
        v += 1.0

        self.assertTrue(np.allclose(v[0], a+1))
        self.assertTrue(np.allclose(v[1], b + 1))

        v = BlockVector(2)
        a = np.ones(5)
        b = np.zeros(9)
        v[0] = a
        v[1] = b

        v2 = BlockVector(2)
        v2[0] = np.ones(5)
        v2[1] = np.ones(9)

        v += v2
        self.assertTrue(np.allclose(v[0], a + 1))
        self.assertTrue(np.allclose(v[1], b + 1))

        self.assertTrue(np.allclose(v2[0], np.ones(5)))
        self.assertTrue(np.allclose(v2[1], np.ones(9)))
示例#6
0
    def create_vector_y(self, subset=None):
        """Return ndarray of vector of constraints

        Parameters
        ----------
        subset : str, optional
            determines size of vector.
            `c`: only equality constraints
            `d`: only inequality constraints
            `dl`: only inequality constraints with lower bound
            `du`: only inequality constraints with upper bound

        Returns
        -------
        BlockVector

        """
        if subset is None:
            return BlockVector(
                [np.zeros(nlp.ng, dtype=np.double) for nlp in self._nlps] + [
                    np.zeros(self.nz, dtype=np.double)
                    for i in range(self.nblocks)
                ])
        elif subset == 'c':
            return BlockVector(
                [np.zeros(nlp.nc, dtype=np.double) for nlp in self._nlps] + [
                    np.zeros(self.nz, dtype=np.double)
                    for i in range(self.nblocks)
                ])
        elif subset == 'd':
            return BlockVector(
                [np.zeros(nlp.nd, dtype=np.double) for nlp in self._nlps])
        else:
            raise RuntimeError('Subset not recognized')
示例#7
0
 def setUp(self):
     self.v1 = np.array([1.1, 2.2, 3.3])
     self.v2 = np.array([4.4, 5.5, 6.6, 7.7])
     self.v3 = np.array([1.1, 2.2, 3.3])*2
     self.v4 = np.array([4.4, 5.5, 6.6, 7.7])*2
     self.bv = BlockVector([self.v1, self.v2])
     self.bv2 = BlockVector([self.v3, self.v4])
示例#8
0
 def test_cumsum(self):
     v = BlockVector(3)
     v[0] = np.arange(1, 5)
     v[1] = np.arange(5, 10)
     v[2] = np.arange(10, 15)
     c = np.arange(1, 15)
     self.assertListEqual(v.cumsum().tolist(), c.cumsum().tolist())
示例#9
0
    def test_get_block_vector_for_dot_product_5(self):
        rank = comm.Get_rank()

        rank_ownership = np.array([[1, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]])
        m = MPIBlockMatrix(4, 3, rank_ownership, comm)
        sub_m = np.array([[1, 0], [0, 1]])
        sub_m = coo_matrix(sub_m)
        if rank == 0:
            m.set_block(3, rank, sub_m.copy())
        elif rank == 1:
            m.set_block(0, 0, sub_m.copy())
            m.set_block(rank, rank, sub_m.copy())
            m.set_block(3, rank, sub_m.copy())
        else:
            m.set_block(rank, rank, sub_m.copy())
            m.set_block(3, rank, sub_m.copy())

        v = BlockVector(3)
        sub_v = np.ones(2)
        for ndx in range(3):
            v.set_block(ndx, sub_v.copy())

        res = m._get_block_vector_for_dot_product(v)

        self.assertIs(res, v)

        v_flat = v.flatten()
        res = m._get_block_vector_for_dot_product(v_flat)
        self.assertIsInstance(res, BlockVector)
        for ndx in range(3):
            block = res.get_block(ndx)
            self.assertTrue(np.array_equal(block, sub_v))
示例#10
0
    def test_multiply(self):

        # test scalar multiplication
        m = self.basic_m * 5.0
        dense_m = m.todense()

        b00 = self.block00.tofullcoo()
        b11 = self.block11.tofullcoo()
        b10 = self.block10
        scipy_m = bmat([[b00, b10.transpose()], [b10, b11]], format='coo')
        dense_scipy_m = scipy_m.todense() * 5.0

        self.assertTrue(np.allclose(dense_scipy_m, dense_m, atol=1e-3))

        m = 5.0 * self.basic_m
        dense_m = m.todense()

        self.assertTrue(np.allclose(dense_scipy_m, dense_m, atol=1e-3))

        # test matrix vector product
        m = self.basic_m
        x = BlockVector(m.bshape[1])
        for i in range(m.bshape[1]):
            x[i] = np.ones(m.col_block_sizes()[i], dtype=np.float64)
        dinopy_res = m * x
        scipy_res = scipy_m * x.flatten()

        self.assertListEqual(dinopy_res.tolist(), scipy_res.tolist())

        dinopy_res = m * x.flatten()
        scipy_res = scipy_m * x.flatten()

        self.assertListEqual(dinopy_res.tolist(), scipy_res.tolist())
示例#11
0
def compute_init_lam(nlp, x=None, lam_max=1e3):
    if x is None:
        x = nlp.init_primals()
    else:
        assert x.size == nlp.n_primals()
    nlp.set_primals(x)

    assert nlp.n_ineq_constraints(
    ) == 0, "only supported for equality constrained nlps for now"

    nx = nlp.n_primals()
    nc = nlp.n_constraints()

    # create Jacobian
    jac = nlp.evaluate_jacobian()

    # create gradient of objective
    df = nlp.evaluate_grad_objective()

    # create KKT system
    kkt = BlockSymMatrix(2)
    kkt[0, 0] = identity(nx)
    kkt[1, 0] = jac

    zeros = np.zeros(nc)
    rhs = BlockVector([-df, zeros])

    flat_kkt = kkt.tocoo().tocsc()
    flat_rhs = rhs.flatten()

    sol = spsolve(flat_kkt, flat_rhs)
    return sol[nlp.n_primals():nlp.n_primals() + nlp.n_constraints()]
示例#12
0
 def set_primal_dual_kkt_solution(self, sol: BlockVector):
     for ndx, nlp in self._nlps.items():
         nlp.set_primal_dual_kkt_solution(sol.get_block(ndx).get_block(0))
         self._delta_primals.set_block(ndx, nlp.get_delta_primals())
         self._delta_slacks.set_block(ndx, nlp.get_delta_slacks())
         self._delta_duals_eq.get_block(ndx).set_block(
             0, nlp.get_delta_duals_eq())
         self._delta_duals_ineq.set_block(ndx, nlp.get_delta_duals_ineq())
         self._delta_duals_primals_lb.set_block(
             ndx, nlp.get_delta_duals_primals_lb())
         self._delta_duals_primals_ub.set_block(
             ndx, nlp.get_delta_duals_primals_ub())
         self._delta_duals_slacks_lb.set_block(
             ndx, nlp.get_delta_duals_slacks_lb())
         self._delta_duals_slacks_ub.set_block(
             ndx, nlp.get_delta_duals_slacks_ub())
         self._delta_duals_eq.get_block(ndx).set_block(
             1,
             sol.get_block(ndx).get_block(1))
         self._delta_duals_eq.get_block(ndx).set_block(
             2,
             sol.get_block(
                 self._num_time_blocks).get_block(0).get_block(ndx))
     self._delta_primals.set_block(
         self._num_time_blocks,
         sol.get_block(self._num_time_blocks).get_block(1))
示例#13
0
 def test_tolist(self):
     v = BlockVector(2)
     a = np.arange(5)
     b = np.arange(9)
     c = np.concatenate([a, b])
     v[0] = a
     v[1] = b
     self.assertListEqual(v.tolist(), c.tolist())
示例#14
0
 def test_fill(self):
     v = BlockVector(2)
     a = np.arange(5)
     b = np.arange(9)
     v[0] = a
     v[1] = b
     v.fill(1.0)
     c = np.ones(v.size)
     self.assertListEqual(v.tolist(), c.tolist())
示例#15
0
 def test_min(self):
     self.assertEqual(self.ones.min(), 1)
     v = BlockVector(2)
     a = np.arange(5)
     b = np.arange(9)
     c = np.concatenate([a, b])
     v[0] = a
     v[1] = b
     self.assertEqual(v.min(), c.min())
示例#16
0
 def test_copyto(self):
     v = self.ones
     v2 = BlockVector(len(self.list_sizes_ones))
     v.copyto(v2)
     self.assertListEqual(v.tolist(), v2.tolist())
     v3 = np.zeros(v.size)
     v.copyto(v3)
     self.assertListEqual(v.tolist(), v3.tolist())
     v *= 5
     v.copyto(v2)
     self.assertListEqual(v.tolist(), v2.tolist())
示例#17
0
 def set_duals_ineq(self, duals_ineq: BlockVector):
     """
     Parameters
     ----------
     duals_ineq: BlockVector
         The values for the duals of the inequality constraints. This BlockVector has one block for
         every time block.
     """
     for ndx, nlp in self._nlps.items():
         nlp.set_duals_ineq(duals_ineq.get_block(ndx))
         self._duals_ineq.set_block(ndx, duals_ineq.get_block(ndx))
示例#18
0
    def test_multiply(self):

        # check scalar multiplication
        block = self.block_m
        m = self.basic_m * 5.0
        scipy_mat = bmat([[block, block], [None, block]], format='coo')
        mulscipy_mat = scipy_mat * 5.0
        dinopy_mat = m.tocoo()
        drow = np.sort(dinopy_mat.row)
        dcol = np.sort(dinopy_mat.col)
        ddata = np.sort(dinopy_mat.data)
        srow = np.sort(mulscipy_mat.row)
        scol = np.sort(mulscipy_mat.col)
        sdata = np.sort(mulscipy_mat.data)
        self.assertListEqual(drow.tolist(), srow.tolist())
        self.assertListEqual(dcol.tolist(), scol.tolist())
        self.assertListEqual(ddata.tolist(), sdata.tolist())

        m = 5.0 * self.basic_m
        dinopy_mat = m.tocoo()
        drow = np.sort(dinopy_mat.row)
        dcol = np.sort(dinopy_mat.col)
        ddata = np.sort(dinopy_mat.data)
        self.assertListEqual(drow.tolist(), srow.tolist())
        self.assertListEqual(dcol.tolist(), scol.tolist())
        self.assertListEqual(ddata.tolist(), sdata.tolist())

        # check dot product with block vector
        block = self.block_m
        m = self.basic_m
        scipy_mat = bmat([[block, block], [None, block]], format='coo')
        x = BlockVector(2)
        x[0] = np.ones(block.shape[1], dtype=np.float64)
        x[1] = np.ones(block.shape[1], dtype=np.float64)

        res_scipy = scipy_mat.dot(x.flatten())
        res_dinopy = m * x
        res_dinopy_flat = m * x.flatten()

        self.assertListEqual(res_dinopy.tolist(), res_scipy.tolist())
        self.assertListEqual(res_dinopy_flat.tolist(), res_scipy.tolist())

        dense_mat = dinopy_mat.todense()
        self.basic_m *= 5.0
        self.assertTrue(np.allclose(dense_mat, self.basic_m.todense()))

        flat_mat = self.basic_m.tocoo()
        result = flat_mat * flat_mat
        dense_result = result.toarray()
        mat = self.basic_m * self.basic_m.tocoo()
        dense_mat = mat.toarray()
        self.assertTrue(np.allclose(dense_mat, dense_result))
示例#19
0
    def test_multiply(self):

        # check scalar multiplication
        block = self.block_m
        m = self.basic_m * 5.0
        scipy_mat = bmat([[block, block], [None, block]], format='coo')
        mulscipy_mat = scipy_mat * 5.0
        dinopy_mat = m.tocoo()
        drow = np.sort(dinopy_mat.row)
        dcol = np.sort(dinopy_mat.col)
        ddata = np.sort(dinopy_mat.data)
        srow = np.sort(mulscipy_mat.row)
        scol = np.sort(mulscipy_mat.col)
        sdata = np.sort(mulscipy_mat.data)
        self.assertListEqual(drow.tolist(), srow.tolist())
        self.assertListEqual(dcol.tolist(), scol.tolist())
        self.assertListEqual(ddata.tolist(), sdata.tolist())

        m = 5.0 * self.basic_m
        dinopy_mat = m.tocoo()
        drow = np.sort(dinopy_mat.row)
        dcol = np.sort(dinopy_mat.col)
        ddata = np.sort(dinopy_mat.data)
        self.assertListEqual(drow.tolist(), srow.tolist())
        self.assertListEqual(dcol.tolist(), scol.tolist())
        self.assertListEqual(ddata.tolist(), sdata.tolist())

        # check dot product with block vector
        block = self.block_m
        m = self.basic_m
        scipy_mat = bmat([[block, block], [None, block]], format='coo')
        x = BlockVector(2)
        x[0] = np.ones(block.shape[1], dtype=np.float64)
        x[1] = np.ones(block.shape[1], dtype=np.float64)

        res_scipy = scipy_mat.dot(x.flatten())
        res_dinopy = m * x
        res_dinopy_flat = m * x.flatten()

        self.assertListEqual(res_dinopy.tolist(), res_scipy.tolist())
        self.assertListEqual(res_dinopy_flat.tolist(), res_scipy.tolist())

        dense_mat = dinopy_mat.todense()
        self.basic_m *= 5.0
        self.assertTrue(np.allclose(dense_mat, self.basic_m.todense()))

        flat_mat = self.basic_m.tocoo()
        result = flat_mat * flat_mat
        dense_result = result.toarray()
        mat = self.basic_m * self.basic_m.tocoo()
        dense_mat = mat.toarray()
        self.assertTrue(np.allclose(dense_mat, dense_result))
示例#20
0
    def test_create_vector_x(self):

        x_ = BlockVector(self.n_scenarios + 1)
        nz = len(self.complicated_vars_ids)
        nx_i = (self.G.shape[0] + nz)
        for i in range(self.n_scenarios):
            x_[i] = np.zeros(nx_i)
        x_[self.n_scenarios] = np.zeros(nz)
        self.assertEqual(x_.shape, self.nlp.create_vector_x().shape)
        self.assertEqual(x_.nblocks, self.nlp.create_vector_x().nblocks)
        self.assertTrue(
            np.allclose(x_.block_sizes(),
                        self.nlp.create_vector_x().block_sizes()))
        self.assertListEqual(list(x_.flatten()),
                             list(self.nlp.create_vector_x().flatten()))

        # check for subset
        for s in ['l', 'u']:
            xs = self.nlp.create_vector_x(subset=s)
            xs_ = BlockVector(self.n_scenarios + 1)
            for i in range(self.n_scenarios):
                xs_[i] = np.zeros(1)
            xs_[self.n_scenarios] = np.zeros(0)
            self.assertEqual(xs_.shape, xs.shape)
            self.assertEqual(xs_.nblocks, xs.nblocks)
            self.assertTrue(np.allclose(xs_.block_sizes(), xs.block_sizes()))
            self.assertListEqual(list(xs_.flatten()), list(xs.flatten()))
示例#21
0
 def evaluate_eq_constraints(self) -> BlockVector:
     """
     Returns
     -------
     eq_resid: BlockVector
         The residuals of the equality constraints, including the coupling constraints.
         This BlockVector has one block for every time block. Each block is itself a BlockVector with
         3 blocks. The first block contains the residuals of the equality constraints in the corresponding time
         block. The second block has the residuals for the coupling constraints linking the states at the
         beginning of the time block to the coupling variables between the time block and the previous
         time block. The third block has the residuals for the coupling constraints linking the states at the
         end of the time block to the coupling variables between the time block and the next time block.
     """
     for ndx, nlp in self._nlps.items():
         sub_block = BlockVector(3)
         sub_block.set_block(0, nlp.evaluate_eq_constraints())
         sub_block.set_block(
             1, (self._link_backward_matrices[ndx] * nlp.get_primals() -
                 (self._link_backward_coupling_matrices[ndx] *
                  self._primals.get_block(self._num_time_blocks))))
         sub_block.set_block(
             2, (self._link_forward_matrices[ndx] * nlp.get_primals() -
                 (self._link_forward_coupling_matrices[ndx] *
                  self._primals.get_block(self._num_time_blocks))))
         self._eq_resid.set_block(ndx, sub_block)
     return self._eq_resid
示例#22
0
    def set_primals(self, primals: BlockVector):
        """
        Set the values of the primal variables for evaluation (i.e., the evaluate_* methods).

        Parameters
        ----------
        primals: BlockVector
            The values for each primal variable. This BlockVector should have one block for every time block
            and one block for the coupling variables.
        """
        for ndx, nlp in self._nlps.items():
            nlp.set_primals(primals.get_block(ndx))
            self._primals.set_block(ndx, primals.get_block(ndx))
        self._primals.set_block(self._num_time_blocks,
                                primals.get_block(self._num_time_blocks))
示例#23
0
 def test_xu(self):
     xu = BlockVector(self.n_scenarios + 1)
     nz = len(self.complicated_vars_ids)
     nx_i = (self.G.shape[0] + nz)
     for i in range(self.n_scenarios):
         xu[i] = np.array([np.inf] * nx_i)
         xu[i][0] = 100.0
     xu[self.n_scenarios] = np.array([np.inf] * nz)
     self.assertIsInstance(self.nlp.xu(), BlockVector)
     xu_flat = xu.flatten()
     self.assertEqual(xu.nblocks, self.nlp.xu().nblocks)
     self.assertTrue(
         np.allclose(xu.block_sizes(),
                     self.nlp.xu().block_sizes()))
     self.assertListEqual(list(xu_flat), list(self.nlp.xu().flatten()))
示例#24
0
    def evaluate_d(self, x, out=None, **kwargs):
        """Returns the inequality constraints evaluated at x

        Parameters
        ----------
        x : array_like
            Array with values of primal variables.
        out : array_like
            Output array. Its type is preserved and it
            must be of the right shape to hold the output.

        Returns
        -------
        array_like

        """
        evaluated_g = kwargs.pop('evaluated_g', None)

        if out is None:
            res = self.create_vector_y(subset='d')
        else:
            assert isinstance(
                out,
                BlockVector), 'Composite NLP takes block vector to evaluate g'
            assert out.nblocks == self.nblocks
            assert out.size == self.nd
            res = out

        if evaluated_g is not None:
            assert isinstance(evaluated_g,
                              BlockVector), 'evaluated_g must be a BlockVector'
            assert evaluated_g.nblocks == 2 * self.nblocks
            assert evaluated_g.size == self.ng
            d = evaluated_g.compress(self._d_mask)
            if out is None:
                return BlockVector(
                    [d.get_block(j) for j in range(self.nblocks)])
            for bid in range(self.nblocks):
                out.set_block(bid, d.get_block(bid))
            return out

        if isinstance(x, BlockVector):
            assert x.size == self.nx
            assert x.nblocks == self.nblocks + 1
            for sid in range(self.nblocks):
                self._nlps[sid].evaluate_d(x.get_block(sid),
                                           out=res.get_block(sid))
            return res
        elif isinstance(x, np.ndarray):
            assert x.size == self.nx
            block_x = self.create_vector_x()
            block_x.copyfrom(x)
            x_ = block_x
            for sid in range(self.nblocks):
                self._nlps[sid].evaluate_d(x_.get_block(sid),
                                           out=res.get_block(sid))
            return res
        else:
            raise NotImplementedError(
                "x must be a numpy array or a BlockVector")
示例#25
0
 def test_x_init(self):
     x_init = BlockVector(self.n_scenarios + 1)
     nz = len(self.complicated_vars_ids)
     nx_i = (self.G.shape[0] + nz)
     for i in range(self.n_scenarios):
         x_init[i] = np.zeros(nx_i)
         x_init[i][0] = 1.0
     x_init[self.n_scenarios] = np.zeros(nz)
     self.assertIsInstance(self.nlp.x_init(), BlockVector)
     x_init_flat = x_init.flatten()
     self.assertEqual(x_init.nblocks, self.nlp.x_init().nblocks)
     self.assertTrue(
         np.allclose(x_init.block_sizes(),
                     self.nlp.x_init().block_sizes()))
     self.assertListEqual(list(x_init_flat),
                          list(self.nlp.x_init().flatten()))
示例#26
0
    def test_setdiff1d(self):

        vv1 = np.array([1.1, 3.3])
        vv2 = np.array([4.4, 7.7])
        bvv = BlockVector(2)
        bvv.set_blocks([vv1, vv2])
        res = pn.setdiff1d(self.bv, bvv)
        self.assertIsInstance(res, BlockVector)
        self.assertTrue(np.allclose(res.get_block(0), np.array([2.2])))
        self.assertTrue(np.allclose(res.get_block(1), np.array([5.5, 6.6])))
        vv3 = np.array([1.1, 7.7])
        res = pn.setdiff1d(self.bv, vv3)
        self.assertIsInstance(res, BlockVector)
        self.assertTrue(np.allclose(res.get_block(0), np.array([2.2, 3.3])))
        self.assertTrue(
            np.allclose(res.get_block(1), np.array([4.4, 5.5, 6.6])))
示例#27
0
    def test_arccos(self):
        self.v1 = np.array([1.1, 2.2, 3.3]) / 10.0
        self.v2 = np.array([4.4, 5.5, 6.6, 7.7]) / 10.0
        self.bv = BlockVector([self.v1, self.v2])
        fname = 'arccos'
        fnp = getattr(np, fname)
        fpn = getattr(pn, fname)
        np_v1 = fnp(self.v1)
        pn_v1 = fpn(self.v1)
        self.assertTrue(np.allclose(np_v1, pn_v1))

        np_v1 = fnp(self.v1)
        np_v2 = fnp(self.v2)
        pn_block = fpn(self.bv)
        self.assertTrue(np.allclose(np_v1, pn_block[0]))
        self.assertTrue(np.allclose(np_v2, pn_block[1]))
示例#28
0
    def test_isin(self):

        bv = self.bv
        test_bv = BlockVector(2)
        a = np.array([1.1, 3.3])
        b = np.array([5.5, 7.7])
        test_bv[0] = a
        test_bv[1] = b

        res = pn.isin(bv, test_bv)
        for bid, blk in enumerate(bv):
            self.assertEqual(blk.size, res[bid].size)
            res_flat = np.isin(blk, test_bv[bid])
            self.assertTrue(np.allclose(res[bid], res_flat))

        c = np.concatenate([a, b])
        res = pn.isin(bv, c)
        for bid, blk in enumerate(bv):
            self.assertEqual(blk.size, res[bid].size)
            res_flat = np.isin(blk, c)
            self.assertTrue(np.allclose(res[bid], res_flat))

        res = pn.isin(bv, test_bv, invert=True)
        for bid, blk in enumerate(bv):
            self.assertEqual(blk.size, res[bid].size)
            res_flat = np.isin(blk, test_bv[bid], invert=True)
            self.assertTrue(np.allclose(res[bid], res_flat))

        c = np.concatenate([a, b])
        res = pn.isin(bv, c, invert=True)
        for bid, blk in enumerate(bv):
            self.assertEqual(blk.size, res[bid].size)
            res_flat = np.isin(blk, c, invert=True)
            self.assertTrue(np.allclose(res[bid], res_flat))
示例#29
0
    def test_where(self):

        bv = self.bv
        condition = bv >= 4.5
        res = pn.where(condition)[0]
        for bid, blk in enumerate(res):
            self.assertTrue(
                np.allclose(blk, pn.where(bv.get_block(bid) >= 4.5)))

        flat_condition = condition.flatten()
        res = pn.where(condition, 2.0, 1.0)
        res_flat = pn.where(flat_condition, 2.0, 1.0)
        self.assertTrue(np.allclose(res.flatten(), res_flat))

        res = pn.where(condition, 2.0, np.ones(bv.size))
        res_flat = pn.where(flat_condition, 2.0, np.ones(bv.size))
        self.assertTrue(np.allclose(res.flatten(), res_flat))

        res = pn.where(condition, np.ones(bv.size) * 2.0, 1.0)
        res_flat = pn.where(flat_condition, np.ones(bv.size) * 2.0, 1.0)
        self.assertTrue(np.allclose(res.flatten(), res_flat))

        res = pn.where(condition, np.ones(bv.size) * 2.0, np.ones(bv.size))
        res_flat = pn.where(flat_condition,
                            np.ones(bv.size) * 2.0, np.ones(bv.size))
        self.assertTrue(np.allclose(res.flatten(), res_flat))

        bones = BlockVector(2)
        bones.set_blocks([np.ones(3), np.ones(4)])

        res = pn.where(condition, bones * 2.0, 1.0)
        res_flat = pn.where(flat_condition, np.ones(bv.size) * 2.0, 1.0)
        self.assertTrue(np.allclose(res.flatten(), res_flat))

        res = pn.where(condition, 2.0, bones)
        res_flat = pn.where(flat_condition, 2.0, bones)
        self.assertTrue(np.allclose(res.flatten(), res_flat))

        res = pn.where(condition, np.ones(bv.size) * 2.0, bones)
        res_flat = pn.where(flat_condition,
                            np.ones(bv.size) * 2.0, np.ones(bv.size))
        self.assertTrue(np.allclose(res.flatten(), res_flat))

        res = pn.where(condition, bones * 2.0, np.ones(bv.size))
        res_flat = pn.where(flat_condition,
                            np.ones(bv.size) * 2.0, np.ones(bv.size))
        self.assertTrue(np.allclose(res.flatten(), res_flat))
示例#30
0
    def test_copyfrom(self):
        v = self.ones
        v1 = np.zeros(v.size)
        v.copyfrom(v1)
        self.assertListEqual(v.tolist(), v1.tolist())

        v2 = BlockVector(len(self.list_sizes_ones))
        for i, s in enumerate(self.list_sizes_ones):
            v2[i] = np.ones(s)*i
        v.copyfrom(v2)
        for idx, blk in enumerate(v2):
            self.assertListEqual(blk.tolist(), v2[idx].tolist())

        v3 = BlockVector(2)
        v4 = v.clone(2)
        v3[0] = v4
        v3[1] = np.zeros(3)
        self.assertListEqual(v3.tolist(), v4.tolist() + [0]*3)
示例#31
0
    def test_intersect1d(self):

        vv1 = np.array([1.1, 3.3])
        vv2 = np.array([4.4, 7.7])
        bvv = BlockVector(2)
        bvv.set_blocks([vv1, vv2])
        res = pn.intersect1d(self.bv, bvv)
        self.assertIsInstance(res, BlockVector)
        self.assertTrue(np.allclose(res.get_block(0), vv1))
        self.assertTrue(np.allclose(res.get_block(1), vv2))
        vv3 = np.array([1.1, 7.7])
        res = pn.intersect1d(self.bv, vv3)
        self.assertIsInstance(res, BlockVector)
        self.assertTrue(np.allclose(res.get_block(0), np.array([1.1])))
        self.assertTrue(np.allclose(res.get_block(1), np.array([7.7])))
        res = pn.intersect1d(vv3, self.bv)
        self.assertIsInstance(res, BlockVector)
        self.assertTrue(np.allclose(res.get_block(0), np.array([1.1])))
        self.assertTrue(np.allclose(res.get_block(1), np.array([7.7])))
示例#32
0
 def create_blocks(self, m: np.ndarray, x: np.ndarray):
     m = coo_matrix(m)
     r = m * x
     bm = BlockMatrix(2, 2)
     bm.set_block(0, 0, m.copy())
     bm.set_block(1, 1, m.copy())
     br = BlockVector(2)
     br.set_block(0, r.copy())
     br.set_block(1, r.copy())
     bx = BlockVector(2)
     bx.set_block(0, x.copy())
     bx.set_block(1, x.copy())
     return bm, bx, br