예제 #1
0
    def test_simple_paraboloid_equality(self):

        prob = Problem()
        root = prob.root = Group()

        root.add('p1', ParamComp('x', 50.0), promotes=['*'])
        root.add('p2', ParamComp('y', 50.0), promotes=['*'])
        root.add('comp', Paraboloid(), promotes=['*'])
        root.add('con', ExecComp('c = 15.0 - x + y'), promotes=['*'])

        prob.driver = ScipyOptimizer()
        prob.driver.options['optimizer'] = 'SLSQP'
        prob.driver.options['tol'] = 1.0e-8
        prob.driver.add_param('x', low=-50.0, high=50.0)
        prob.driver.add_param('y', low=-50.0, high=50.0)

        prob.driver.add_objective('f_xy')
        prob.driver.add_constraint('c', ctype='ineq')
        prob.driver.options['disp'] = False

        prob.setup(check=False)
        prob.run()

        # Minimum should be at (7.166667, -7.833334)
        assert_rel_error(self, prob['x'], 7.16667, 1e-6)
        assert_rel_error(self, prob['y'], -7.833334, 1e-6)
예제 #2
0
    def test_double_arraycomp(self):
        # Mainly testing a bug in the array return for multiple arrays

        group = Group()
        group.add('x_param1', ParamComp('x1', np.ones((2))), promotes=['*'])
        group.add('x_param2', ParamComp('x2', np.ones((2))), promotes=['*'])
        group.add('mycomp', DoubleArrayComp(), promotes=['*'])

        prob = Problem()
        prob.root = group
        prob.root.ln_solver = ScipyGMRES()
        prob.setup(check=False)
        prob.run()

        Jbase = group.mycomp.JJ

        J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='fwd',
                               return_format='array')
        diff = np.linalg.norm(J - Jbase)
        assert_rel_error(self, diff, 0.0, 1e-8)

        J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'], mode='fd',
                               return_format='array')
        diff = np.linalg.norm(J - Jbase)
        assert_rel_error(self, diff, 0.0, 1e-8)
예제 #3
0
    def test_simple_paraboloid_equality(self):

        prob = Problem()
        root = prob.root = Group()

        root.add("p1", ParamComp("x", 50.0), promotes=["*"])
        root.add("p2", ParamComp("y", 50.0), promotes=["*"])
        root.add("comp", Paraboloid(), promotes=["*"])
        root.add("con", ExecComp("c = 15.0 - x + y"), promotes=["*"])

        prob.driver = ScipyOptimizer()
        prob.driver.options["optimizer"] = "SLSQP"
        prob.driver.options["tol"] = 1.0e-8
        prob.driver.add_param("x", low=-50.0, high=50.0)
        prob.driver.add_param("y", low=-50.0, high=50.0)

        prob.driver.add_objective("f_xy")
        prob.driver.add_constraint("c", ctype="ineq")

        prob.setup(check=False)
        prob.run()

        # Minimum should be at (7.166667, -7.833334)
        assert_rel_error(self, prob["x"], 7.16667, 1e-6)
        assert_rel_error(self, prob["y"], -7.833334, 1e-6)
예제 #4
0
    def test_simple_matvec(self):
        class VerificationComp(SimpleCompDerivMatVec):
            def jacobian(self, params, unknowns, resids):
                raise RuntimeError("Derivative functions on this comp should not run.")

            def apply_linear(self, params, unknowns, dparams, dunknowns, dresids, mode):
                raise RuntimeError("Derivative functions on this comp should not run.")

        sub = Group()
        sub.add("mycomp", VerificationComp())

        prob = Problem()
        prob.root = Group()
        prob.root.add("sub", sub)
        prob.root.add("x_param", ParamComp("x", 1.0))
        prob.root.connect("x_param.x", "sub.mycomp.x")

        sub.fd_options["force_fd"] = True
        prob.setup(check=False)
        prob.run()

        J = prob.calc_gradient(["x_param.x"], ["sub.mycomp.y"], mode="fwd", return_format="dict")
        assert_rel_error(self, J["sub.mycomp.y"]["x_param.x"][0][0], 2.0, 1e-6)

        J = prob.calc_gradient(["x_param.x"], ["sub.mycomp.y"], mode="rev", return_format="dict")
        assert_rel_error(self, J["sub.mycomp.y"]["x_param.x"][0][0], 2.0, 1e-6)
