예제 #1
0
    def test_lt(self):

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

        flags = v < 1
        v.set_block(0, a - 1)
        v.set_block(1, b + 1)
        self.assertEqual(v.nblocks, flags.nblocks)
        for bid, blk in enumerate(flags):
            self.assertTrue(np.allclose(blk, v.get_block(bid)))
        v.set_block(0, a + 1)
        v.set_block(1, b - 1)
        flags = v < np.ones(v.size)
        v.set_block(0, a - 1)
        v.set_block(1, b + 1)
        self.assertEqual(v.nblocks, flags.nblocks)
        for bid, blk in enumerate(flags):
            self.assertTrue(np.allclose(blk, v.get_block(bid)))

        v.set_block(0, a + 1)
        v.set_block(1, b - 1)
        vv = v.copy()
        vv.fill(1.0)
        flags = v < vv
        v.set_block(0, a - 1)
        v.set_block(1, b + 1)
        self.assertEqual(v.nblocks, flags.nblocks)
        for bid, blk in enumerate(flags):
            self.assertTrue(np.allclose(blk, v.get_block(bid)))
예제 #2
0
    def test_nonzero(self):

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

        n = v.nonzero()

        v2 = BlockVector(2)
        v2.set_block(0, np.arange(5))
        v2.set_block(1, np.zeros(0))
        self.assertEqual(n[0].nblocks, v.nblocks)
        for bid, blk in enumerate(n[0]):
            self.assertTrue(np.allclose(blk, v2.get_block(bid)))
예제 #3
0
    def calculate_full_space_lagrangian_hessians(self, lam, x):
        y = self.evaluate_external_variables(x)
        lam_g = self.calculate_external_multipliers(lam, x)
        d2fdx0dx0 = 2.0
        d2fdx1dx1 = 2.0
        d2fdy0dy0 = 2.0
        d2fdy1dy1 = 2.0
        hfxx = np.array([[d2fdx0dx0, 0], [0, d2fdx1dx1]])
        hfxy = np.array([[0, 0], [0, 0]])
        hfyy = np.array([[d2fdy0dy0, 0], [0, d2fdy1dy1]])

        dg0dx0dx0 = 2 * y[0] * x[1]**0.5 * y[1]
        dg0dx0dx1 = x[0] * y[0] * y[1] / x[1]**0.5
        dg0dx1dx1 = -1 / 4 * x[0]**2 * y[0] * y[1] / x[1]**(3 / 2)
        dg0dx0dy0 = 2 * x[0] * x[1]**0.5 * y[1]
        dg0dx0dy1 = 2 * x[0] * y[0] * x[1]**0.5
        dg0dx1dy0 = 0.5 * x[0]**2 * y[1] / x[1]**0.5
        dg0dx1dy1 = 0.5 * x[0]**2 * y[0] / x[1]**0.5
        dg0dy0dy1 = x[0]**2 * x[1]**0.5
        hg0xx = np.array([[dg0dx0dx0, dg0dx0dx1], [dg0dx0dx1, dg0dx1dx1]])
        hg0xy = np.array([[dg0dx0dy0, dg0dx0dy1], [dg0dx1dy0, dg0dx1dy1]])
        hg0yy = np.array([[0, dg0dy0dy1], [dg0dy0dy1, 0]])

        dg1dx0dx1 = y[0]
        dg1dx0dy0 = x[1]
        dg1dx1dy0 = x[0]
        hg1xx = np.array([[0, dg1dx0dx1], [dg1dx0dx1, 0]])
        hg1xy = np.array([[dg1dx0dy0, 0], [dg1dx1dy0, 0]])
        hg1yy = np.zeros((2, 2))

        hlxx = lam[0] * hfxx + lam_g[0] * hg0xx + lam_g[1] * hg1xx
        hlxy = lam[0] * hfxy + lam_g[0] * hg0xy + lam_g[1] * hg1xy
        hlyy = lam[0] * hfyy + lam_g[0] * hg0yy + lam_g[1] * hg1yy
        return hlxx, hlxy, hlyy
예제 #4
0
 def test_y_init(self):
     y_init = np.zeros(self.nlp3.ng)
     self.assertTrue(np.allclose(self.nlp3.y_init(), y_init))
     self.assertTrue(
         np.allclose(self.nlp2.y_init(), self.pyomo_nlp2.y_init()))
     self.assertTrue(
         np.allclose(self.nlp3.y_init(), self.pyomo_nlp3.y_init()))
예제 #5
0
 def test_copy(self):
     v = BlockVector(2)
     a = np.ones(5)
     b = np.zeros(9)
     v.set_block(0, a)
     v.set_block(1, b)
     v2 = v.copy()
     self.assertTrue(np.allclose(v.flatten(), v2.flatten()))
예제 #6
0
    def test_iadd(self):
        v = self.ones
        v += 3
        self.assertListEqual(v.tolist(), [4] * v.size)
        v.fill(1.0)
        v += v
        self.assertListEqual(v.tolist(), [2] * v.size)
        v.fill(1.0)
        v += np.ones(v.size) * 3
        self.assertTrue(np.allclose(v.flatten(), np.ones(v.size) * 4))

        v = BlockVector(2)
        a = np.ones(5)
        b = np.zeros(9)
        a_copy = a.copy()
        b_copy = b.copy()

        v.set_block(0, a)
        v.set_block(1, b)
        v += 1.0

        self.assertTrue(np.allclose(v.get_block(0), a_copy + 1))
        self.assertTrue(np.allclose(v.get_block(1), b_copy + 1))

        v = BlockVector(2)
        a = np.ones(5)
        b = np.zeros(9)
        a_copy = a.copy()
        b_copy = b.copy()

        v.set_block(0, a)
        v.set_block(1, b)

        v2 = BlockVector(2)
        v2.set_block(0, np.ones(5))
        v2.set_block(1, np.ones(9))

        v += v2
        self.assertTrue(np.allclose(v.get_block(0), a_copy + 1))
        self.assertTrue(np.allclose(v.get_block(1), b_copy + 1))

        self.assertTrue(np.allclose(v2.get_block(0), np.ones(5)))
        self.assertTrue(np.allclose(v2.get_block(1), np.ones(9)))

        with self.assertRaises(Exception) as context:
            v += 'hola'
