Example #1
0
    def test_derivatives(self):
        meta = MetaModel()
        meta.add_param('x', 0.)
        meta.add_output('f', 0.)
        meta.default_surrogate = FloatKrigingSurrogate()

        prob = Problem(Group())
        prob.root.add('meta', meta, promotes=['x'])
        prob.root.add('p', IndepVarComp('x', 0.), promotes=['x'])
        prob.setup(check=False)

        prob['meta.train:x'] = [0., .25, .5, .75, 1.]
        prob['meta.train:f'] = [1., .75, .5, .25, 0.]
        prob['x'] = 0.125
        prob.run()

        Jf = prob.calc_gradient(['x'], ['meta.f'], mode='fwd')
        Jr = prob.calc_gradient(['x'], ['meta.f'], mode='rev')

        assert_rel_error(self, Jf[0][0], -1., 1.e-5)
        assert_rel_error(self, Jr[0][0], -1., 1.e-5)

        stream = cStringIO()
        prob.check_partial_derivatives(out_stream=stream, global_options={'check_type': 'cs'})

        abs_errors = findall('Absolute Error \(.+\) : (.+)', stream.getvalue())
        self.assertTrue(len(abs_errors) > 0)
        for match in abs_errors:
            abs_error = float(match)
            self.assertTrue(abs_error < 1.e-6)
Example #2
0
    def test_derivatives(self):
        meta = MetaModel()
        meta.add_param('x', 0.)
        meta.add_output('f', 0.)
        meta.default_surrogate = FloatKrigingSurrogate()

        prob = Problem(Group())
        prob.root.add('meta', meta, promotes=['x'])
        prob.root.add('p', IndepVarComp('x', 0.), promotes=['x'])
        prob.setup(check=False)

        prob['meta.train:x'] = [0., .25, .5, .75, 1.]
        prob['meta.train:f'] = [1., .75, .5, .25, 0.]
        prob['x'] = 0.125
        prob.run()

        Jf = prob.calc_gradient(['x'], ['meta.f'], mode='fwd')
        Jr = prob.calc_gradient(['x'], ['meta.f'], mode='rev')

        assert_rel_error(self, Jf[0][0], -1., 1.e-5)
        assert_rel_error(self, Jr[0][0], -1., 1.e-5)

        stream = cStringIO()
        prob.check_partial_derivatives(out_stream=stream,
                                       global_options={'check_type': 'cs'})

        abs_errors = findall('Absolute Error \(.+\) : (.+)', stream.getvalue())
        self.assertTrue(len(abs_errors) > 0)
        for match in abs_errors:
            abs_error = float(match)
            self.assertTrue(abs_error < 1.e-6)
    def test_overrides(self):

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SimpleImplicitComp())
        prob.root.add('p1', IndepVarComp('x', 0.5))

        prob.root.connect('p1.x', 'comp.x')
        prob.root.comp.deriv_options['check_type'] = 'fd'
        prob.root.comp.deriv_options['check_step_size'] = 1e25

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

        # This should override the bad stepsize.
        opts = {'check_step_size' : 1e-6}
        mystream = StringIO()
        data = prob.check_partial_derivatives(out_stream=mystream, global_options=opts)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SimpleImplicitComp())
        prob.root.add('p1', IndepVarComp('x', 0.5))

        prob.root.connect('p1.x', 'comp.x')
        prob.root.comp.deriv_options['check_type'] = 'fd'
        prob.root.comp.deriv_options['check_step_size'] = 1e25

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

        mystream = StringIO()
        opts = {'check_form' : 'central'}
        data = prob.check_partial_derivatives(out_stream=mystream, global_options=opts,
                                              compact_print=True)
        text = mystream.getvalue()
        self.assertTrue('fd:central' in text)
        self.assertTrue('complex_step' not in text)

        mystream = StringIO()
        opts = {'check_type' : 'cs'}
        data = prob.check_partial_derivatives(out_stream=mystream, global_options=opts,
                                              compact_print=True)
        text = mystream.getvalue()
        self.assertTrue('fd:central' not in text)
        self.assertTrue('complex step' in text)
Example #4
0
    def test_check_derivs_param(self):
        class Comp(Component):
            def __init__(self):
                super(Comp, self).__init__()
                self.add_param('x', val=0.0)
                self.add_param('y', val=3, pass_by_obj=True)
                self.add_output('z', val=0.0)

            def solve_nonlinear(self, params, unknowns, resids):
                unknowns['z'] = params['y'] * params['x']

            def linearize(self, params, unknowns, resids):
                J = {}
                J['z', 'x'] = params['y']
                return J

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', Comp(), promotes=['*'])
        prob.root.add('p1', IndepVarComp('x', 0.0), promotes=['x'])
        prob.root.add('p2',
                      IndepVarComp('y', 3, pass_by_obj=True),
                      promotes=['y'])

        prob.setup(check=False)

        prob.run()

        data = prob.check_partial_derivatives(out_stream=None)
        self.assertEqual(data['comp'][('z', 'x')]['J_fwd'][0][0], 3.0)

        data = prob.check_total_derivatives(out_stream=None)
        self.assertEqual(data[('z', 'x')]['J_fwd'][0][0], 3.0)
    def test_simple_implicit_complex_step(self):

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add("comp", SimpleImplicitComp())
        prob.root.add("p1", IndepVarComp("x", 0.5))

        prob.root.connect("p1.x", "comp.x")

        prob.root.comp.fd_options["step_size"] = 1.0e4
        prob.root.comp.fd_options["form"] = "complex_step"

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2["abs error"][0], 0.0, 1e-5)
                assert_rel_error(self, val2["abs error"][1], 0.0, 1e-5)
                assert_rel_error(self, val2["abs error"][2], 0.0, 1e-5)
                assert_rel_error(self, val2["rel error"][0], 0.0, 1e-5)
                assert_rel_error(self, val2["rel error"][1], 0.0, 1e-5)
                assert_rel_error(self, val2["rel error"][2], 0.0, 1e-5)
    def test_check_partials_calls_run_once(self):
        prob = Problem()
        root = prob.root = Group()
        root.add('p1', IndepVarComp('x', 1.0), promotes=['*'])
        root.add('p2', IndepVarComp('y', 1.0), promotes=['*'])
        root.add('comp', Paraboloid(), promotes=['*'])

        prob.driver.add_desvar('x')
        prob.driver.add_desvar('y')
        prob.driver.add_objective('f_xy')

        prob.setup(check=False)

        prob['x'] = 5.0
        prob['y'] = 2.0

        iostream = StringIO()

        data = prob.check_partial_derivatives(out_stream=iostream)

        self.assertAlmostEqual(first=prob["f_xy"],
                               second= (prob['x']-3.0)**2 \
                                       + prob['x']*prob['y'] \
                                       + (prob['y']+4.0)**2 - 3.0,
                               places=5,
                               msg="check partial derivatives did not call"
                                   "run_once on the driver as expected.")

        self.assertEqual(
            first=iostream.getvalue()[:39],
            second="Executing model to populate unknowns...",
            msg="check partial derivatives failed to run driver once")
    def test_double_diamond_model_complex_step(self):

        prob = Problem()
        prob.root = ConvergeDivergeGroups()

        prob.root.sub1.comp1.fd_options['form'] = 'complex_step'
        prob.root.sub1.sub2.comp2.fd_options['form'] = 'complex_step'
        prob.root.sub1.sub2.comp3.fd_options['form'] = 'complex_step'
        prob.root.sub1.comp4.fd_options['form'] = 'complex_step'
        prob.root.sub3.comp5.fd_options['form'] = 'complex_step'
        prob.root.sub3.comp6.fd_options['form'] = 'complex_step'
        prob.root.comp7.fd_options['form'] = 'complex_step'

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
    def test_extra_fd(self):

        class CSTestComp(Component):

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

                self.add_param('x', val=1.5, step_size=1e-2) # pick a big step to make sure FD sucks
                self.add_output('f', val=0.)

            def solve_nonlinear(self, p, u, r):
                x = p['x']
                u['f'] = np.exp(x)/np.sqrt(np.sin(x)**3 + np.cos(x)**3)

        p = Problem()
        p.root = Group()

        p.root.add('des_vars', IndepVarComp('x', 1.5), promotes=['*'])
        c = p.root.add('comp', CSTestComp(), promotes=["*"])
        c.fd_options['force_fd'] = True
        c.fd_options['form'] = "complex_step"
        c.fd_options['extra_check_partials_form'] = "forward"

        p.setup(check=False)
        p.run_once()

        check_data = p.check_partial_derivatives(out_stream=None)
        cs_val = check_data['comp']['f','x']['J_fd'][0,0] # should be the complex steped value!
        assert_rel_error(self, cs_val, 4.05289181447, 1e-8)

        fd2_val = check_data['comp']['f','x']['J_fd2'][0,0] # should be the real-fd'd value!
        assert_rel_error(self, fd2_val, 4.10128351131, 1e-8)