예제 #5
0
    def test_array(self):
        prob = Problem(root=Group())
        C1 = prob.root.add('C1', ExecComp('y=x[1]', x=np.array([1.,2.,3.]), y=0.0))
        self.assertTrue('x' in C1._params_dict)
        self.assertTrue('y' in C1._unknowns_dict)

        prob.setup(check=False)
        prob.run()

        assert_rel_error(self, C1.unknowns['y'], 2.0, 0.00001)
예제 #6
0
    def test_math(self):
        prob = Problem(root=Group())
        C1 = prob.root.add('C1', ExecComp('y=sin(x)', x=2.0))
        self.assertTrue('x' in C1._params_dict)
        self.assertTrue('y' in C1._unknowns_dict)

        prob.setup(check=False)
        prob.run()

        assert_rel_error(self, C1.unknowns['y'], math.sin(2.0), 0.00001)
예제 #7
0
    def test_array_lhs(self):
        prob = Problem(root=Group())
        C1 = prob.root.add('C1', ExecComp(['y[0]=x[1]', 'y[1]=x[0]'],
                                          x=np.array([1.,2.,3.]), y=np.array([0.,0.])))
        self.assertTrue('x' in C1._params_dict)
        self.assertTrue('y' in C1._unknowns_dict)

        prob.setup(check=False)
        prob.run()

        assert_rel_error(self, C1.unknowns['y'], np.array([2.,1.]), 0.00001)
예제 #8
0
    def test_group_fd(self):
        class SimpleComp(Component):
            """ A simple component that provides derivatives. """

            def __init__(self):
                super(SimpleComp, self).__init__()

                # Params
                self.add_param("x", 2.0)

                # Unknowns
                self.add_output("y", 0.0)

            def solve_nonlinear(self, params, unknowns, resids):
                """ Doesn't do much.  Just multiply by 3"""
                unknowns["y"] = 3.0 * params["x"]

            def jacobian(self, params, unknowns, resids):
                """Analytical derivatives."""

                J = {}
                J[("y", "x")] = 3.0
                return J

        class Model(Group):
            """ Simple model to experiment with finite difference."""

            def __init__(self):
                super(Model, self).__init__()

                self.add("px", ParamComp("x", 2.0))

                self.add("comp1", SimpleComp())
                sub = self.add("sub", Group())
                sub.add("comp2", SimpleComp())
                sub.add("comp3", SimpleComp())
                self.add("comp4", SimpleComp())

                self.connect("px.x", "comp1.x")
                self.connect("comp1.y", "sub.comp2.x")
                self.connect("sub.comp2.y", "sub.comp3.x")
                self.connect("sub.comp3.y", "comp4.x")

                self.sub.fd_options["force_fd"] = True

        prob = Problem()
        prob.root = Model()

        prob.setup(check=False)
        prob.run()

        J = prob.calc_gradient(["px.x"], ["comp4.y"])
        assert_rel_error(self, J[0][0], 81.0, 1e-6)
예제 #9
0
    def test_sellar_group(self):

        prob = Problem()
        prob.root = SellarDerivativesGrouped()
        prob.root.nl_solver = NLGaussSeidel()
        prob.root.nl_solver.options['atol'] = 1e-9
        prob.root.mda.nl_solver.options['atol'] = 1e-3
        prob.root.nl_solver.options['iprint'] = 1 # so that print_norm is in coverage

        prob.setup(check=False)
        prob.run()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)