예제 #7
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.set_block(i, np.ones(s) * i)
        v.copyfrom(v2)
        for idx, blk in enumerate(v2):
            self.assertListEqual(blk.tolist(), v2.get_block(idx).tolist())

        v3 = BlockVector(2)
        v4 = v.clone(2)
        v3.set_block(0, v4)
        v3.set_block(1, np.zeros(3))
        self.assertListEqual(v3.tolist(), v4.tolist() + [0] * 3)
예제 #8
0
 def test_copy_structure(self):
     v = BlockVector(2)
     a = np.ones(5)
     b = np.zeros(9)
     v.set_block(0, a)
     v.set_block(1, b)
     v2 = v.copy_structure()
     self.assertEqual(v.get_block(0).size, v2.get_block(0).size)
     self.assertEqual(v.get_block(1).size, v2.get_block(1).size)
예제 #9
0
    def test_contains(self):

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

        self.assertTrue(0 in v)
        self.assertFalse(3 in v)
예제 #10
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())
예제 #11
0
    def __init__(self, A1, A2, c1, c2, N, dt):
        self._A1 = A1
        self._A2 = A2
        self._c1 = c1
        self._c2 = c2
        self._N = N
        self._dt = dt
        self._input_names = ['F1_{}'.format(t) for t in range(1, N)]
        self._input_names.extend(['F2_{}'.format(t) for t in range(1, N)])
        self._input_names.extend(['h1_{}'.format(t) for t in range(0, N)])
        self._input_names.extend(['h2_{}'.format(t) for t in range(0, N)])
        self._output_names = ['F12_{}'.format(t) for t in range(0, N)]
        self._output_names.extend(['Fo_{}'.format(t) for t in range(0, N)])
        self._equality_constraint_names = [
            'h1bal_{}'.format(t) for t in range(1, N)
        ]
        self._equality_constraint_names.extend(
            ['h2bal_{}'.format(t) for t in range(1, N)])

        # inputs
        self._F1 = np.zeros(N)  # we don't use the first one
        self._F2 = np.zeros(N)  # we don't use the first one
        self._h1 = np.zeros(N)
        self._h2 = np.zeros(N)

        # outputs
        self._F12 = np.zeros(N)
        self._Fo = np.zeros(N)

        # multipliers
        self._eq_con_mult_values = np.ones(2 * (N - 1))
        self._output_con_mult_values = np.ones(2 * N)
예제 #12
0
    def test_matrix_multiply(self):
        """
        Test

        [A  B  C   *  [G  J   = [A*G + B*H + C*I    A*J + B*K + C*L
         D  E  F]      H  K      D*G + E*H + F*I    D*J + E*K + F*L]
                       I  L]
        """
        np.random.seed(0)
        A = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        B = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        C = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        D = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        E = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        F = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        G = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        H = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        I = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        J = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        K = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))
        L = sp.csr_matrix(np.random.normal(0, 10, (2, 2)))

        bm1 = BlockMatrix(2, 3)
        bm2 = BlockMatrix(3, 2)

        bm1.set_block(0, 0, A)
        bm1.set_block(0, 1, B)
        bm1.set_block(0, 2, C)
        bm1.set_block(1, 0, D)
        bm1.set_block(1, 1, E)
        bm1.set_block(1, 2, F)

        bm2.set_block(0, 0, G)
        bm2.set_block(1, 0, H)
        bm2.set_block(2, 0, I)
        bm2.set_block(0, 1, J)
        bm2.set_block(1, 1, K)
        bm2.set_block(2, 1, L)

        got = (bm1 * bm2).toarray()
        exp00 = (A * G + B * H + C * I).toarray()
        exp01 = (A * J + B * K + C * L).toarray()
        exp10 = (D * G + E * H + F * I).toarray()
        exp11 = (D * J + E * K + F * L).toarray()
        exp = np.zeros((4, 4))
        exp[0:2, 0:2] = exp00
        exp[0:2, 2:4] = exp01
        exp[2:4, 0:2] = exp10
        exp[2:4, 2:4] = exp11

        self.assertTrue(np.allclose(got, exp))