Example #9
0
    def test_check_derivs_param(self):

        class Comp(Component):
            def __init__(self):
                super(Comp, self).__init__()
                self.add_param('x', val=0.0)
                self.add_param('y', val=3, pass_by_obj=True)
                self.add_output('z', val=0.0)

            def solve_nonlinear(self, params, unknowns, resids):
                unknowns['z'] = params['y']*params['x']

            def linearize(self, params, unknowns, resids):
                J = {}
                J['z', 'x'] = params['y']
                return J

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', Comp(), promotes=['*'])
        prob.root.add('p1', IndepVarComp('x', 0.0), promotes=['x'])
        prob.root.add('p2', IndepVarComp('y', 3, pass_by_obj=True), promotes=['y'])

        prob.setup(check=False)

        prob.run()

        data = prob.check_partial_derivatives(out_stream=None)
        self.assertEqual(data['comp'][('z', 'x')]['J_fwd'][0][0], 3.0)

        data = prob.check_total_derivatives(out_stream=None)
        self.assertEqual(data[('z', 'x')]['J_fwd'][0][0], 3.0)
    def test_simple_implicit_run_once(self):
        class SIC2(SimpleImplicitComp):
            def solve_nonlinear(self, params, unknowns, resids):
                """ Simple iterative solve. (Babylonian method)."""

                super(SIC2, self).solve_nonlinear(params, unknowns, resids)

                # This mimics a problem with residuals that aren't up-to-date
                # with the solve
                resids['z'] = 999.999

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SIC2())
        prob.root.add('p1', IndepVarComp('x', 0.5))

        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
Example #11
0
    def test_problem_deriv_test(self):

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', SimpleCompWrongDeriv())
        prob.root.add('p1', IndepVarComp('x', 2.0))
        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        # suppress printed output from problem_derivatives_check()
        sysout = sys.stdout
        devnull = open(os.devnull, 'w')

        try:
            sys.stdout = devnull
            problem_derivatives_check(self, prob)
        except AssertionError as err:
            sys.stdout = sysout
            self.assertIn("not less than or equal to 1e-05", err.args[0])
        finally:
            sys.stdout = sysout
Example #12
0
    def test_simple_array_model2_colons(self):
        prob = Problem()
        prob.root = Group()
        comp = prob.root.add(
            'comp',
            ExecComp('foo:y = foo:mat.dot(x)',
                     inits={
                         'foo:y': np.zeros((2, )),
                         'foo:mat': np.array([[2., 7.], [5., -3.]])
                     },
                     x=np.zeros((2, ))))

        p1 = prob.root.add('p1', IndepVarComp('x', np.ones([2])))

        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        assert_rel_error(self, data['comp'][('foo:y', 'x')]['abs error'][0],
                         0.0, 1e-5)
        assert_rel_error(self, data['comp'][('foo:y', 'x')]['abs error'][1],
                         0.0, 1e-5)
        assert_rel_error(self, data['comp'][('foo:y', 'x')]['abs error'][2],
                         0.0, 1e-5)
        assert_rel_error(self, data['comp'][('foo:y', 'x')]['rel error'][0],
                         0.0, 1e-5)
        assert_rel_error(self, data['comp'][('foo:y', 'x')]['rel error'][1],
                         0.0, 1e-5)
        assert_rel_error(self, data['comp'][('foo:y', 'x')]['rel error'][2],
                         0.0, 1e-5)
    def test_simple_implicit_run_once(self):

        class SIC2(SimpleImplicitComp):

            def solve_nonlinear(self, params, unknowns, resids):
                """ Simple iterative solve. (Babylonian method)."""

                super(SIC2, self).solve_nonlinear(params, unknowns, resids)

                # This mimics a problem with residuals that aren't up-to-date
                # with the solve
                resids['z'] = 999.999


        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SIC2())
        prob.root.add('p1', IndepVarComp('x', 0.5))

        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
Example #14
0
    def test_simple_array_model(self):
        prob = Problem()
        prob.root = Group()
        prob.root.add(
            'comp',
            ExecComp(['y[0]=2.0*x[0]+7.0*x[1]', 'y[1]=5.0*x[0]-3.0*x[1]'],
                     x=np.zeros([2]),
                     y=np.zeros([2])))

        prob.root.add('p1', IndepVarComp('x', np.ones([2])))

        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][0], 0.0,
                         1e-5)
        assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][1], 0.0,
                         1e-5)
        assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][2], 0.0,
                         1e-5)
        assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][0], 0.0,
                         1e-5)
        assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][1], 0.0,
                         1e-5)
        assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][2], 0.0,
                         1e-5)
    def test_bad_size(self):
        class BadComp(SimpleArrayComp):
            def linearize(self, params, unknowns, resids):
                """Analytical derivatives"""
                J = {}
                J[('y', 'x')] = np.zeros((3, 3))
                return J

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', BadComp())
        prob.root.add('p1', IndepVarComp('x', np.ones([2])))

        prob.root.connect('p1.x', 'comp.x')

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

        try:
            data = prob.check_partial_derivatives(out_stream=None)
        except Exception as err:
            msg = "derivative in component 'comp' of 'y' wrt 'x' is the wrong size. It should be (2, 2), but got (3, 3)"

            # Good ole Numpy
            raised_error = str(err)
            raised_error = raised_error.replace('3L', '3')

            self.assertEqual(raised_error, msg)
        else:
            self.fail("Error expected")
    def test_simple_implicit_complex_step(self):

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SimpleImplicitComp())
        prob.root.add('p1', IndepVarComp('x', 0.5))

        prob.root.connect('p1.x', 'comp.x')

        prob.root.comp.fd_options['step_size'] = 1.0e4
        prob.root.comp.fd_options['form'] = 'complex_step'

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
    def test_check_partials_calls_run_once(self):
        prob = Problem()
        root = prob.root = Group()
        root.add('p1', IndepVarComp('x', 1.0), promotes=['*'])
        root.add('p2', IndepVarComp('y', 1.0), promotes=['*'])
        root.add('comp', Paraboloid(), promotes=['*'])

        prob.driver.add_desvar('x')
        prob.driver.add_desvar('y')
        prob.driver.add_objective('f_xy')

        prob.setup(check=False)

        prob['x'] = 5.0
        prob['y'] = 2.0

        iostream = StringIO()

        data = prob.check_partial_derivatives(out_stream=iostream)

        self.assertAlmostEqual(first=prob["f_xy"],
                               second= (prob['x']-3.0)**2 \
                                       + prob['x']*prob['y'] \
                                       + (prob['y']+4.0)**2 - 3.0,
                               places=5,
                               msg="check partial derivatives did not call"
                                   "run_once on the driver as expected.")

        self.assertEqual(first=iostream.getvalue()[:39],
                         second="Executing model to populate unknowns...",
                         msg="check partial derivatives failed to run driver once")
    def test_bad_size(self):

        class BadComp(SimpleArrayComp):
            def linearize(self, params, unknowns, resids):
                """Analytical derivatives"""
                J = {}
                J[('y', 'x')] = np.zeros((3, 3))
                return J


        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', BadComp())
        prob.root.add('p1', IndepVarComp('x', np.ones([2])))

        prob.root.connect('p1.x', 'comp.x')

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

        try:
            data = prob.check_partial_derivatives(out_stream=None)
        except Exception as err:
            msg = "derivative in component 'comp' of 'y' wrt 'x' is the wrong size. It should be (2, 2), but got (3, 3)"

            # Good ole Numpy
            raised_error = str(err)
            raised_error = raised_error.replace('3L', '3')

            self.assertEqual(raised_error, msg)
        else:
            self.fail("Error expected")
    def test_message_no_connections(self):

        p = Problem()
        p.root = Group()

        c = p.root.add('comp', Paraboloid())

        p.setup(check=False)
        p.run_once()

        mystream = StringIO()
        p.check_partial_derivatives(out_stream=mystream)

        text = mystream.getvalue()
        expected = 'Skipping because component has no connected inputs.'
        self.assertTrue(expected in text)
    def test_double_diamond_model_complex_step(self):

        prob = Problem()
        prob.root = ConvergeDivergeGroups()

        prob.root.sub1.comp1.fd_options['form'] = 'complex_step'
        prob.root.sub1.sub2.comp2.fd_options['form'] = 'complex_step'
        prob.root.sub1.sub2.comp3.fd_options['form'] = 'complex_step'
        prob.root.sub1.comp4.fd_options['form'] = 'complex_step'
        prob.root.sub3.comp5.fd_options['form'] = 'complex_step'
        prob.root.sub3.comp6.fd_options['form'] = 'complex_step'
        prob.root.comp7.fd_options['form'] = 'complex_step'

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
    def test_simple_implicit_complex_step(self):

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SimpleImplicitComp())
        prob.root.add('p1', IndepVarComp('x', 0.5))

        prob.root.connect('p1.x', 'comp.x')

        prob.root.comp.fd_options['step_size'] = 1.0e4
        prob.root.comp.fd_options['form'] = 'complex_step'

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
Example #22
0
    def test_simple_array_model2(self):
        raise unittest.SkipTest("no check_partial_derivatives function")
        prob = Problem()
        prob.root = Group()
        comp = prob.root.add_subsystem(
            'comp',
            ExecComp('y = mat.dot(x)',
                     x=np.zeros((2, )),
                     y=np.zeros((2, )),
                     mat=np.array([[2., 7.], [5., -3.]])))

        p1 = prob.root.add_subsystem('p1', IndepVarComp('x', np.ones([2])))

        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][0], 0.0,
                         1e-5)
        assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][1], 0.0,
                         1e-5)
        assert_rel_error(self, data['comp'][('y', 'x')]['abs error'][2], 0.0,
                         1e-5)
        assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][0], 0.0,
                         1e-5)
        assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][1], 0.0,
                         1e-5)
        assert_rel_error(self, data['comp'][('y', 'x')]['rel error'][2], 0.0,
                         1e-5)