예제 #10
0
    def test_sellar(self):

        prob = Problem()
        prob.root = SellarNoDerivatives()
        prob.root.nl_solver = NLGaussSeidel()

        prob.setup(check=False)
        prob.run()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)

        # Make sure we aren't iterating like crazy
        self.assertLess(prob.root.nl_solver.iter_count, 8)
예제 #11
0
    def test_fan_in_serial_sets(self):

        prob = Problem(impl=impl)
        prob.root = FanInGrouped()
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.sub.ln_solver = LinearGaussSeidel()

        # Parallel Groups
        prob.driver.add_param("p1.x1")
        prob.driver.add_param("p2.x2")
        prob.driver.add_objective("comp3.y")

        prob.setup(check=False)
        prob.run()

        param_list = ["p1.x1", "p2.x2"]
        unknown_list = ["comp3.y"]

        J = prob.calc_gradient(param_list, unknown_list, mode="rev", return_format="dict")
        assert_rel_error(self, J["comp3.y"]["p1.x1"][0][0], -6.0, 1e-6)
        assert_rel_error(self, J["comp3.y"]["p2.x2"][0][0], 35.0, 1e-6)

        J = prob.calc_gradient(param_list, unknown_list, mode="fwd", return_format="dict")
        assert_rel_error(self, J["comp3.y"]["p1.x1"][0][0], -6.0, 1e-6)
        assert_rel_error(self, J["comp3.y"]["p2.x2"][0][0], 35.0, 1e-6)
예제 #12
0
    def test_sellar_state_connection(self):

        prob = Problem()
        prob.root = SellarStateConnection()
        prob.root.nl_solver = Newton()

        prob.setup(check=False)
        prob.run()

        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['state_eq.y2_command'], 12.05848819, .00001)

        # Make sure we aren't iterating like crazy
        self.assertLess(prob.root.nl_solver.iter_count, 8)
예제 #13
0
    def test_fan_out_serial_sets(self):

        prob = Problem(impl=impl)
        prob.root = FanOutGrouped()
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.sub.ln_solver = LinearGaussSeidel()

        # Parallel Groups
        prob.driver.add_param("p.x")
        prob.driver.add_constraint("c2.y")
        prob.driver.add_constraint("c3.y")

        prob.setup(check=False)
        prob.run()

        unknown_list = ["c2.y", "c3.y"]
        param_list = ["p.x"]

        J = prob.calc_gradient(param_list, unknown_list, mode="fwd", return_format="dict")
        assert_rel_error(self, J["c2.y"]["p.x"][0][0], -6.0, 1e-6)
        assert_rel_error(self, J["c3.y"]["p.x"][0][0], 15.0, 1e-6)

        J = prob.calc_gradient(param_list, unknown_list, mode="rev", return_format="dict")
        assert_rel_error(self, J["c2.y"]["p.x"][0][0], -6.0, 1e-6)
        assert_rel_error(self, J["c3.y"]["p.x"][0][0], 15.0, 1e-6)
예제 #14
0
    def test_fan_out_parallel_sets(self):

        prob = Problem(impl=impl)
        prob.root = FanOutGrouped()
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.sub.ln_solver = LinearGaussSeidel()

        # need to set mode to rev before setup. Otherwise the sub-vectors
        # for the parallel set vars won't get allocated.
        prob.root.ln_solver.options["mode"] = "rev"
        prob.root.sub.ln_solver.options["mode"] = "rev"

        # Parallel Groups
        prob.driver.add_param("p.x")
        prob.driver.add_constraint("c2.y")
        prob.driver.add_constraint("c3.y")
        prob.driver.parallel_derivs(["c2.y", "c3.y"])

        self.assertEqual(prob.driver.outputs_of_interest(), [("c2.y", "c3.y")])
        prob.setup(check=False)
        prob.run()

        unknown_list = ["c2.y", "c3.y"]
        param_list = ["p.x"]

        J = prob.calc_gradient(param_list, unknown_list, mode="rev", return_format="dict")
        assert_rel_error(self, J["c2.y"]["p.x"][0][0], -6.0, 1e-6)
        assert_rel_error(self, J["c3.y"]["p.x"][0][0], 15.0, 1e-6)

        J = prob.calc_gradient(param_list, unknown_list, mode="fwd", return_format="dict")
        assert_rel_error(self, J["c2.y"]["p.x"][0][0], -6.0, 1e-6)
        assert_rel_error(self, J["c3.y"]["p.x"][0][0], 15.0, 1e-6)