예제 #13
0
 def test_rfloordiv(self):
     v = self.ones
     v.fill(2.0)
     v1 = v.clone(5.0, copy=True)
     result = v.__rfloordiv__(v1)
     self.assertListEqual(result.tolist(), [5.0 // 2.0] * v.size)
     result = v.flatten() // v1
     self.assertTrue(
         np.allclose(result.flatten(),
                     v.flatten() // v1.flatten()))
     result = 2.0 // v1
     self.assertTrue(np.allclose(result.flatten(), np.zeros(v1.size)))
     result = v1 // 2.0
     self.assertTrue(np.allclose(result.flatten(), np.ones(v1.size) * 2.0))
예제 #14
0
    def evaluate_outputs(self):
        N = self._N
        h1 = self._h1
        h2 = self._h2

        resid = np.zeros(2 * N)

        for t in range(N):
            resid[t] = self._c1 * math.sqrt(h1[t])

        for t in range(N):
            resid[t + N] = self._c2 * math.sqrt(h2[t])

        return resid
예제 #15
0
    def test_gt(self):

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

        flags = v > 0
        self.assertEqual(v.nblocks, flags.nblocks)
        for bid, blk in enumerate(flags):
            self.assertTrue(np.allclose(blk, v.get_block(bid)))

        flags = v > np.zeros(v.size)
        self.assertEqual(v.nblocks, flags.nblocks)
        for bid, blk in enumerate(flags):
            self.assertTrue(np.allclose(blk, v.get_block(bid)))

        vv = v.copy()
        vv.fill(0.0)
        flags = v > vv
        self.assertEqual(v.nblocks, flags.nblocks)
        for bid, blk in enumerate(flags):
            self.assertTrue(np.allclose(blk, v.get_block(bid)))
예제 #16
0
    def evaluate_hessian_outputs(self):
        N = self._N
        F1 = self._F1
        F2 = self._F2
        h1 = self._h1
        h2 = self._h2
        A1 = self._A1
        A2 = self._A2
        c1 = self._c1
        c2 = self._c2
        dt = self._dt
        lam = self._output_con_mult_values

        nnz = 2 * N
        irow = np.zeros(nnz, dtype=np.int64)
        jcol = np.zeros(nnz, dtype=np.int64)
        data = np.zeros(nnz, dtype=np.float64)
        idx = 0

        # Hess F12_t
        for i in range(N):
            irow[idx] = 2 * (N - 1) + i
            jcol[idx] = 2 * (N - 1) + i
            data[idx] = lam[i] * c1 * (-1 / 4) * h1[i]**(-1.5)
            idx += 1
        # Hess Fo_t
        for i in range(N):
            irow[idx] = 2 * (N - 1) + N + i
            jcol[idx] = 2 * (N - 1) + N + i
            data[idx] = lam[N + i] * c2 * (-1 / 4) * h2[i]**(-1.5)
            idx += 1

        assert idx == nnz
        hess = spa.coo_matrix((data, (irow, jcol)),
                              shape=(2 * (N - 1) + 2 * N, 2 * (N - 1) + 2 * N))
        return hess
예제 #17
0
    def evaluate_equality_constraints(self):
        N = self._N
        F1 = self._F1
        F2 = self._F2
        h1 = self._h1
        h2 = self._h2

        resid = np.zeros(2 * (N - 1))

        for t in range(1, N):
            resid[t-1] = (h1[t]-h1[t-1]) - \
                self._dt/self._A1*(F1[t] - self._c1*math.sqrt(h1[t]))

        for t in range(1, N):
            resid[t-2+N] = (h2[t]-h2[t-1]) - \
                self._dt/self._A2*(self._c1*math.sqrt(h1[t]) + F2[t] - self._c2*math.sqrt(h2[t]))
        return resid
예제 #18
0
    def test_util_maps(self):
        anlp = AslNLP(self.filename)
        full_to_compressed_mask = build_compression_mask_for_finite_values(anlp.primals_lb())

        # test build_bounds_mask - should be the same as above
        self.assertTrue(np.array_equal(full_to_compressed_mask, build_bounds_mask(anlp.primals_lb())))

        expected_compressed_primals_lb = np.asarray([-1, 2, -3, -5, -7, -9], dtype=np.float64)

        # test build_compression_matrix
        C = build_compression_matrix(full_to_compressed_mask)
        compressed_primals_lb = C*anlp.primals_lb()
        self.assertTrue(np.array_equal(expected_compressed_primals_lb, compressed_primals_lb))

        # test full_to_compressed
        compressed_primals_lb = full_to_compressed(anlp.primals_lb(), full_to_compressed_mask)
        self.assertTrue(np.array_equal(expected_compressed_primals_lb, compressed_primals_lb))
        # test in place
        compressed_primals_lb = np.zeros(len(expected_compressed_primals_lb))
        ret = full_to_compressed(anlp.primals_lb(), full_to_compressed_mask, out=compressed_primals_lb)
        self.assertTrue(ret is compressed_primals_lb)
        self.assertTrue(np.array_equal(expected_compressed_primals_lb, compressed_primals_lb))
        
        # test compressed_to_full
        expected_full_primals_lb = np.asarray([-1, 2, -3, -np.inf, -5, -np.inf, -7, -np.inf, -9], dtype=np.float64)
        full_primals_lb = compressed_to_full(compressed_primals_lb, full_to_compressed_mask, default=-np.inf)
        self.assertTrue(np.array_equal(expected_full_primals_lb, full_primals_lb))
        # test in place
        full_primals_lb.fill(0.0)
        ret = compressed_to_full(compressed_primals_lb, full_to_compressed_mask, out=full_primals_lb, default=-np.inf)
        self.assertTrue(ret is full_primals_lb)
        self.assertTrue(np.array_equal(expected_full_primals_lb, full_primals_lb))

        # test no default
        expected_full_primals_lb = np.asarray([-1, 2, -3, np.nan, -5, np.nan, -7, np.nan, -9], dtype=np.float64)
        full_primals_lb = compressed_to_full(compressed_primals_lb, full_to_compressed_mask)
        print(expected_full_primals_lb)
        print(full_primals_lb)
        np.testing.assert_array_equal(expected_full_primals_lb, full_primals_lb)
        # test in place no default
        expected_full_primals_lb = np.asarray([-1, 2, -3, 0.0, -5, 0.0, -7, 0.0, -9], dtype=np.float64)
        full_primals_lb.fill(0.0)
        ret = compressed_to_full(compressed_primals_lb, full_to_compressed_mask, out=full_primals_lb)
        self.assertTrue(ret is full_primals_lb)
        self.assertTrue(np.array_equal(expected_full_primals_lb, full_primals_lb))
예제 #19
0
    def test_imul(self):
        v = self.ones
        v *= 3
        self.assertListEqual(v.tolist(), [3] * v.size)
        v.fill(1.0)
        v *= v
        self.assertListEqual(v.tolist(), [1] * v.size)
        v.fill(1.0)
        v *= np.ones(v.size) * 2
        self.assertTrue(np.allclose(v.flatten(), np.ones(v.size) * 2))

        v = BlockVector(2)
        a = np.ones(5)
        b = np.arange(9, dtype=np.float64)
        a_copy = a.copy()
        b_copy = b.copy()
        v.set_block(0, a)
        v.set_block(1, b)
        v *= 2.0

        self.assertTrue(np.allclose(v.get_block(0), a_copy * 2.0))
        self.assertTrue(np.allclose(v.get_block(1), b_copy * 2.0))

        v = BlockVector(2)
        a = np.ones(5)
        b = np.zeros(9)
        a_copy = a.copy()
        b_copy = b.copy()
        v.set_block(0, a)
        v.set_block(1, b)

        v2 = BlockVector(2)
        v2.set_block(0, np.ones(5) * 2)
        v2.set_block(1, np.ones(9) * 2)

        v *= v2
        self.assertTrue(np.allclose(v.get_block(0), a_copy * 2))
        self.assertTrue(np.allclose(v.get_block(1), b_copy * 2))

        self.assertTrue(np.allclose(v2.get_block(0), np.ones(5) * 2))
        self.assertTrue(np.allclose(v2.get_block(1), np.ones(9) * 2))

        with self.assertRaises(Exception) as context:
            v *= 'hola'
예제 #20
0
    def test_itruediv(self):
        v = self.ones
        v /= 3
        self.assertTrue(np.allclose(v.flatten(), np.ones(v.size) / 3))
        v.fill(1.0)
        v /= v
        self.assertTrue(np.allclose(v.flatten(), np.ones(v.size)))
        v.fill(1.0)
        v /= np.ones(v.size) * 2
        self.assertTrue(np.allclose(v.flatten(), np.ones(v.size) / 2))

        v = BlockVector(2)
        a = np.ones(5)
        b = np.arange(9, dtype=np.float64)
        a_copy = a.copy()
        b_copy = b.copy()
        v.set_block(0, a)
        v.set_block(1, b)
        v /= 2.0

        self.assertTrue(np.allclose(v.get_block(0), a_copy / 2.0))
        self.assertTrue(np.allclose(v.get_block(1), b_copy / 2.0))

        v = BlockVector(2)
        a = np.ones(5)
        b = np.zeros(9)
        a_copy = a.copy()
        b_copy = b.copy()
        v.set_block(0, a)
        v.set_block(1, b)

        v2 = BlockVector(2)
        v2.set_block(0, np.ones(5) * 2)
        v2.set_block(1, np.ones(9) * 2)

        v /= v2
        self.assertTrue(np.allclose(v.get_block(0), a_copy / 2))
        self.assertTrue(np.allclose(v.get_block(1), b_copy / 2))

        self.assertTrue(np.allclose(v2.get_block(0), np.ones(5) * 2))
        self.assertTrue(np.allclose(v2.get_block(1), np.ones(9) * 2))

        with self.assertRaises(Exception) as context:
            v *= 'hola'
예제 #21
0
    def test_clip(self):

        v = BlockVector(3)
        v2 = BlockVector(3)
        a = np.zeros(5)
        b = np.ones(3) * 5.0
        c = np.ones(3) * 10.0

        v.set_block(0, a)
        v.set_block(1, b)
        v.set_block(2, c)

        v2.set_block(0, np.ones(5) * 4.0)
        v2.set_block(1, np.ones(3) * 5.0)
        v2.set_block(2, np.ones(3) * 9.0)

        vv = v.clip(4.0, 9.0)
        self.assertEqual(vv.nblocks, v.nblocks)
        for bid, blk in enumerate(vv):
            self.assertTrue(np.allclose(blk, v2.get_block(bid)))
예제 #22
0
def check_sparse_matrix_specific_order(tst,
                                       m1,
                                       m1rows,
                                       m1cols,
                                       m2,
                                       m2rows,
                                       m2cols,
                                       m1_m2_rows_map=None,
                                       m1_m2_cols_map=None):
    tst.assertEqual(m1.shape[0], len(m1rows))
    tst.assertEqual(m1.shape[1], len(m1cols))
    tst.assertEqual(m2.shape[0], len(m2rows))
    tst.assertEqual(m2.shape[1], len(m2cols))
    tst.assertEqual(len(m1rows), len(m2rows))
    tst.assertEqual(len(m1cols), len(m2cols))

    m1c = m1
    if scipy.sparse.issparse(m1c):
        m1c = m1c.todense()
    m2d = m2
    if scipy.sparse.issparse(m2d):
        m2d = m2d.todense()

    m2c = np.zeros((len(m2rows), len(m2cols)))
    if m1_m2_rows_map is None:
        rowmap = [m2rows.index(x) for x in m1rows]
    else:
        rowmap = [m2rows.index(m1_m2_rows_map[x]) for x in m1rows]
    if m1_m2_cols_map is None:
        colmap = [m2cols.index(x) for x in m1cols]
    else:
        colmap = [m2cols.index(m1_m2_cols_map[x]) for x in m1cols]

    for i in range(len(m1rows)):
        for j in range(len(m1cols)):
            m2c[i, j] = m2d[rowmap[i], colmap[j]]

    for i in range(len(m1rows)):
        for j in range(len(m1cols)):
            tst.assertAlmostEqual(m1c[i, j], m2c[i, j], places=7)
예제 #23
0
    def setUp(self):
        row = np.array([0, 3, 1, 2, 3, 0])
        col = np.array([0, 0, 1, 2, 3, 3])
        data = np.array([2., 1, 3, 4, 5, 1])
        m = coo_matrix((data, (row, col)), shape=(4, 4))

        self.block_m = m

        bm = BlockMatrix(2, 2)
        bm.name = 'basic_matrix'
        bm.set_block(0, 0, m.copy())
        bm.set_block(1, 1, m.copy())
        bm.set_block(0, 1, m.copy())
        self.basic_m = bm
        self.dense = np.zeros((8, 8))
        self.dense[0:4, 0:4] = m.toarray()
        self.dense[0:4, 4:8] = m.toarray()
        self.dense[4:8, 4:8] = m.toarray()

        self.composed_m = BlockMatrix(2, 2)
        self.composed_m.set_block(0, 0, self.block_m.copy())
        self.composed_m.set_block(1, 1, self.basic_m.copy())
예제 #24
0
    def test_compare_evaluations(self):
        A1 = 5
        A2 = 10
        c1 = 3
        c2 = 4
        N = 6
        dt = 1

        m = create_pyomo_model(A1, A2, c1, c2, N, dt)
        solver = pyo.SolverFactory('ipopt')
        solver.options['linear_solver'] = 'mumps'
        status = solver.solve(m, tee=False)
        m_nlp = PyomoNLP(m)

        mex = create_pyomo_external_grey_box_model(A1, A2, c1, c2, N, dt)
        # mex_nlp = PyomoGreyBoxNLP(mex)
        mex_nlp = PyomoNLPWithGreyBoxBlocks(mex)

        # get the variable and constraint order and create the maps
        # reliable order independent comparisons
        m_x_order = m_nlp.primals_names()
        m_c_order = m_nlp.constraint_names()
        mex_x_order = mex_nlp.primals_names()
        mex_c_order = mex_nlp.constraint_names()

        x1list = [
            'h1[0]', 'h1[1]', 'h1[2]', 'h1[3]', 'h1[4]', 'h1[5]', 'h2[0]',
            'h2[1]', 'h2[2]', 'h2[3]', 'h2[4]', 'h2[5]', 'F1[1]', 'F1[2]',
            'F1[3]', 'F1[4]', 'F1[5]', 'F2[1]', 'F2[2]', 'F2[3]', 'F2[4]',
            'F2[5]', 'F12[0]', 'F12[1]', 'F12[2]', 'F12[3]', 'F12[4]',
            'F12[5]', 'Fo[0]', 'Fo[1]', 'Fo[2]', 'Fo[3]', 'Fo[4]', 'Fo[5]'
        ]
        x2list = [
            'egb.inputs[h1_0]', 'egb.inputs[h1_1]', 'egb.inputs[h1_2]',
            'egb.inputs[h1_3]', 'egb.inputs[h1_4]', 'egb.inputs[h1_5]',
            'egb.inputs[h2_0]', 'egb.inputs[h2_1]', 'egb.inputs[h2_2]',
            'egb.inputs[h2_3]', 'egb.inputs[h2_4]', 'egb.inputs[h2_5]',
            'egb.inputs[F1_1]', 'egb.inputs[F1_2]', 'egb.inputs[F1_3]',
            'egb.inputs[F1_4]', 'egb.inputs[F1_5]', 'egb.inputs[F2_1]',
            'egb.inputs[F2_2]', 'egb.inputs[F2_3]', 'egb.inputs[F2_4]',
            'egb.inputs[F2_5]', 'egb.outputs[F12_0]', 'egb.outputs[F12_1]',
            'egb.outputs[F12_2]', 'egb.outputs[F12_3]', 'egb.outputs[F12_4]',
            'egb.outputs[F12_5]', 'egb.outputs[Fo_0]', 'egb.outputs[Fo_1]',
            'egb.outputs[Fo_2]', 'egb.outputs[Fo_3]', 'egb.outputs[Fo_4]',
            'egb.outputs[Fo_5]'
        ]
        x1_x2_map = dict(zip(x1list, x2list))
        x1idx_x2idx_map = {
            i: mex_x_order.index(x1_x2_map[m_x_order[i]])
            for i in range(len(m_x_order))
        }

        c1list = [
            'h1bal[1]', 'h1bal[2]', 'h1bal[3]', 'h1bal[4]', 'h1bal[5]',
            'h2bal[1]', 'h2bal[2]', 'h2bal[3]', 'h2bal[4]', 'h2bal[5]',
            'F12con[0]', 'F12con[1]', 'F12con[2]', 'F12con[3]', 'F12con[4]',
            'F12con[5]', 'Focon[0]', 'Focon[1]', 'Focon[2]', 'Focon[3]',
            'Focon[4]', 'Focon[5]', 'min_inflow[1]', 'min_inflow[2]',
            'min_inflow[3]', 'min_inflow[4]', 'min_inflow[5]',
            'max_outflow[0]', 'max_outflow[1]', 'max_outflow[2]',
            'max_outflow[3]', 'max_outflow[4]', 'max_outflow[5]', 'h10', 'h20'
        ]
        c2list = [
            'egb.h1bal_1', 'egb.h1bal_2', 'egb.h1bal_3', 'egb.h1bal_4',
            'egb.h1bal_5', 'egb.h2bal_1', 'egb.h2bal_2', 'egb.h2bal_3',
            'egb.h2bal_4', 'egb.h2bal_5', 'egb.output_constraints[F12_0]',
            'egb.output_constraints[F12_1]', 'egb.output_constraints[F12_2]',
            'egb.output_constraints[F12_3]', 'egb.output_constraints[F12_4]',
            'egb.output_constraints[F12_5]', 'egb.output_constraints[Fo_0]',
            'egb.output_constraints[Fo_1]', 'egb.output_constraints[Fo_2]',
            'egb.output_constraints[Fo_3]', 'egb.output_constraints[Fo_4]',
            'egb.output_constraints[Fo_5]', 'min_inflow[1]', 'min_inflow[2]',
            'min_inflow[3]', 'min_inflow[4]', 'min_inflow[5]',
            'max_outflow[0]', 'max_outflow[1]', 'max_outflow[2]',
            'max_outflow[3]', 'max_outflow[4]', 'max_outflow[5]', 'h10', 'h20'
        ]
        c1_c2_map = dict(zip(c1list, c2list))
        c1idx_c2idx_map = {
            i: mex_c_order.index(c1_c2_map[m_c_order[i]])
            for i in range(len(m_c_order))
        }

        # get the primals from m and put them in the correct order for mex
        m_x = m_nlp.get_primals()
        mex_x = np.zeros(len(m_x))
        for i in range(len(m_x)):
            mex_x[x1idx_x2idx_map[i]] = m_x[i]

        # get the duals from m and put them in the correct order for mex
        m_lam = m_nlp.get_duals()
        mex_lam = np.zeros(len(m_lam))
        for i in range(len(m_x)):
            mex_lam[c1idx_c2idx_map[i]] = m_lam[i]

        mex_nlp.set_primals(mex_x)
        mex_nlp.set_duals(mex_lam)

        m_obj = m_nlp.evaluate_objective()
        mex_obj = mex_nlp.evaluate_objective()
        self.assertAlmostEqual(m_obj, mex_obj, places=4)

        m_gobj = m_nlp.evaluate_grad_objective()
        mex_gobj = mex_nlp.evaluate_grad_objective()
        check_vectors_specific_order(self, m_gobj, m_x_order, mex_gobj,
                                     mex_x_order, x1_x2_map)

        m_c = m_nlp.evaluate_constraints()
        mex_c = mex_nlp.evaluate_constraints()
        check_vectors_specific_order(self, m_c, m_c_order, mex_c, mex_c_order,
                                     c1_c2_map)

        m_j = m_nlp.evaluate_jacobian()
        mex_j = mex_nlp.evaluate_jacobian().todense()
        check_sparse_matrix_specific_order(self, m_j, m_c_order, m_x_order,
                                           mex_j, mex_c_order, mex_x_order,
                                           c1_c2_map, x1_x2_map)

        m_h = m_nlp.evaluate_hessian_lag()
        mex_h = mex_nlp.evaluate_hessian_lag()
        check_sparse_matrix_specific_order(self, m_h, m_x_order, m_x_order,
                                           mex_h, mex_x_order, mex_x_order,
                                           x1_x2_map, x1_x2_map)

        mex_h = 0 * mex_h
        mex_nlp.evaluate_hessian_lag(out=mex_h)
        check_sparse_matrix_specific_order(self, m_h, m_x_order, m_x_order,
                                           mex_h, mex_x_order, mex_x_order,
                                           x1_x2_map, x1_x2_map)
예제 #25
0
 def __init__(self):
     self._input_names = ['Pin', 'c', 'F']
     self._input_values = np.zeros(3, dtype=np.float64)
     self._output_names = ['Pout']
예제 #26
0
 def test_xl(self):
     xl = np.array([-np.inf, 0, 0])
     self.assertTrue(np.allclose(xl, self.nlp3.xl()))
     xl = np.zeros(2)
     self.assertTrue(np.allclose(xl, self.nlp3.xl(condensed=True)))
예제 #27
0
    def _apply_to(self, model, **kwds):

        complicating_vars = kwds.pop('complicating_vars', None)
        z_estimates = kwds.pop('z_estimates', None)
        w_estimates = kwds.pop('w_estimates', None)
        rho = kwds.pop('rho', 1.0)

        if complicating_vars is None:
            raise RuntimeError('need to pass list of complicating variables')

        assert isinstance(complicating_vars, list)

        cloned_vars = []
        original_vars = []
        for v in complicating_vars:
            vid = aml.ComponentUID(v)
            vv = vid.find_component_on(model)
            if v.is_indexed():
                raise RuntimeError('Indexed variables not supported')
            else:
                cloned_vars.append(vv)
                original_vars.append(v)

        nz = len(cloned_vars)
        z_vals = np.zeros(nz)
        if z_estimates is not None:
            assert len(z_estimates) == nz
            z_vals = z_estimates

        w_vals = np.zeros(nz)
        if w_estimates is not None:
            assert len(w_estimates) == nz
            w_vals = w_estimates

        model._z = aml.Param(range(nz), initialize=0.0, mutable=True)
        model._w = aml.Param(range(nz), initialize=0.0, mutable=True)
        for i in range(nz):
            model._z[i].value = z_vals[i]
            model._w[i].value = w_vals[i]

        model._rho = aml.Param(initialize=rho, mutable=True)

        # defines objective
        objectives = model.component_map(aml.Objective, active=True)
        if len(objectives) > 1:
            raise RuntimeError('Multiple objectives not supported')
        obj = list(objectives.values())[0]

        def rule_linkin_exprs(m, i):
            return cloned_vars[i] - m._z[i]

        # store non-anticipativity expression
        model._linking_residuals = aml.Expression(range(nz),
                                                  rule=rule_linkin_exprs)

        dual_term = 0.0
        penalty_term = 0.0
        for zid in range(nz):
            dual_term += (model._linking_residuals[zid]) * model._w[zid]
            penalty_term += (model._linking_residuals[zid])**2

        # multiplier terms in objective
        model._dual_obj_term = aml.Expression(expr=dual_term)
        # penalty term
        model._penalty_obj_term = aml.Expression(expr=0.5 * model._rho *
                                                 penalty_term)

        model._aug_obj = aml.Objective(expr=obj.expr + model._dual_obj_term +
                                       model._penalty_obj_term)

        obj.deactivate()
예제 #28
0
def execute_extended_nlp_interface(self, anlp):
    self.assertEqual(anlp.n_primals(), 9)
    self.assertEqual(anlp.n_constraints(), 9)
    self.assertEqual(anlp.n_eq_constraints(), 2)
    self.assertEqual(anlp.n_ineq_constraints(), 7)
    self.assertEqual(anlp.nnz_jacobian(), 9 * 9)
    self.assertEqual(anlp.nnz_jacobian_eq(), 2 * 9)
    self.assertEqual(anlp.nnz_jacobian_ineq(), 7 * 9)
    self.assertEqual(anlp.nnz_hessian_lag(), 9 * 9)

    expected_primals_lb = np.asarray(
        [-1, -np.inf, -3, -np.inf, -5, -np.inf, -7, -np.inf, -9],
        dtype=np.float64)
    expected_primals_ub = np.asarray(
        [1, 2, np.inf, np.inf, 5, 6, np.inf, np.inf, 9], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_primals_lb, anlp.primals_lb()))
    self.assertTrue(np.array_equal(expected_primals_ub, anlp.primals_ub()))

    expected_constraints_lb = np.asarray(
        [-1, 0, -3, -np.inf, -5, 0, -7, -np.inf, -9], dtype=np.float64)
    expected_constraints_ub = np.asarray([1, 0, np.inf, 4, 5, 0, np.inf, 8, 9],
                                         dtype=np.float64)
    self.assertTrue(
        np.array_equal(expected_constraints_lb, anlp.constraints_lb()))
    self.assertTrue(
        np.array_equal(expected_constraints_ub, anlp.constraints_ub()))

    expected_ineq_lb = np.asarray([-1, -3, -np.inf, -5, -7, -np.inf, -9],
                                  dtype=np.float64)
    expected_ineq_ub = np.asarray([1, np.inf, 4, 5, np.inf, 8, 9],
                                  dtype=np.float64)
    self.assertTrue(np.array_equal(expected_ineq_lb, anlp.ineq_lb()))
    self.assertTrue(np.array_equal(expected_ineq_ub, anlp.ineq_ub()))

    expected_init_primals = np.ones(9)
    self.assertTrue(np.array_equal(expected_init_primals, anlp.init_primals()))
    expected_init_duals = np.asarray([1, 2, 3, 4, 5, 6, 7, 8, 9],
                                     dtype=np.float64)
    self.assertTrue(np.array_equal(expected_init_duals, anlp.init_duals()))
    expected_init_duals_ineq = np.asarray([1, 3, 4, 5, 7, 8, 9],
                                          dtype=np.float64)
    self.assertTrue(
        np.array_equal(expected_init_duals_ineq, anlp.init_duals_ineq()))
    expected_init_duals_eq = np.asarray([2, 6], dtype=np.float64)
    self.assertTrue(
        np.array_equal(expected_init_duals_eq, anlp.init_duals_eq()))

    t = anlp.create_new_vector('primals')
    self.assertTrue(t.size == 9)
    t = anlp.create_new_vector('constraints')
    self.assertTrue(t.size == 9)
    t = anlp.create_new_vector('eq_constraints')
    self.assertTrue(t.size == 2)
    t = anlp.create_new_vector('ineq_constraints')
    self.assertTrue(t.size == 7)
    t = anlp.create_new_vector('duals')
    self.assertTrue(t.size == 9)
    t = anlp.create_new_vector('duals_eq')
    self.assertTrue(t.size == 2)
    t = anlp.create_new_vector('duals_ineq')
    self.assertTrue(t.size == 7)

    expected_primals = [i + 1 for i in range(9)]
    new_primals = np.asarray(expected_primals, dtype=np.float64)
    expected_primals = np.asarray(expected_primals, dtype=np.float64)
    anlp.set_primals(new_primals)
    ret = anlp.get_primals()
    self.assertTrue(np.array_equal(new_primals, ret))
    self.assertTrue(np.array_equal(expected_primals, anlp._primals))
    anlp.set_primals(np.ones(9))

    expected_duals = [i + 1 for i in range(9)]
    new_duals = np.asarray(expected_duals, dtype=np.float64)
    expected_duals = np.asarray(expected_duals, dtype=np.float64)
    anlp.set_duals(new_duals)
    self.assertTrue(np.array_equal(expected_duals, anlp._duals_full))
    ret = anlp.get_duals()
    self.assertTrue(np.array_equal(new_duals, ret))
    expected_duals_eq = np.asarray([2, 6], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_duals_eq, anlp._duals_eq))
    expected_duals_ineq = np.asarray([1, 3, 4, 5, 7, 8, 9], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_duals_ineq, anlp._duals_ineq))
    anlp.set_duals(np.ones(9))

    expected_duals_eq = [i + 1 for i in range(2)]
    new_duals_eq = np.asarray(expected_duals_eq, dtype=np.float64)
    anlp.set_duals_eq(new_duals_eq)
    ret = anlp.get_duals_eq()
    self.assertTrue(np.array_equal(new_duals_eq, ret))
    self.assertTrue(np.array_equal(expected_duals_eq, anlp._duals_eq))
    expected_duals = np.asarray([1, 1, 1, 1, 1, 2, 1, 1, 1], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_duals, anlp._duals_full))
    expected_duals_ineq = np.asarray([1, 1, 1, 1, 1, 1, 1], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_duals_ineq, anlp._duals_ineq))
    anlp.set_duals_eq(np.ones(2))
    expected_duals = np.asarray([1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_duals, anlp._duals_full))

    expected_duals_ineq = [i + 1 for i in range(7)]
    new_duals_ineq = np.asarray(expected_duals_ineq, dtype=np.float64)
    anlp.set_duals_ineq(new_duals_ineq)
    ret = anlp.get_duals_ineq()
    self.assertTrue(np.array_equal(new_duals_ineq, ret))
    self.assertTrue(np.array_equal(expected_duals_ineq, anlp._duals_ineq))
    expected_duals = np.asarray([1, 1, 2, 3, 4, 1, 5, 6, 7], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_duals, anlp._duals_full))
    expected_duals_eq = np.asarray([1, 1], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_duals_eq, anlp._duals_eq))
    anlp.set_duals_ineq(np.ones(7))
    expected_duals = np.asarray([1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_duals, anlp._duals_full))

    # objective function
    expected_objective = sum(
        (i + 1) * (j + 1) for i in range(9) for j in range(9))
    self.assertEqual(expected_objective, anlp.evaluate_objective())
    # change the value of the primals
    anlp.set_primals(2.0 * np.ones(9))
    expected_objective = sum(2.0**2 * (i + 1) * (j + 1) for i in range(9)
                             for j in range(9))
    self.assertEqual(expected_objective, anlp.evaluate_objective())
    anlp.set_primals(np.ones(9))

    # gradient of the objective
    expected_gradient = np.asarray(
        [2 * sum((i + 1) * (j + 1) for j in range(9)) for i in range(9)],
        dtype=np.float64)
    grad_obj = anlp.evaluate_grad_objective()
    self.assertTrue(np.array_equal(expected_gradient, grad_obj))
    # test inplace
    grad_obj = np.ones(9)
    ret = anlp.evaluate_grad_objective(out=grad_obj)
    self.assertTrue(ret is grad_obj)
    self.assertTrue(np.array_equal(expected_gradient, grad_obj))
    # change the value of the primals
    anlp.set_primals(2.0 * np.ones(9))
    expected_gradient = np.asarray(
        [2 * 2 * sum((i + 1) * (j + 1) for j in range(9)) for i in range(9)],
        dtype=np.float64)
    grad_obj = np.ones(9)
    anlp.evaluate_grad_objective(out=grad_obj)
    self.assertTrue(np.array_equal(expected_gradient, grad_obj))
    anlp.set_primals(np.ones(9))

    # full constraints
    con = anlp.evaluate_constraints()
    expected_con = np.asarray(
        [45, 88, 3 * 45, 4 * 45, 5 * 45, 276, 7 * 45, 8 * 45, 9 * 45],
        dtype=np.float64)
    self.assertTrue(np.array_equal(expected_con, con))
    # test inplace
    con = np.zeros(9)
    ret = anlp.evaluate_constraints(out=con)
    self.assertTrue(ret is con)
    self.assertTrue(np.array_equal(expected_con, con))
    # change the value of the primals
    anlp.set_primals(2.0 * np.ones(9))
    con = np.zeros(9)
    anlp.evaluate_constraints(out=con)
    expected_con = np.asarray([
        2 * 45, 2 * (88 + 2) - 2, 2 * 3 * 45, 2 * 4 * 45, 2 * 5 * 45, 2 *
        (276 - 6) + 6, 2 * 7 * 45, 2 * 8 * 45, 2 * 9 * 45
    ],
                              dtype=np.float64)
    self.assertTrue(np.array_equal(expected_con, con))
    anlp.set_primals(np.ones(9))

    # equality constraints
    con_eq = anlp.evaluate_eq_constraints()
    expected_con_eq = np.asarray([88, 276], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_con_eq, con_eq))
    # test inplace
    con_eq = np.zeros(2)
    ret = anlp.evaluate_eq_constraints(out=con_eq)
    self.assertTrue(ret is con_eq)
    self.assertTrue(np.array_equal(expected_con_eq, con_eq))
    # change the value of the primals
    anlp.set_primals(2.0 * np.ones(9))
    con_eq = np.zeros(2)
    anlp.evaluate_eq_constraints(out=con_eq)
    expected_con_eq = np.asarray([2 * (88 + 2) - 2, 2 * (276 - 6) + 6],
                                 dtype=np.float64)
    self.assertTrue(np.array_equal(expected_con_eq, con_eq))
    anlp.set_primals(np.ones(9))

    # inequality constraints
    con_ineq = anlp.evaluate_ineq_constraints()
    expected_con_ineq = np.asarray(
        [45, 3 * 45, 4 * 45, 5 * 45, 7 * 45, 8 * 45, 9 * 45], dtype=np.float64)
    self.assertTrue(np.array_equal(expected_con_ineq, con_ineq))
    # test inplace
    con_ineq = np.zeros(7)
    ret = anlp.evaluate_ineq_constraints(out=con_ineq)
    self.assertTrue(ret is con_ineq)
    self.assertTrue(np.array_equal(expected_con_ineq, con_ineq))
    # change the value of the primals
    anlp.set_primals(2.0 * np.ones(9))
    con_ineq = np.zeros(7)
    anlp.evaluate_ineq_constraints(out=con_ineq)
    expected_con_ineq = 2.0 * expected_con_ineq
    self.assertTrue(np.array_equal(expected_con_ineq, con_ineq))
    anlp.set_primals(np.ones(9))

    # jacobian of all constraints
    jac = anlp.evaluate_jacobian()
    dense_jac = jac.todense()
    expected_jac = [[(i) * (j) for j in range(1, 10)] for i in range(1, 10)]
    expected_jac = np.asarray(expected_jac, dtype=np.float64)
    self.assertTrue(np.array_equal(dense_jac, expected_jac))
    # test inplace
    jac.data = 0 * jac.data
    ret = anlp.evaluate_jacobian(out=jac)
    self.assertTrue(ret is jac)
    dense_jac = jac.todense()
    self.assertTrue(np.array_equal(dense_jac, expected_jac))
    # change the value of the primals
    # ToDo: not a great test since this problem is linear
    anlp.set_primals(2.0 * np.ones(9))
    anlp.evaluate_jacobian(out=jac)
    dense_jac = jac.todense()
    self.assertTrue(np.array_equal(dense_jac, expected_jac))

    # jacobian of equality constraints
    jac_eq = anlp.evaluate_jacobian_eq()
    dense_jac_eq = jac_eq.todense()
    expected_jac_eq = np.asarray([[2, 4, 6, 8, 10, 12, 14, 16, 18],
                                  [6, 12, 18, 24, 30, 36, 42, 48, 54]],
                                 dtype=np.float64)
    self.assertTrue(np.array_equal(dense_jac_eq, expected_jac_eq))
    # test inplace
    jac_eq.data = 0 * jac_eq.data
    ret = anlp.evaluate_jacobian_eq(out=jac_eq)
    self.assertTrue(ret is jac_eq)
    dense_jac_eq = jac_eq.todense()
    self.assertTrue(np.array_equal(dense_jac_eq, expected_jac_eq))
    # change the value of the primals
    # ToDo: not a great test since this problem is linear
    anlp.set_primals(2.0 * np.ones(9))
    anlp.evaluate_jacobian_eq(out=jac_eq)
    dense_jac_eq = jac_eq.todense()
    self.assertTrue(np.array_equal(dense_jac_eq, expected_jac_eq))

    # jacobian of inequality constraints
    jac_ineq = anlp.evaluate_jacobian_ineq()
    dense_jac_ineq = jac_ineq.todense()
    expected_jac_ineq = [[(i) * (j) for j in range(1, 10)]
                         for i in [1, 3, 4, 5, 7, 8, 9]]
    expected_jac_ineq = np.asarray(expected_jac_ineq, dtype=np.float64)
    self.assertTrue(np.array_equal(dense_jac_ineq, expected_jac_ineq))
    # test inplace
    jac_ineq.data = 0 * jac_ineq.data
    ret = anlp.evaluate_jacobian_ineq(out=jac_ineq)
    self.assertTrue(ret is jac_ineq)
    dense_jac_ineq = jac_ineq.todense()
    self.assertTrue(np.array_equal(dense_jac_ineq, expected_jac_ineq))
    # change the value of the primals
    # ToDo: not a great test since this problem is linear
    anlp.set_primals(2.0 * np.ones(9))
    anlp.evaluate_jacobian_ineq(out=jac_ineq)
    dense_jac_ineq = jac_ineq.todense()
    self.assertTrue(np.array_equal(dense_jac_ineq, expected_jac_ineq))

    # hessian
    hess = anlp.evaluate_hessian_lag()
    dense_hess = hess.todense()
    expected_hess = [[2.0 * i * j for j in range(1, 10)] for i in range(1, 10)]
    expected_hess = np.asarray(expected_hess, dtype=np.float64)
    self.assertTrue(np.array_equal(dense_hess, expected_hess))
    # test inplace
    hess.data = np.zeros(len(hess.data))
    ret = anlp.evaluate_hessian_lag(out=hess)
    self.assertTrue(ret is hess)
    dense_hess = hess.todense()
    self.assertTrue(np.array_equal(dense_hess, expected_hess))
    # change the value of the primals
    anlp.set_primals(2.0 * np.ones(9))
    anlp.evaluate_hessian_lag(out=hess)
    dense_hess = hess.todense()
    self.assertTrue(np.array_equal(dense_hess, expected_hess))
    # change the value of the obj factor
    anlp.set_obj_factor(2.0)
    hess = anlp.evaluate_hessian_lag()
    dense_hess = hess.todense()
    expected_hess = [[4.0 * i * j for j in range(1, 10)] for i in range(1, 10)]
    expected_hess = np.asarray(expected_hess, dtype=np.float64)
    self.assertTrue(np.array_equal(dense_hess, expected_hess))
예제 #29
0
 def test_max_with_empty_blocks(self):
     b = BlockVector(3)
     b.set_block(0, np.zeros(3))
     b.set_block(1, np.zeros(0))
     b.set_block(2, np.zeros(3))
     self.assertEqual(b.max(), 0)
예제 #30
0
 def __init__(self):
     super(PressureDropTwoEqualitiesTwoOutputsWithHessian, self).__init__()
     self._eq_con_mult_values = np.zeros(2, dtype=np.float64)
     self._output_con_mult_values = np.zeros(2, dtype=np.float64)