Example #23
0
    def test_problem_deriv_test(self):

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', SimpleCompWrongDeriv())
        prob.root.add('p1', IndepVarComp('x', 2.0))
        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        # suppress printed output from problem_derivatives_check()
        sysout = sys.stdout
        devnull = open(os.devnull, 'w')

        try:
            sys.stdout = devnull
            problem_derivatives_check(self, prob)
        except AssertionError as err:
            sys.stdout = sysout
            self.assertIn("not less than or equal to 1e-05", err.args[0])
        finally:
            sys.stdout = sysout
    def test_simple_implicit(self):

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add('comp', SimpleImplicitComp())
        prob.root.add('p1', IndepVarComp('x', 0.5))

        prob.root.connect('p1.x', 'comp.x')

        prob.root.comp.deriv_options['check_type'] = 'cs'

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

        # Correct total derivatives (we can do this one manually)
        J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='fwd')
        assert_rel_error(self, J[0][0], -2.5555511, 1e-5)

        J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='rev')
        assert_rel_error(self, J[0][0], -2.5555511, 1e-5)

        J = prob.calc_gradient(['p1.x'], ['comp.y'], mode='fd')
        assert_rel_error(self, J[0][0], -2.5555511, 1e-5)

        # Clean up old FD
        prob.run()

        # Partials
        data = prob.check_partial_derivatives(out_stream=None)
        #data = prob.check_partial_derivatives()

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)

        assert_rel_error(self, data['comp'][('y', 'x')]['J_fwd'][0][0], 1.0, 1e-6)
        assert_rel_error(self, data['comp'][('y', 'z')]['J_fwd'][0][0], 2.0, 1e-6)
        assert_rel_error(self, data['comp'][('z', 'x')]['J_fwd'][0][0], 2.66666667, 1e-6)
        assert_rel_error(self, data['comp'][('z', 'z')]['J_fwd'][0][0], 1.5, 1e-6)

        # Clean up old FD
        prob.run()

        # Make sure check_totals works too
        data = prob.check_total_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            assert_rel_error(self, val1['abs error'][0], 0.0, 1e-5)
            assert_rel_error(self, val1['abs error'][1], 0.0, 1e-5)
            assert_rel_error(self, val1['abs error'][2], 0.0, 1e-5)
            assert_rel_error(self, val1['rel error'][0], 0.0, 1e-5)
            assert_rel_error(self, val1['rel error'][1], 0.0, 1e-5)
            assert_rel_error(self, val1['rel error'][2], 0.0, 1e-5)
Example #25
0
    def test_simple_implicit(self):

        prob = Problem()
        prob.root = Group()
        prob.root.ln_solver = ScipyGMRES()
        prob.root.add("comp", SimpleImplicitComp())
        prob.root.add("p1", IndepVarComp("x", 0.5))

        prob.root.connect("p1.x", "comp.x")

        prob.root.comp.fd_options["extra_check_partials_form"] = "complex_step"

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

        # Correct total derivatives (we can do this one manually)
        J = prob.calc_gradient(["p1.x"], ["comp.y"], mode="fwd")
        assert_rel_error(self, J[0][0], -2.5555511, 1e-5)

        J = prob.calc_gradient(["p1.x"], ["comp.y"], mode="rev")
        assert_rel_error(self, J[0][0], -2.5555511, 1e-5)

        J = prob.calc_gradient(["p1.x"], ["comp.y"], mode="fd")
        assert_rel_error(self, J[0][0], -2.5555511, 1e-5)

        # Clean up old FD
        prob.run()

        # Partials
        data = prob.check_partial_derivatives(out_stream=None)
        # data = prob.check_partial_derivatives()

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2["abs error"][0], 0.0, 1e-5)
                assert_rel_error(self, val2["abs error"][1], 0.0, 1e-5)
                assert_rel_error(self, val2["abs error"][2], 0.0, 1e-5)
                assert_rel_error(self, val2["rel error"][0], 0.0, 1e-5)
                assert_rel_error(self, val2["rel error"][1], 0.0, 1e-5)
                assert_rel_error(self, val2["rel error"][2], 0.0, 1e-5)

        assert_rel_error(self, data["comp"][("y", "x")]["J_fwd"][0][0], 1.0, 1e-6)
        assert_rel_error(self, data["comp"][("y", "z")]["J_fwd"][0][0], 20.0, 1e-6)
        assert_rel_error(self, data["comp"][("z", "x")]["J_fwd"][0][0], 2.66666667, 1e-6)
        assert_rel_error(self, data["comp"][("z", "z")]["J_fwd"][0][0], 15.0, 1e-6)

        # Clean up old FD
        prob.run()

        # Make sure check_totals works too
        data = prob.check_total_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            assert_rel_error(self, val1["abs error"][0], 0.0, 1e-5)
            assert_rel_error(self, val1["abs error"][1], 0.0, 1e-5)
            assert_rel_error(self, val1["abs error"][2], 0.0, 1e-5)
            assert_rel_error(self, val1["rel error"][0], 0.0, 1e-5)
            assert_rel_error(self, val1["rel error"][1], 0.0, 1e-5)
            assert_rel_error(self, val1["rel error"][2], 0.0, 1e-5)
    def test_double_diamond_model(self):

        prob = Problem()
        prob.root = ConvergeDivergeGroups()

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)

        self.assertEqual(len(data), 7)

        # Piggyback a test for the 'comps' option.

        data = prob.check_partial_derivatives(out_stream=None,
                                              comps=['sub1.sub2.comp3', 'comp7'])
        self.assertEqual(len(data), 2)
        self.assertTrue('sub1.sub2.comp3' in data)
        self.assertTrue('comp7' in data)

        with self.assertRaises(RuntimeError) as cm:
            data = prob.check_partial_derivatives(out_stream=None,
                                                  comps=['sub1', 'bogus'])

        expected_msg = "The following are not valid comp names: ['bogus', 'sub1']"
        self.assertEqual(str(cm.exception), expected_msg)

        # This is a good test to piggyback the compact_print test

        mystream = StringIO()
        prob.check_partial_derivatives(out_stream=mystream,
                                       compact_print=True)

        text = mystream.getvalue()
        expected = "'y1'            wrt 'x1'            | 8.0000e+00 | 8.0000e+00 |  8.0000e+00 | 2.0013e-06 | 2.0013e-06 | 2.5016e-07 | 2.5016e-07"
        self.assertTrue(expected in text)
    def test_double_diamond_model(self):

        prob = Problem()
        prob.root = ConvergeDivergeGroups()

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)

        self.assertEqual(len(data), 7)

        # Piggyback a test for the 'comps' option.

        data = prob.check_partial_derivatives(out_stream=None,
                                              comps=['sub1.sub2.comp3', 'comp7'])
        self.assertEqual(len(data), 2)
        self.assertTrue('sub1.sub2.comp3' in data)
        self.assertTrue('comp7' in data)

        with self.assertRaises(RuntimeError) as cm:
            data = prob.check_partial_derivatives(out_stream=None,
                                                  comps=['sub1', 'bogus'])

        expected_msg = "The following are not valid comp names: ['bogus', 'sub1']"
        self.assertEqual(str(cm.exception), expected_msg)

        # This is a good test to piggyback the compact_print test

        mystream = StringIO()
        prob.check_partial_derivatives(out_stream=mystream,
                                       compact_print=True)

        text = mystream.getvalue()
        expected = "'y1'            wrt 'x1'            | 8.0000e+00 | 8.0000e+00 |  8.0000e+00 | 2.0013e-06 | 2.0013e-06 | 2.5016e-07 | 2.5016e-07"
        self.assertTrue(expected in text)