예제 #15
0
    def test_complex_step(self):
        prob = Problem(root=Group())
        C1 = prob.root.add('C1', ExecComp(['y=2.0*x+1.'], x=2.0))

        self.assertTrue('x' in C1._params_dict)
        self.assertTrue('y' in C1._unknowns_dict)

        prob.setup(check=False)
        prob.run()

        assert_rel_error(self, C1.unknowns['y'], 5.0, 0.00001)

        J = C1.jacobian(C1.params, C1.unknowns, C1.resids)

        assert_rel_error(self, J[('y','x')], 2.0, 0.00001)
예제 #16
0
    def test_rel_error_array(self):

        try:
            assert_rel_error(self, 1e-2 * np.ones(3), np.zeros(3), 1e-3)
        except AssertionError as exc:
            msg = "arrays do not match, rel error 1.732e-02 > tol (1.000e-03)"
            self.assertEqual(msg, str(exc))
        else:
            self.fail("Expected Assertion Error")

        err = assert_rel_error(self, 1e-2 * np.ones(3), 1e-2 * np.ones(3), 1e-10)
        self.assertEqual(err, 0.0)

        err = assert_rel_error(self, 1e-2 * np.ones(3), 1.00001e-2 * np.ones(3), 1e-3)
        self.assertLessEqual(err, 1e-5)
예제 #17
0
    def test_simple_matvec(self):
        group = Group()
        group.add('x_param', ParamComp('x', 1.0), promotes=['*'])
        group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])

        prob = Problem()
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.setup(check=False)
        prob.run()

        J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')
        assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)

        J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')
        assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)
예제 #18
0
    def test_simple_jac(self):
        group = Group()
        group.add('x_param', ParamComp('x', 1.0), promotes=['*'])
        group.add('mycomp', ExecComp(['y=2.0*x']), promotes=['x', 'y'])

        prob = Problem()
        prob.root = group
        prob.root.ln_solver = ScipyGMRES()
        prob.setup(check=False)
        prob.run()

        J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')
        assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)

        J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')
        assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)
예제 #19
0
    def test_complex_step2(self):
        prob = Problem(Group())
        comp = prob.root.add('comp', ExecComp('y=x*x + x*2.0'))
        prob.root.add('p1', ParamComp('x', 2.0))
        prob.root.connect('p1.x', 'comp.x')

        comp.fd_options['force_fd'] = False

        prob.setup(check=False)
        prob.run()

        J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='fwd', return_format='dict')
        assert_rel_error(self, J['comp.y']['p1.x'], np.array([6.0]), 0.00001)

        J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='rev', return_format='dict')
        assert_rel_error(self, J['comp.y']['p1.x'], np.array([6.0]), 0.00001)
예제 #20
0
    def test_converge_diverge_groups(self):

        prob = Problem()
        prob.root = Group()
        prob.root.add("sub", ConvergeDivergeGroups())

        param_list = ["sub.p.x"]
        unknown_list = ["sub.comp7.y1"]

        prob.setup(check=False)
        prob.run()

        J = prob.calc_gradient(param_list, unknown_list, mode="fwd", return_format="dict")
        assert_rel_error(self, J["sub.comp7.y1"]["sub.p.x"][0][0], -40.75, 1e-6)

        J = prob.calc_gradient(param_list, unknown_list, mode="rev", return_format="dict")
        assert_rel_error(self, J["sub.comp7.y1"]["sub.p.x"][0][0], -40.75, 1e-6)