Example #28
0
    def test_check_derivs_unknowns(self):

        class Comp1(Component):
            def __init__(self):
                super(Comp1, self).__init__()
                self.add_param('x', shape=1)
                self.add_output('y', shape=1)
                self.add_output('dz_dy', shape=1, pass_by_obj=True)

            def solve_nonlinear(self, params, unknowns, resids):
                x = params['x']
                unknowns['y'] = 4.0*x + 1.0
                unknowns['dz_dy'] = 2.0

            def linearize(self, params, unknowns, resids):
                J = {}
                J['y', 'x'] = 4.0
                return J

        class Comp2(Component):
            def __init__(self):
                super(Comp2, self).__init__()
                self.add_param('y', shape=1)
                self.add_param('dz_dy', shape=1, pass_by_obj=True)
                self.add_output('z', shape=1)

            def solve_nonlinear(self, params, unknowns, resids):
                y = params['y']
                unknowns['z'] = y*2.0

            def linearize(self, params, unknowns, resids):
                J = {}
                J['z', 'y'] = params['dz_dy']
                return J

        class TestGroup(Group):
            def __init__(self):
                super(TestGroup, self).__init__()
                self.add('x', IndepVarComp('x', 0.0), promotes=['*'])
                self.add('c1', Comp1(), promotes=['*'])
                self.add('c2', Comp2(), promotes=['*'])

        prob = Problem()
        prob.root = TestGroup()
        prob.setup(check=False)

        prob['x'] = 2.0
        prob.run()

        data = prob.check_partial_derivatives(out_stream=None)
        self.assertEqual(data['c1'][('y', 'x')]['J_fwd'][0][0], 4.0)
        self.assertEqual(data['c1'][('y', 'x')]['J_rev'][0][0], 4.0)
        self.assertEqual(data['c2'][('z', 'y')]['J_fwd'][0][0], 2.0)
        self.assertEqual(data['c2'][('z', 'y')]['J_rev'][0][0], 2.0)

        data = prob.check_total_derivatives(out_stream=None)
        self.assertEqual(data[('z', 'x')]['J_fwd'][0][0], 8.0)
Example #29
0
    def test_check_derivs_unknowns(self):
        class Comp1(Component):
            def __init__(self):
                super(Comp1, self).__init__()
                self.add_param('x', shape=1)
                self.add_output('y', shape=1)
                self.add_output('dz_dy', shape=1, pass_by_obj=True)

            def solve_nonlinear(self, params, unknowns, resids):
                x = params['x']
                unknowns['y'] = 4.0 * x + 1.0
                unknowns['dz_dy'] = 2.0

            def linearize(self, params, unknowns, resids):
                J = {}
                J['y', 'x'] = 4.0
                return J

        class Comp2(Component):
            def __init__(self):
                super(Comp2, self).__init__()
                self.add_param('y', shape=1)
                self.add_param('dz_dy', shape=1, pass_by_obj=True)
                self.add_output('z', shape=1)

            def solve_nonlinear(self, params, unknowns, resids):
                y = params['y']
                unknowns['z'] = y * 2.0

            def linearize(self, params, unknowns, resids):
                J = {}
                J['z', 'y'] = params['dz_dy']
                return J

        class TestGroup(Group):
            def __init__(self):
                super(TestGroup, self).__init__()
                self.add('x', IndepVarComp('x', 0.0), promotes=['*'])
                self.add('c1', Comp1(), promotes=['*'])
                self.add('c2', Comp2(), promotes=['*'])

        prob = Problem()
        prob.root = TestGroup()
        prob.setup(check=False)

        prob['x'] = 2.0
        prob.run()

        data = prob.check_partial_derivatives(out_stream=None)
        self.assertEqual(data['c1'][('y', 'x')]['J_fwd'][0][0], 4.0)
        self.assertEqual(data['c1'][('y', 'x')]['J_rev'][0][0], 4.0)
        self.assertEqual(data['c2'][('z', 'y')]['J_fwd'][0][0], 2.0)
        self.assertEqual(data['c2'][('z', 'y')]['J_rev'][0][0], 2.0)

        data = prob.check_total_derivatives(out_stream=None)
        self.assertEqual(data[('z', 'x')]['J_fwd'][0][0], 8.0)
    def test_extra_fd(self):
        class CSTestComp(Component):
            def __init__(self):
                super(CSTestComp, self).__init__()

                self.add_param(
                    'x', val=1.5,
                    step_size=1e-2)  # pick a big step to make sure FD sucks
                self.add_output('f', val=0.)

            def solve_nonlinear(self, p, u, r):
                x = p['x']
                u['f'] = np.exp(x) / np.sqrt(np.sin(x)**3 + np.cos(x)**3)

        p = Problem()
        p.root = Group()

        p.root.add('des_vars', IndepVarComp('x', 1.5), promotes=['*'])
        c = p.root.add('comp', CSTestComp(), promotes=["*"])
        c.fd_options['force_fd'] = True
        c.fd_options['form'] = "complex_step"
        c.fd_options['extra_check_partials_form'] = "forward"

        p.setup(check=False)
        p.run_once()

        check_data = p.check_partial_derivatives(out_stream=None)
        cs_val = check_data['comp']['f', 'x']['J_fd'][
            0, 0]  # should be the complex steped value!
        assert_rel_error(self, cs_val, 4.05289181447, 1e-8)

        fd2_val = check_data['comp']['f', 'x']['J_fd2'][
            0, 0]  # should be the real-fd'd value!
        assert_rel_error(self, fd2_val, 4.10128351131, 1e-8)

        # For coverage

        mystream = StringIO()
        p.check_partial_derivatives(out_stream=mystream, compact_print=True)

        text = mystream.getvalue()
        expected = "'f'             wrt 'x'             |  4.052892e+00 | 4.101284e+00 |  4.839170e-02 |  1.194004e-02"
        self.assertTrue(expected in text)
Example #31
0
    def test_basic_gmres(self):
        top = Problem()
        root = top.root = Group()
        root.add("p", IndepVarComp("x", 2000.0))
        root.add("comp1", BasicComp())
        root.add("comp2", ExecComp(["y = 2.0*x"]))
        root.connect("p.x", "comp1.x")
        root.connect("comp1.y", "comp2.x")

        top.driver.add_desvar("p.x", 2000.0)
        top.driver.add_objective("comp2.y")

        root.ln_solver = ScipyGMRES()

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

        # correct execution
        assert_rel_error(self, top["comp2.y"], 12000.0, 1e-6)

        # in-component query is unscaled
        assert_rel_error(self, root.comp1.store_y, 6000.0, 1e-6)

        # afterwards direct query is unscaled
        assert_rel_error(self, root.unknowns["comp1.y"], 6000.0, 1e-6)

        # OpenMDAO behind-the-scenes query is scaled
        # (So, internal storage is scaled)
        assert_rel_error(self, root.unknowns._dat["comp1.y"].val, 6.0, 1e-6)

        # Correct derivatives
        J = top.calc_gradient(["p.x"], ["comp2.y"], mode="fwd")
        assert_rel_error(self, J[0][0], 6.0, 1e-6)

        J = top.calc_gradient(["p.x"], ["comp2.y"], mode="rev")
        assert_rel_error(self, J[0][0], 6.0, 1e-6)

        J = top.calc_gradient(["p.x"], ["comp2.y"], mode="fd")
        assert_rel_error(self, J[0][0], 6.0, 1e-6)

        # Clean up old FD
        top.run()

        # Make sure check_partials works too
        data = top.check_partial_derivatives(out_stream=None)
        # data = top.check_partial_derivatives()

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2["abs error"][0], 0.0, 1e-5)
                assert_rel_error(self, val2["abs error"][1], 0.0, 1e-5)
                assert_rel_error(self, val2["abs error"][2], 0.0, 1e-5)
                assert_rel_error(self, val2["rel error"][0], 0.0, 1e-5)
                assert_rel_error(self, val2["rel error"][1], 0.0, 1e-5)
                assert_rel_error(self, val2["rel error"][2], 0.0, 1e-5)
    def test_message_root_is_fd(self):

        p = Problem()
        p.root = Group()

        p.root.add('p1', IndepVarComp('x', 1.0))
        c = p.root.add('comp', Paraboloid())
        p.root.connect('p1.x', 'comp.x')

        p.root.deriv_options['type'] = 'fd'

        p.setup(check=False)

        with self.assertRaises(RuntimeError) as cm:
            p.check_partial_derivatives()

        msg = "You cannot run check_partial_derivatives when option 'type' "
        msg += "in `root` is set to 'fd' or 'cs' because no derivative "
        msg += "vectors are allocated in that case."
        self.assertEqual(str(cm.exception), msg)
    def test_message_check_types_are_same(self):

        p = Problem()
        p.root = Group()

        p.root.add('p1', IndepVarComp('x', 1.0))
        c = p.root.add('comp', Paraboloid())
        p.root.connect('p1.x', 'comp.x')

        p.root.comp.deriv_options['type'] = 'fd'
        p.root.comp.deriv_options['check_type'] = 'fd'

        p.setup(check=False)
        p.run_once()

        mystream = StringIO()
        p.check_partial_derivatives(out_stream=mystream)

        text = mystream.getvalue()
        expected = 'Skipping because type == check_type.'
        self.assertTrue(expected in text)
    def test_incorrect_jacobian(self):

        class MyComp(Component):

            def __init__(self, multiplier=2.0):
                super(MyComp, self).__init__()

                # Params
                self.add_param('x1', 3.0)
                self.add_param('x2', 5.0)

                # Unknowns
                self.add_output('y', 5.5)

            def solve_nonlinear(self, params, unknowns, resids):
                """ Doesn't do much. """
                unknowns['y'] = 3.0*params['x1'] + 4.0*params['x2']

            def linearize(self, params, unknowns, resids):
                """Intentionally incorrect derivative."""

                J = {}
                J['y', 'x1'] = np.array([4.0])
                J['y', 'x2'] = np.array([40])
                return J

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', MyComp())
        prob.root.add('p1', IndepVarComp('x1', 3.0))
        prob.root.add('p2', IndepVarComp('x2', 5.0))

        prob.root.connect('p1.x1', 'comp.x1')
        prob.root.connect('p2.x2', 'comp.x2')

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

        stringstream = StringIO()

        data = prob.check_partial_derivatives(out_stream=stringstream)

        lines = stringstream.getvalue().split("\n")

        y_wrt_x1_line = lines.index("  comp: 'y' wrt 'x1'")

        self.assertTrue(lines[y_wrt_x1_line+6].endswith('*'),
                        msg='Error flag expected in output but not displayed')
        self.assertTrue(lines[y_wrt_x1_line+7].endswith('*'),
                        msg='Error flag expected in output but not displayed')
        self.assertFalse(lines[y_wrt_x1_line+8].endswith('*'),
                        msg='Error flag not expected in output but displayed')
    def test_incorrect_jacobian(self):

        class MyComp(Component):

            def __init__(self, multiplier=2.0):
                super(MyComp, self).__init__()

                # Params
                self.add_param('x1', 3.0)
                self.add_param('x2', 5.0)

                # Unknowns
                self.add_output('y', 5.5)

            def solve_nonlinear(self, params, unknowns, resids):
                """ Doesn't do much. """
                unknowns['y'] = 3.0*params['x1'] + 4.0*params['x2']

            def linearize(self, params, unknowns, resids):
                """Intentionally incorrect derivative."""

                J = {}
                J['y', 'x1'] = np.array([4.0])
                J['y', 'x2'] = np.array([40])
                return J

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', MyComp())
        prob.root.add('p1', IndepVarComp('x1', 3.0))
        prob.root.add('p2', IndepVarComp('x2', 5.0))

        prob.root.connect('p1.x1', 'comp.x1')
        prob.root.connect('p2.x2', 'comp.x2')

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

        stringstream = StringIO()

        data = prob.check_partial_derivatives(out_stream=stringstream)

        lines = stringstream.getvalue().split("\n")

        y_wrt_x1_line = lines.index("  comp: 'y' wrt 'x1'")

        self.assertTrue(lines[y_wrt_x1_line+6].endswith('*'),
                        msg='Error flag expected in output but not displayed')
        self.assertTrue(lines[y_wrt_x1_line+7].endswith('*'),
                        msg='Error flag expected in output but not displayed')
        self.assertFalse(lines[y_wrt_x1_line+8].endswith('*'),
                        msg='Error flag not expected in output but displayed')
Example #36
0
    def test_problem_deriv_test(self):

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', SimpleCompWrongDeriv())
        prob.root.add('p1', IndepVarComp('x', 2.0))
        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        try:
            problem_derivatives_check(self, prob)
        except AssertionError as err:
            self.assertIn("not less than or equal to 1e-05", err.args[0])
    def test_double_diamond_model(self):

        prob = Problem()
        prob.root = ConvergeDivergeGroups()

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
    def test_double_diamond_model(self):

        prob = Problem()
        prob.root = ConvergeDivergeGroups()

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
    def test_big_boy_Jacobian(self):

        class MyComp(Component):

            def __init__(self, multiplier=2.0):
                super(MyComp, self).__init__()

                # Params
                self.add_param('x1', 3.0)
                self.add_param('x2', 5.0)

                # Unknowns
                self.add_output('y', 5.5)

            def solve_nonlinear(self, params, unknowns, resids):
                """ Doesn't do much. """
                unknowns['y'] = 3.0*params['x1'] + 4.0*params['x2']

            def linearize(self, params, unknowns, resids):
                """Intentionally left out x2 derivative."""

                J = {}
                J[('y', 'x1')] = np.array([[3.0]])
                return J

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', MyComp())
        prob.root.add('p1', IndepVarComp('x1', 3.0))
        prob.root.add('p2', IndepVarComp('x2', 5.0))

        prob.root.connect('p1.x1', 'comp.x1')
        prob.root.connect('p2.x2', 'comp.x2')

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

        data = prob.check_partial_derivatives(out_stream=None)
        self.assertTrue(('y', 'x1') in data['comp'])
        self.assertTrue(('y', 'x2') in data['comp'])
    def test_big_boy_Jacobian(self):

        class MyComp(Component):

            def __init__(self, multiplier=2.0):
                super(MyComp, self).__init__()

                # Params
                self.add_param('x1', 3.0)
                self.add_param('x2', 5.0)

                # Unknowns
                self.add_output('y', 5.5)

            def solve_nonlinear(self, params, unknowns, resids):
                """ Doesn't do much. """
                unknowns['y'] = 3.0*params['x1'] + 4.0*params['x2']

            def linearize(self, params, unknowns, resids):
                """Intentionally left out x2 derivative."""

                J = {}
                J[('y', 'x1')] = np.array([[3.0]])
                return J

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', MyComp())
        prob.root.add('p1', IndepVarComp('x1', 3.0))
        prob.root.add('p2', IndepVarComp('x2', 5.0))

        prob.root.connect('p1.x1', 'comp.x1')
        prob.root.connect('p2.x2', 'comp.x2')

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

        data = prob.check_partial_derivatives(out_stream=None)
        self.assertTrue(('y', 'x1') in data['comp'])
        self.assertTrue(('y', 'x2') in data['comp'])
Example #41
0
    def test_simple_array_model2(self):
        prob = Problem()
        prob.root = Group()
        comp = prob.root.add('comp', ExecComp('y = mat.dot(x)',
                                              x=np.zeros((2,)), y=np.zeros((2,)),
                                              mat=np.array([[2.,7.],[5.,-3.]])))

        p1 = prob.root.add('p1', IndepVarComp('x', np.ones([2])))

        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        assert_rel_error(self, data['comp'][('y','x')]['abs error'][0], 0.0, 1e-5)
        assert_rel_error(self, data['comp'][('y','x')]['abs error'][1], 0.0, 1e-5)
        assert_rel_error(self, data['comp'][('y','x')]['abs error'][2], 0.0, 1e-5)
        assert_rel_error(self, data['comp'][('y','x')]['rel error'][0], 0.0, 1e-5)
        assert_rel_error(self, data['comp'][('y','x')]['rel error'][1], 0.0, 1e-5)
        assert_rel_error(self, data['comp'][('y','x')]['rel error'][2], 0.0, 1e-5)
Example #42
0
    def test_simple_array_model(self):
        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', ExecComp(['y[0]=2.0*x[0]+7.0*x[1]',
                                        'y[1]=5.0*x[0]-3.0*x[1]'],
                                       x=np.zeros([2]), y=np.zeros([2])))

        prob.root.add('p1', IndepVarComp('x', np.ones([2])))

        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        assert_rel_error(self, data['comp'][('y','x')]['abs error'][0], 0.0, 1e-5)
        assert_rel_error(self, data['comp'][('y','x')]['abs error'][1], 0.0, 1e-5)
        assert_rel_error(self, data['comp'][('y','x')]['abs error'][2], 0.0, 1e-5)
        assert_rel_error(self, data['comp'][('y','x')]['rel error'][0], 0.0, 1e-5)
        assert_rel_error(self, data['comp'][('y','x')]['rel error'][1], 0.0, 1e-5)
        assert_rel_error(self, data['comp'][('y','x')]['rel error'][2], 0.0, 1e-5)
    def test_simple_array_model(self):

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', SimpleArrayComp())
        prob.root.add('p1', IndepVarComp('x', np.ones([2])))

        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
Example #44
0
    def setUp(self):

        top = Problem()

        root = top.root = Group()
        root.add('p', MyComp())

        self.x, self.y, self.A = 3.0, -4.0, np.random.randn(2,2)


        root.add('p1', IndepVarComp('x', self.x))
        root.add('p2', IndepVarComp('y', self.y))
        root.add('p3', IndepVarComp('A', self.A))
        
        root.connect('p1.x', 'p.x')
        root.connect('p2.y', 'p.y')
        root.connect('p3.A', 'p.A')

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

        self.deriv = top.check_partial_derivatives(out_stream=None)['p']
    def test_simple_array_model(self):

        prob = Problem()
        prob.root = Group()
        prob.root.add('comp', SimpleArrayComp())
        prob.root.add('p1', IndepVarComp('x', np.ones([2])))

        prob.root.connect('p1.x', 'comp.x')

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

        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
Example #46
0
prob.setup()

t0 = time.time()
prob.run()
t1 = time.time()

#print t1-t0

nodes0 = nodes
nodes1 = nodes + prob['disp']

#writeBDF('jig.bdf', nodes0, elements+1)
#writeBDF('deflected.bdf', nodes1, elements+1)

if 0:
    prob.check_partial_derivatives(compact_print=True)
    exit()