예제 #21
0
    def test_fan_in_parallel_sets(self):

        prob = Problem(impl=impl)
        prob.root = FanInGrouped()
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.sub.ln_solver = LinearGaussSeidel()

        # auto calculated mode is fwd, so we don't have to set it explicitly
        # in the ln_solvers in order to have our voi subvecs allocated
        # properly.

        # Parallel Groups
        prob.driver.add_param("p1.x1")
        prob.driver.add_param("p2.x2")
        prob.driver.add_objective("comp3.y")

        # make sure we can't mix inputs and outputs in parallel sets
        try:
            prob.driver.parallel_derivs(["p1.x1", "comp3.y"])
        except Exception as err:
            self.assertEqual(
                str(err),
                "['p1.x1', 'comp3.y'] cannot be grouped because ['p1.x1'] are " "params and ['comp3.y'] are not.",
            )
        else:
            self.fail("Exception expected")

        prob.driver.parallel_derivs(["p1.x1", "p2.x2"])

        self.assertEqual(prob.driver.params_of_interest(), [("p1.x1", "p2.x2")])

        # make sure we can't add a VOI to multiple groups
        try:
            prob.driver.parallel_derivs(["p1.x1", "p3.x3"])
        except Exception as err:
            self.assertEqual(
                str(err),
                "'p1.x1' cannot be added to VOI set ('p1.x1', 'p3.x3') "
                "because it already exists in VOI set: ('p1.x1', 'p2.x2')",
            )
        else:
            self.fail("Exception expected")

        prob.setup(check=False)
        prob.run()

        param_list = ["p1.x1", "p2.x2"]
        unknown_list = ["comp3.y"]

        J = prob.calc_gradient(param_list, unknown_list, mode="rev", return_format="dict")
        assert_rel_error(self, J["comp3.y"]["p1.x1"][0][0], -6.0, 1e-6)
        assert_rel_error(self, J["comp3.y"]["p2.x2"][0][0], 35.0, 1e-6)

        J = prob.calc_gradient(param_list, unknown_list, mode="fwd", return_format="dict")
        assert_rel_error(self, J["comp3.y"]["p1.x1"][0][0], -6.0, 1e-6)
        assert_rel_error(self, J["comp3.y"]["p2.x2"][0][0], 35.0, 1e-6)
예제 #22
0
    def test_sellar_derivs(self):

        prob = Problem()
        prob.root = SellarDerivatives()
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.ln_solver.options['maxiter'] = 4

        prob.root.nl_solver.options['atol'] = 1e-12
        prob.setup(check=False)
        prob.run()

        # Just make sure we are at the right answer
        assert_rel_error(self, prob['y1'], 25.58830273, .00001)
        assert_rel_error(self, prob['y2'], 12.05848819, .00001)

        param_list = ['x', 'z']
        param_list = ['x']
        unknown_list = ['obj', 'con1', 'con2']

        Jbase = {}
        Jbase['con1'] = {}
        Jbase['con1']['x'] = -0.98061433
        Jbase['con1']['z'] = np.array([-9.61002285, -0.78449158])
        Jbase['con2'] = {}
        Jbase['con2']['x'] = 0.09692762
        Jbase['con2']['z'] = np.array([1.94989079, 1.0775421 ])
        Jbase['obj'] = {}
        Jbase['obj']['x'] = 2.98061392
        Jbase['obj']['z'] = np.array([9.61001155, 1.78448534])

        J = prob.calc_gradient(param_list, unknown_list, mode='fwd', return_format='dict')
        print(J)
        #for key1, val1 in Jbase.items():
            #for key2, val2 in val1.items():
                #assert_rel_error(self, J[key1][key2], val2, .00001)

        J = prob.calc_gradient(param_list, unknown_list, mode='rev', return_format='dict')
        print(J)
        #for key1, val1 in Jbase.items():
            #for key2, val2 in val1.items():
                #assert_rel_error(self, J[key1][key2], val2, .00001)

        prob.root.fd_options['form'] = 'central'
        J = prob.calc_gradient(param_list, unknown_list, mode='fd', return_format='dict')
        print(J)
예제 #23
0
    def test_full_model_fd_simple_comp_promoted(self):

        prob = Problem()
        prob.root = Group()
        sub = prob.root.add('sub', Group(), promotes=['*'])
        sub.add('comp', SimpleCompDerivMatVec(), promotes=['*'])
        prob.root.add('p1', ParamComp('x', 1.0), promotes=['*'])

        prob.root.fd_options['force_fd'] = True

        prob.setup(check=False)
        prob.run()

        param_list = ['x']
        unknown_list = ['y']

        J = prob.calc_gradient(param_list, unknown_list, mode='fwd', return_format='dict')
        assert_rel_error(self, J['y']['x'][0][0], 2.0, 1e-6)
예제 #24
0
    def test_no_derivatives(self):

        prob = Problem()
        prob.root = Group()
        comp = prob.root.add('comp', ExecComp('y=x*2.0'))
        prob.root.add('p1', ParamComp('x', 2.0))
        prob.root.connect('p1.x', 'comp.x')

        comp.fd_options['force_fd'] = True

        prob.setup(check=False)
        prob.run()

        J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='fwd', return_format='dict')
        assert_rel_error(self, J['comp.y']['p1.x'][0][0], 2.0, 1e-6)

        J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='rev', return_format='dict')
        assert_rel_error(self, J['comp.y']['p1.x'][0][0], 2.0, 1e-6)
예제 #25
0
    def test_full_model_fd_double_diamond_grouped(self):

        prob = Problem()
        prob.root = ConvergeDivergeGroups()
        prob.setup(check=False)
        prob.run()

        prob.root.fd_options['force_fd'] = True

        param_list = ['sub1.comp1.x1']
        unknown_list = ['comp7.y1']

        J = prob.calc_gradient(param_list, unknown_list, mode='fwd', return_format='dict')
        assert_rel_error(self, J['comp7.y1']['sub1.comp1.x1'][0][0], -40.75, 1e-6)

        prob.root.fd_options['form'] = 'central'
        J = prob.calc_gradient(param_list, unknown_list, mode='fwd', return_format='dict')
        assert_rel_error(self, J['comp7.y1']['sub1.comp1.x1'][0][0], -40.75, 1e-6)
예제 #26
0
    def assertDatasetEquals(self, expected, tolerance):
        # Close the file to ensure it is written to disk.
        self.recorder.out.close()
        self.recorder.out = None

        sentinel = object()

        f = shelve.open(self.filename)

        order = f['order']
        del f['order']

        for coord, expect in expected:
            iter_coord = format_iteration_coordinate(coord)

            self.assertEqual(order.pop(0), iter_coord)

            groupings = (
                ("Parameters", expect[0]),
                ("Unknowns", expect[1]),
                ("Residuals", expect[2])
            )

            actual_group = f[iter_coord]

            for label, values in groupings:
                actual = actual_group[label]
                # If len(actual) == len(expected) and actual <= expected, then
                # actual == expected.
                self.assertEqual(len(actual), len(values))
                for key, val in values:
                    found_val = actual.get(key, sentinel)
                    if found_val is sentinel:
                        self.fail("Did not find key '{0}'".format(key))
                    assert_rel_error(self, found_val, val, tolerance)
            del f[iter_coord]

        # Having deleted all found values, the file should now be empty.
        self.assertEqual(len(f), 0)

        # As should the ordering.
        self.assertEqual(len(order), 0)

        f.close()