prob.driver = pyOptSparseDriver()
prob.driver.options['optimizer'] = "SNOPT"
prob.driver.opt_settings = {'Major optimality tolerance': 1.0e-7,
                            'Major feasibility tolerance': 1.0e-7,
                            'Iterations limit': int(1e8),
}

prob.driver.add_desvar('areas',lower=area_low, upper=area_up, scaler=1e0) # test
prob.driver.add_objective('volume', scaler=1e0)
prob.driver.add_constraint('minstress', upper=0.)
prob.driver.add_constraint('maxstress', upper=0.)
prob.driver.add_constraint('neg_stress_plus_buckling_con', upper=0.)
Example #47
0
#     ('P_generated', np.random.randn(n)**2, {'units' : 'W'}),
#     ('array_power', 100, {'units' : 'W'}),
#     ('P_consumption', np.random.randn(n)**2, {'units' : 'W'}),
#     ('power_capacity', 50.0, {'units' : 'W*h'}),
# )

top.root.add("batt", BatteryConstraints(n), promotes=["*"])
top.root.batt.fd_options['form'] = 'complex_step'
dvar = (('SOC', np.random.rand(n)), )

# top.root.add("loads", Loads(n), promotes=["*"])
# dvar = (
#     ('P_generated', np.random.randn(n) * 4, {'units' : 'W'}),
#     ('ambient_temperatures', np.random.randn(n)**2, {'units' : 'W'}),
#     ('irradiance', np.random.randn(n)*20, {'units' : 'W/m**2'}),
#     ('array_power', 1000.0, {'units' : 'W'}),
#     ('P_constant', 4.0, {'units' : 'W'}),
#     ('P_direct', 3.0, {'units' : 'W'}),
#     ('P_daytime', 2.0, {'units' : 'W'}),
#     ('P_nighttime', 1.0, {'units' : 'W'}),
#     ('power_capacity', 50.0, {'units' : 'W*h'}),
# )

top.root.add("dvar", IndepVarComp(dvar), promotes=["*"])

top.setup()

top.run()

top.check_partial_derivatives()
Example #48
0
        J['thrust', 'Vu'] = 4.0 * a_area_rho_vu * (one_minus_a)

        J['Cp', 'a'] = 4.0 * a * (2.0 * a - 2.0) + 4.0 * (one_minus_a)**2

        J['power', 'a'] = 2.0 * Area * Vu**3 * a * rho * (
            2.0 * a - 2.0) + 2.0 * Area * Vu**3 * rho * one_minus_a**2
        J['power', 'Area'] = 2.0 * Vu**3 * a * rho * one_minus_a**2
        J['power', 'rho'] = 2.0 * a_times_area * Vu**3 * (one_minus_a)**2
        J['power', 'Vu'] = 6.0 * Area * Vu**2 * a * rho * one_minus_a**2

        return J


if __name__ == "__main__":

    from openmdao.api import Problem, Group, IndepVarComp

    prob = Problem()
    prob.root = Group()
    prob.root.add('disc', ActuatorDisc(), promotes=['a', 'Area', 'rho', 'Vu'])

    prob.root.add('p_a', IndepVarComp('a', 0.5), promotes=['*'])
    prob.root.add('p_Area', IndepVarComp('Area', 10.0), promotes=['*'])
    prob.root.add('p_rho', IndepVarComp('rho', 1.225), promotes=['*'])
    prob.root.add('p_Vu', IndepVarComp('Vu', 10.0), promotes=['*'])

    prob.setup()
    prob.run()

    prob.check_partial_derivatives()
    def test_apply_linear_units(self):
        # Make sure we can index into dparams

        class Attitude_Angular(Component):
            """ Calculates angular velocity vector from the satellite's orientation
            matrix and its derivative.
            """
            def __init__(self, n=2):
                super(Attitude_Angular, self).__init__()

                self.n = n

                # Inputs
                self.add_param(
                    'O_BI',
                    np.zeros((3, 3, n)),
                    units="ft",
                    desc=
                    "Rotation matrix from body-fixed frame to Earth-centered "
                    "inertial frame over time")

                self.add_param('Odot_BI',
                               np.zeros((3, 3, n)),
                               units="km",
                               desc="First derivative of O_BI over time")

                # Outputs
                self.add_output(
                    'w_B',
                    np.zeros((3, n)),
                    units="1/s",
                    scaler=12.0,
                    desc="Angular velocity vector in body-fixed frame over time"
                )

                self.dw_dOdot = np.zeros((n, 3, 3, 3))
                self.dw_dO = np.zeros((n, 3, 3, 3))

            def solve_nonlinear(self, params, unknowns, resids):
                """ Calculate output. """

                O_BI = params['O_BI']
                Odot_BI = params['Odot_BI']
                w_B = unknowns['w_B']

                for i in range(0, self.n):
                    w_B[0, i] = np.dot(Odot_BI[2, :, i], O_BI[1, :, i])
                    w_B[1, i] = np.dot(Odot_BI[0, :, i], O_BI[2, :, i])
                    w_B[2, i] = np.dot(Odot_BI[1, :, i], O_BI[0, :, i])

                #print(unknowns['w_B'])

            def linearize(self, params, unknowns, resids):
                """ Calculate and save derivatives. (i.e., Jacobian) """

                O_BI = params['O_BI']
                Odot_BI = params['Odot_BI']

                for i in range(0, self.n):
                    self.dw_dOdot[i, 0, 2, :] = O_BI[1, :, i]
                    self.dw_dO[i, 0, 1, :] = Odot_BI[2, :, i]

                    self.dw_dOdot[i, 1, 0, :] = O_BI[2, :, i]
                    self.dw_dO[i, 1, 2, :] = Odot_BI[0, :, i]

                    self.dw_dOdot[i, 2, 1, :] = O_BI[0, :, i]
                    self.dw_dO[i, 2, 0, :] = Odot_BI[1, :, i]

            def apply_linear(self, params, unknowns, dparams, dunknowns,
                             dresids, mode):
                """ Matrix-vector product with the Jacobian. """

                dw_B = dresids['w_B']

                if mode == 'fwd':
                    for k in range(3):
                        for i in range(3):
                            for j in range(3):
                                if 'O_BI' in dparams:
                                    dw_B[k, :] += self.dw_dO[:, k, i, j] * \
                                        dparams['O_BI'][i, j, :]
                                if 'Odot_BI' in dparams:
                                    dw_B[k, :] += self.dw_dOdot[:, k, i, j] * \
                                        dparams['Odot_BI'][i, j, :]

                else:

                    for k in range(3):
                        for i in range(3):
                            for j in range(3):

                                if 'O_BI' in dparams:
                                    dparams['O_BI'][i, j, :] += self.dw_dO[:, k, i, j] * \
                                        dw_B[k, :]

                                if 'Odot_BI' in dparams:
                                    dparams['Odot_BI'][i, j, :] -= -self.dw_dOdot[:, k, i, j] * \
                                        dw_B[k, :]

        prob = Problem()
        root = prob.root = Group()
        prob.root.add('comp', Attitude_Angular(n=5), promotes=['*'])
        prob.root.add('p1',
                      IndepVarComp('O_BI', np.ones((3, 3, 5))),
                      promotes=['*'])
        prob.root.add('p2',
                      IndepVarComp('Odot_BI', np.ones((3, 3, 5))),
                      promotes=['*'])

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

        indep_list = ['O_BI', 'Odot_BI']
        unknown_list = ['w_B']
        Jf = prob.calc_gradient(indep_list,
                                unknown_list,
                                mode='fwd',
                                return_format='dict')

        indep_list = ['O_BI', 'Odot_BI']
        unknown_list = ['w_B']
        Jr = prob.calc_gradient(indep_list,
                                unknown_list,
                                mode='rev',
                                return_format='dict')

        for key, val in iteritems(Jr):
            for key2 in val:
                diff = abs(Jf[key][key2] - Jr[key][key2])
                assert_rel_error(self, diff, 0.0, 1e-10)

        # Clean up old FD
        prob.run()

        # Partials
        data = prob.check_partial_derivatives(out_stream=None)
        #data = prob.check_partial_derivatives()

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
    prob['Ct_in'] = Ct
    prob['Cp_in'] = Cp

    # assign boundary values
    prob['boundary_center'] = np.array([boundary_center_x, boundary_center_y])
    prob['boundary_radius'] = boundary_radius

    # set options
    # prob['floris_params:FLORISoriginal'] = True
    # prob['floris_params:CPcorrected'] = False
    # prob['floris_params:CTcorrected'] = False

    prob.run_once()
    AEP_init = prob['AEP']
    # pass results to self for use with unit test
    Jp = prob.check_partial_derivatives(out_stream=None)
    Jt = prob.check_total_derivatives(out_stream=None)

    # run the problem
    mpi_print(prob, 'start Bastankhah run')
    tic = time.time()
    # cProfile.run('prob.run()')
    prob.run()
    toc = time.time()

    # print the results
    mpi_print(prob, ('Opt. calculation took %.03f sec.' % (toc - tic)))

    for direction_id in range(0, windDirections.size):
        mpi_print(prob, 'yaw%i (deg) = ' % direction_id,
                  prob['yaw%i' % direction_id])
    def test_apply_linear_units(self):
        # Make sure we can index into dparams

        class Attitude_Angular(Component):
            """ Calculates angular velocity vector from the satellite's orientation
            matrix and its derivative.
            """

            def __init__(self, n=2):
                super(Attitude_Angular, self).__init__()

                self.n = n

                # Inputs
                self.add_param('O_BI', np.zeros((3, 3, n)), units="ft",
                               desc="Rotation matrix from body-fixed frame to Earth-centered "
                               "inertial frame over time")

                self.add_param('Odot_BI', np.zeros((3, 3, n)), units="km",
                               desc="First derivative of O_BI over time")

                # Outputs
                self.add_output('w_B', np.zeros((3, n)), units="1/s", scaler=12.0,
                                desc="Angular velocity vector in body-fixed frame over time")

                self.dw_dOdot = np.zeros((n, 3, 3, 3))
                self.dw_dO = np.zeros((n, 3, 3, 3))

            def solve_nonlinear(self, params, unknowns, resids):
                """ Calculate output. """

                O_BI = params['O_BI']
                Odot_BI = params['Odot_BI']
                w_B = unknowns['w_B']

                for i in range(0, self.n):
                    w_B[0, i] = np.dot(Odot_BI[2, :, i], O_BI[1, :, i])
                    w_B[1, i] = np.dot(Odot_BI[0, :, i], O_BI[2, :, i])
                    w_B[2, i] = np.dot(Odot_BI[1, :, i], O_BI[0, :, i])

                #print(unknowns['w_B'])

            def linearize(self, params, unknowns, resids):
                """ Calculate and save derivatives. (i.e., Jacobian) """

                O_BI = params['O_BI']
                Odot_BI = params['Odot_BI']

                for i in range(0, self.n):
                    self.dw_dOdot[i, 0, 2, :] = O_BI[1, :, i]
                    self.dw_dO[i, 0, 1, :] = Odot_BI[2, :, i]

                    self.dw_dOdot[i, 1, 0, :] = O_BI[2, :, i]
                    self.dw_dO[i, 1, 2, :] = Odot_BI[0, :, i]

                    self.dw_dOdot[i, 2, 1, :] = O_BI[0, :, i]
                    self.dw_dO[i, 2, 0, :] = Odot_BI[1, :, i]

            def apply_linear(self, params, unknowns, dparams, dunknowns, dresids, mode):
                """ Matrix-vector product with the Jacobian. """

                dw_B = dresids['w_B']

                if mode == 'fwd':
                    for k in range(3):
                        for i in range(3):
                            for j in range(3):
                                if 'O_BI' in dparams:
                                    dw_B[k, :] += self.dw_dO[:, k, i, j] * \
                                        dparams['O_BI'][i, j, :]
                                if 'Odot_BI' in dparams:
                                    dw_B[k, :] += self.dw_dOdot[:, k, i, j] * \
                                        dparams['Odot_BI'][i, j, :]

                else:

                    for k in range(3):
                        for i in range(3):
                            for j in range(3):

                                if 'O_BI' in dparams:
                                    dparams['O_BI'][i, j, :] += self.dw_dO[:, k, i, j] * \
                                        dw_B[k, :]

                                if 'Odot_BI' in dparams:
                                    dparams['Odot_BI'][i, j, :] -= -self.dw_dOdot[:, k, i, j] * \
                                        dw_B[k, :]

        prob = Problem()
        root = prob.root = Group()
        prob.root.add('comp', Attitude_Angular(n=5), promotes=['*'])
        prob.root.add('p1', IndepVarComp('O_BI', np.ones((3, 3, 5))), promotes=['*'])
        prob.root.add('p2', IndepVarComp('Odot_BI', np.ones((3, 3, 5))), promotes=['*'])

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

        indep_list = ['O_BI', 'Odot_BI']
        unknown_list = ['w_B']
        Jf = prob.calc_gradient(indep_list, unknown_list, mode='fwd',
                                return_format='dict')

        indep_list = ['O_BI', 'Odot_BI']
        unknown_list = ['w_B']
        Jr = prob.calc_gradient(indep_list, unknown_list, mode='rev',
                                return_format='dict')

        for key, val in iteritems(Jr):
            for key2 in val:
                diff = abs(Jf[key][key2] - Jr[key][key2])
                assert_rel_error(self, diff, 0.0, 1e-10)

        # Clean up old FD
        prob.run()

        # Partials
        data = prob.check_partial_derivatives(out_stream=None)
        #data = prob.check_partial_derivatives()

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-5)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-5)
Example #52
0
prob.setup()