예제 #27
0
    def test_array2D(self):
        group = Group()
        group.add('x_param', ParamComp('x', np.ones((2, 2))), promotes=['*'])
        group.add('mycomp', ArrayComp2D(), promotes=['x', 'y'])

        prob = Problem()
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.setup(check=False)
        prob.run()

        J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')
        Jbase = prob.root.mycomp._jacobian_cache
        diff = np.linalg.norm(J['y']['x'] - Jbase['y', 'x'])
        assert_rel_error(self, diff, 0.0, 1e-8)

        J = prob.calc_gradient(['x'], ['y'], mode='rev', return_format='dict')
        diff = np.linalg.norm(J['y']['x'] - Jbase['y', 'x'])
        assert_rel_error(self, diff, 0.0, 1e-8)
예제 #28
0
    def assertDatasetEquals(self, expected, tolerance):
        for coord, expect in expected:
            icoord = format_iteration_coordinate(coord)

            f = self.recorder.out[icoord]
            params = f['Parameters']
            unknowns = f['Unknowns']
            resids = f['Residuals']

            sentinel = object()

            # If len(actual) == len(expected) and actual <= expected, then
            # actual == expected.
            for actual, exp in zip((params, unknowns, resids), expect):
                self.assertEqual(len(actual), len(exp))
                for key, val in exp:
                    found_val = actual.get(key, sentinel)
                    if found_val is sentinel:
                        self.fail("Did not find key '{0}'.".format(key))
                    assert_rel_error(self, found_val[()], val, tolerance)
예제 #29
0
    def test_two_simple(self):
        group = Group()
        group.add('x_param', ParamComp('x', 1.0))
        group.add('comp1', ExecComp(['y=2.0*x']))
        group.add('comp2', ExecComp(['z=3.0*y']))

        prob = Problem()
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.connect('x_param.x', 'comp1.x')
        prob.root.connect('comp1.y', 'comp2.y')

        prob.setup(check=False)
        prob.run()

        J = prob.calc_gradient(['x_param.x'], ['comp2.z'], mode='fwd', return_format='dict')
        assert_rel_error(self, J['comp2.z']['x_param.x'][0][0], 6.0, 1e-6)

        J = prob.calc_gradient(['x_param.x'], ['comp2.z'], mode='rev', return_format='dict')
        assert_rel_error(self, J['comp2.z']['x_param.x'][0][0], 6.0, 1e-6)
예제 #30
0
    def test_fan_out(self):

        prob = Problem()
        root = prob.root = Group()

        root.add('p1', ParamComp('x', 1.0))
        root.add('p2', ParamComp('x', 1.0))

        root.add('comp1', ExecComp('y = 3.0*x'))
        root.add('comp2', ExecComp('y = 5.0*x'))

        root.add('obj', ExecComp('o = i1 + i2'))
        root.add('con1', ExecComp('c = 15.0 - x'))
        root.add('con2', ExecComp('c = 15.0 - x'))

        # hook up non explicitly
        root.connect('p1.x', 'comp1.x')
        root.connect('p2.x', 'comp2.x')
        root.connect('comp1.y', 'obj.i1')
        root.connect('comp2.y', 'obj.i2')
        root.connect('comp1.y', 'con1.x')
        root.connect('comp2.y', 'con2.x')

        prob.driver = pyOptSparseDriver()
        prob.driver.add_param('p1.x', low=-50.0, high=50.0)
        prob.driver.add_param('p2.x', low=-50.0, high=50.0)
        prob.driver.add_objective('obj.o')
        prob.driver.add_constraint('con1.c', ctype='eq')
        prob.driver.add_constraint('con2.c', ctype='eq')

        prob.setup(check=False)
        prob.run()

        obj = prob['obj.o']
        assert_rel_error(self, obj, 30.0, 1e-6)

        # Verify that pyOpt has the correct wrt names
        con1 = prob.driver.pyopt_solution.constraints['con1.c']
        self.assertEqual(con1.wrt, ['p1.x'])
        con2 = prob.driver.pyopt_solution.constraints['con2.c']
        self.assertEqual(con2.wrt, ['p2.x'])