t0 = time.time()
prob.run()
t1 = time.time()

#print t1-t0

nodes0 = nodes
nodes1 = nodes + prob['disp']

writeBDF('jig.bdf', nodes0, elements+1)
writeBDF('deflected.bdf', nodes1, elements+1)

if 0:
    prob.check_partial_derivatives(compact_print=True)
    exit()

prob.driver = pyOptSparseDriver()
prob.driver.options['optimizer'] = "SNOPT"
prob.driver.opt_settings = {'Major optimality tolerance': 1.0e-7,
                            'Major feasibility tolerance': 1.0e-7,
                            'Iterations limit': int(1e6),
}

prob.driver.add_desvar('areas',lower=0.0001, upper=0.1, scaler=1e0) # test
prob.driver.add_objective('volume', scaler=1e0)
prob.driver.add_constraint('minstress', upper=0.)
prob.driver.add_constraint('maxstress', upper=0.)
# setup data recording
prob.driver.add_recorder(SqliteRecorder('data.db'))
Example #53
0
    def test_scaler_on_src_with_unit_conversion(self):

        from openmdao.core.test.test_units import TgtCompC, TgtCompF, TgtCompK

        class SrcComp(Component):
            def __init__(self):
                super(SrcComp, self).__init__()

                self.add_param("x1", 100.0)
                self.add_output("x2", 100.0, units="degC", scaler=10.0)

            def solve_nonlinear(self, params, unknowns, resids):
                """ No action."""
                unknowns["x2"] = params["x1"]

            def linearize(self, params, unknowns, resids):
                """ Derivative is 1.0"""
                J = {}
                J[("x2", "x1")] = np.array([1.0])
                return J

        prob = Problem()
        prob.root = Group()
        prob.root.add("src", SrcComp())
        prob.root.add("tgtF", TgtCompF())
        prob.root.add("tgtC", TgtCompC())
        prob.root.add("tgtK", TgtCompK())
        prob.root.add("px1", IndepVarComp("x1", 100.0), promotes=["x1"])
        prob.root.connect("x1", "src.x1")
        prob.root.connect("src.x2", "tgtF.x2")
        prob.root.connect("src.x2", "tgtC.x2")
        prob.root.connect("src.x2", "tgtK.x2")

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

        assert_rel_error(self, prob["src.x2"], 100.0, 1e-6)
        assert_rel_error(self, prob["tgtF.x3"], 212.0, 1e-6)
        assert_rel_error(self, prob["tgtC.x3"], 100.0, 1e-6)
        assert_rel_error(self, prob["tgtK.x3"], 373.15, 1e-6)

        # Make sure the scale factor is included here, even though no unit conversion
        self.assertEqual(prob.root.params.metadata("tgtC.x2").get("unit_conv"), (10.0, 0.0))

        indep_list = ["x1"]
        unknown_list = ["tgtF.x3", "tgtC.x3", "tgtK.x3"]
        J = prob.calc_gradient(indep_list, unknown_list, mode="fwd", return_format="dict")

        assert_rel_error(self, J["tgtF.x3"]["x1"][0][0], 1.8, 1e-6)
        assert_rel_error(self, J["tgtC.x3"]["x1"][0][0], 1.0, 1e-6)
        assert_rel_error(self, J["tgtK.x3"]["x1"][0][0], 1.0, 1e-6)

        J = prob.calc_gradient(indep_list, unknown_list, mode="rev", return_format="dict")

        assert_rel_error(self, J["tgtF.x3"]["x1"][0][0], 1.8, 1e-6)
        assert_rel_error(self, J["tgtC.x3"]["x1"][0][0], 1.0, 1e-6)
        assert_rel_error(self, J["tgtK.x3"]["x1"][0][0], 1.0, 1e-6)

        J = prob.calc_gradient(indep_list, unknown_list, mode="fd", return_format="dict")

        assert_rel_error(self, J["tgtF.x3"]["x1"][0][0], 1.8, 1e-6)
        assert_rel_error(self, J["tgtC.x3"]["x1"][0][0], 1.0, 1e-6)
        assert_rel_error(self, J["tgtK.x3"]["x1"][0][0], 1.0, 1e-6)

        # Need to clean up after FD gradient call, so just rerun.
        prob.run()

        # Make sure check partials handles conversion
        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2["abs error"][0], 0.0, 1e-6)
                assert_rel_error(self, val2["abs error"][1], 0.0, 1e-6)
                assert_rel_error(self, val2["abs error"][2], 0.0, 1e-6)
                assert_rel_error(self, val2["rel error"][0], 0.0, 1e-6)
                assert_rel_error(self, val2["rel error"][1], 0.0, 1e-6)
                assert_rel_error(self, val2["rel error"][2], 0.0, 1e-6)

        stream = cStringIO()
        conv = prob.root.list_unit_conv(stream=stream)
        self.assertTrue((("src.x2", "tgtF.x2"), ("degC", "degF")) in conv)
        self.assertTrue((("src.x2", "tgtK.x2"), ("degC", "degK")) in conv)
Example #54
0
    prob['Ct_in'] = Ct
    prob['Cp_in'] = Cp

    # assign boundary values
    prob['boundary_center'] = np.array([boundary_center_x, boundary_center_y])
    prob['boundary_radius'] = boundary_radius

    # set options
    # prob['floris_params:FLORISoriginal'] = True
    # prob['floris_params:CPcorrected'] = False
    # prob['floris_params:CTcorrected'] = False

    prob.run_once()
    AEP_init = prob['AEP']
    # pass results to self for use with unit test
    Jp = prob.check_partial_derivatives(out_stream=None)
    Jt = prob.check_total_derivatives(out_stream=None)

    # run the problem
    mpi_print(prob, 'start Bastankhah run')
    tic = time.time()
    # cProfile.run('prob.run()')
    prob.run()
    toc = time.time()

    # print the results
    mpi_print(prob, ('Opt. calculation took %.03f sec.' % (toc-tic)))

    for direction_id in range(0, windDirections.size):
        mpi_print(prob,  'yaw%i (deg) = ' % direction_id, prob['yaw%i' % direction_id])
    # for direction_id in range(0, windDirections.size):
Example #55
0
    def solve_nonlinear(self, params, unknowns, resids):

        x = params['x']
        y = params['y']
        A = params['A']

        unknowns['f_xy'] = x**2 + y**2 + np.sin(A).sum()
        unknowns['g_xy'] = np.linalg.dot(A**2, np.array([y, x**2]))


if __name__ == "__main__":

    top = Problem()

    root = top.root = Group()
    root.add('p', MyComp())

    root.add('p1', IndepVarComp('x', 3.0))
    root.add('p2', IndepVarComp('y', -4.0))
    root.add('p3', IndepVarComp('A', np.random.randn(2,2)))

    root.connect('p1.x', 'p.x')
    root.connect('p2.y', 'p.y')
    root.connect('p3.A', 'p.A')

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

    # compare auto-generated derivatives against FD
    top.check_partial_derivatives()
    else:
        raise ValueError(
            'unknown uncertain_var option "%s", valid options "speed" or "direction".' % method_dict["uncertain_var"]
        )

    method_dict["dakota_filename"] = "dakotageneral.in"

    n = 10
    unused, weights = getPoints(method_dict, n)
    prob = Problem(root=Group())
    prob.root.add("p", IndepVarComp("dirPowers", np.random.rand(n)))
    prob.root.add("w", IndepVarComp("windWeights", weights))
    if method_dict["method"] == "rect":
        prob.root.add(
            "AEPComp", RectStatistics(nDirections=n, method_dict=method_dict)
        )  # , promotes=['*'])  # No need to promote because of the explicit connection below
    if method_dict["method"] == "dakota":
        prob.root.add("AEPComp", DakotaStatistics(nDirections=n, method_dict=method_dict))  # , promotes=['*'])
    prob.root.connect("p.dirPowers", "AEPComp.dirPowers")
    prob.root.connect("w.windWeights", "AEPComp.windWeights")
    prob.setup()
    prob.run()
    print "AEP = ", (prob.root.AEPComp.unknowns["mean"])
    print "power = ", (prob.root.AEPComp.params["dirPowers"])
    print prob.root.AEPComp.params.keys()
    # J = prob.calc_gradient(['AEPComp.mean'], ['p.power'])  # I'm not sure why this returns zero
    # print 'power directions gradient = ', J

    # This check works
    data = prob.check_partial_derivatives()
Example #57
0
    def test_basic_force_fd_comps(self):

        prob = Problem()
        prob.root = Group()
        prob.root.add('src', SrcComp())
        prob.root.add('tgtF', TgtCompF())
        prob.root.add('tgtC', TgtCompC())
        prob.root.add('tgtK', TgtCompK())
        prob.root.add('px1', IndepVarComp('x1', 100.0), promotes=['x1'])
        prob.root.connect('x1', 'src.x1')
        prob.root.connect('src.x2', 'tgtF.x2')
        prob.root.connect('src.x2', 'tgtC.x2')
        prob.root.connect('src.x2', 'tgtK.x2')

        prob.root.src.deriv_options['type'] = 'fd'
        prob.root.tgtF.deriv_options['type'] = 'fd'
        prob.root.tgtC.deriv_options['type'] = 'fd'
        prob.root.tgtK.deriv_options['type'] = 'fd'

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

        assert_rel_error(self, prob['src.x2'], 100.0, 1e-6)
        assert_rel_error(self, prob['tgtF.x3'], 212.0, 1e-6)
        assert_rel_error(self, prob['tgtC.x3'], 100.0, 1e-6)
        assert_rel_error(self, prob['tgtK.x3'], 373.15, 1e-6)

        # Make sure we don't convert equal units
        self.assertEqual(
            prob.root.params.metadata('tgtC.x2').get('unit_conv'), None)

        indep_list = ['x1']
        unknown_list = ['tgtF.x3', 'tgtC.x3', 'tgtK.x3']
        J = prob.calc_gradient(indep_list,
                               unknown_list,
                               mode='fwd',
                               return_format='dict')

        assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)

        J = prob.calc_gradient(indep_list,
                               unknown_list,
                               mode='rev',
                               return_format='dict')

        assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)

        J = prob.calc_gradient(indep_list,
                               unknown_list,
                               mode='fd',
                               return_format='dict')

        assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)

        # Need to clean up after FD gradient call, so just rerun.
        prob.run()

        # Make sure check partials handles conversion
        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-6)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-6)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-6)

        stream = cStringIO()
        conv = prob.root.list_unit_conv(stream=stream)
        self.assertTrue((('src.x2', 'tgtF.x2'), ('degC', 'degF')) in conv)
        self.assertTrue((('src.x2', 'tgtK.x2'), ('degC', 'degK')) in conv)
Example #58
0
    def test_basic(self):

        prob = Problem()
        prob.root = Group()
        prob.root.add('src', SrcComp())
        prob.root.add('tgtF', TgtCompF())
        prob.root.add('tgtC', TgtCompC())
        prob.root.add('tgtK', TgtCompK())
        prob.root.add('px1', IndepVarComp('x1', 100.0), promotes=['x1'])
        prob.root.connect('x1', 'src.x1')
        prob.root.connect('src.x2', 'tgtF.x2')
        prob.root.connect('src.x2', 'tgtC.x2')
        prob.root.connect('src.x2', 'tgtK.x2')

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

        assert_rel_error(self, prob['src.x2'], 100.0, 1e-6)
        assert_rel_error(self, prob['tgtF.x3'], 212.0, 1e-6)
        assert_rel_error(self, prob['tgtC.x3'], 100.0, 1e-6)
        assert_rel_error(self, prob['tgtK.x3'], 373.15, 1e-6)

        # Make sure we don't convert equal units
        self.assertEqual(prob.root.params.metadata('tgtC.x2').get('unit_conv'),
                         None)

        indep_list = ['x1']
        unknown_list = ['tgtF.x3', 'tgtC.x3', 'tgtK.x3']
        J = prob.calc_gradient(indep_list, unknown_list, mode='fwd',
                               return_format='dict')

        assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)

        J = prob.calc_gradient(indep_list, unknown_list, mode='rev',
                               return_format='dict')

        assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)

        J = prob.calc_gradient(indep_list, unknown_list, mode='fd',
                               return_format='dict')

        assert_rel_error(self, J['tgtF.x3']['x1'][0][0], 1.8, 1e-6)
        assert_rel_error(self, J['tgtC.x3']['x1'][0][0], 1.0, 1e-6)
        assert_rel_error(self, J['tgtK.x3']['x1'][0][0], 1.0, 1e-6)

        # Need to clean up after FD gradient call, so just rerun.
        prob.run()

        # Make sure check partials handles conversion
        data = prob.check_partial_derivatives(out_stream=None)

        for key1, val1 in iteritems(data):
            for key2, val2 in iteritems(val1):
                assert_rel_error(self, val2['abs error'][0], 0.0, 1e-6)
                assert_rel_error(self, val2['abs error'][1], 0.0, 1e-6)
                assert_rel_error(self, val2['abs error'][2], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][0], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][1], 0.0, 1e-6)
                assert_rel_error(self, val2['rel error'][2], 0.0, 1e-6)

        stream = cStringIO()
        conv = prob.list_unit_conv(stream=stream)
        self.assertTrue((('src.x2', 'tgtF.x2'), ('degC', 'degF')) in conv)
        self.assertTrue((('src.x2', 'tgtK.x2'), ('degC', 'degK')) in conv)