class CycleComponentTestCase(unittest.TestCase):
    def setUp(self): 
        '''Initialization function called before every test function''' 
        self.g = Group()
        self.comp1 = DummyComp()
        self.comp2 = DummyComp()
        self.g.add('comp1', self.comp1)
        self.g.add('comp2', self.comp2)
        self.p = Problem(root=self.g)
        self.p.setup()

    def tearDown(self):
        '''Function called after every test function'''
        self.g = None
        self.p = None

    def test_copy_flow(self): 
        self.comp1.params['flow:in:W'] = 100.0
        self.comp1.params['flow:in:Tt'] = 518.0
        self.comp1.params['flow:in:Pt'] = 15.0
        CycleComponent.copy_from(self.comp1, 'flow', self.comp2, 'flow')

        self.p.run()

        TOL = 0.0001
        assert_rel_error(self, self.comp2.unknowns['flow:out:Tt'], 518.0, TOL)
        assert_rel_error(self, self.comp2.unknowns['flow:out:Pt'], 15.0, TOL)
示例#2
0
    def test_conflicting_promotions(self):
        # verify we get an error if we have conflicting promotions
        root = Group()

        # promoting G1.x will create an implicit connection to G3.x
        # this is a conflict because G3.x (aka G3.C4.x) is already connected
        # to G3.C3.x
        G2 = root.add('G2', Group())
        G2.add('C1', ParamComp('x', 5.), promotes=['x'])

        G1 = G2.add('G1', Group(), promotes=['x'])
        G1.add('C2', ExecComp('y=x*2.0'), promotes=['x'])

        G3 = root.add('G3', Group(), promotes=['x'])
        G3.add('C3', ExecComp('y=x*2.0'), promotes=['y'])          # promoting y
        G3.add('C4', ExecComp('y=x*2.0'), promotes=['x', 'y'])     # promoting y again.. BAD

        prob = Problem(root)

        try:
            prob.setup(check=False)
        except Exception as error:
            msg = "Promoted name 'G3.y' matches multiple unknowns: ['G3.C3.y', 'G3.C4.y']"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")
示例#3
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)
示例#4
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)

        J = prob.calc_gradient(['x1', 'x2'], ['y1', 'y2'],
                               mode='rev',
                               return_format='array')
        diff = np.linalg.norm(J - Jbase)
        assert_rel_error(self, diff, 0.0, 1e-8)
示例#5
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)
    def test_array2D_index_connection(self):
        group = Group()
        group.add('x_param', IndepVarComp('x', np.ones((2, 2))), promotes=['*'])
        sub = group.add('sub', Group(), promotes=['*'])
        sub.add('mycomp', ArrayComp2D(), promotes=['x', 'y'])
        group.add('obj', ExecComp('b = a'))
        group.connect('y', 'obj.a',  src_indices=[3])

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

        J = prob.calc_gradient(['x'], ['obj.b'], mode='fwd', return_format='dict')
        Jbase = prob.root.sub.mycomp._jacobian_cache
        assert_rel_error(self, Jbase[('y', 'x')][3][0], J['obj.b']['x'][0][0], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][1], J['obj.b']['x'][0][1], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][2], J['obj.b']['x'][0][2], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][3], J['obj.b']['x'][0][3], 1e-8)

        J = prob.calc_gradient(['x'], ['obj.b'], mode='rev', return_format='dict')
        Jbase = prob.root.sub.mycomp._jacobian_cache
        assert_rel_error(self, Jbase[('y', 'x')][3][0], J['obj.b']['x'][0][0], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][1], J['obj.b']['x'][0][1], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][2], J['obj.b']['x'][0][2], 1e-8)
        assert_rel_error(self, Jbase[('y', 'x')][3][3], J['obj.b']['x'][0][3], 1e-8)
示例#7
0
    def test_conflicting_connections(self):
        # verify we get an error if we have conflicting implicit and explicit connections
        root = Group()

        # promoting G1.x will create an implicit connection to G3.x
        # this is a conflict because G3.x (aka G3.C4.x) is already connected
        # to G3.C3.x
        G2 = root.add('G2', Group(), promotes=['x'])  # BAD PROMOTE
        G2.add('C1', ParamComp('x', 5.), promotes=['x'])

        G1 = G2.add('G1', Group(), promotes=['x'])
        G1.add('C2', ExecComp('y=x*2.0'), promotes=['x'])

        G3 = root.add('G3', Group(), promotes=['x'])
        G3.add('C3', ExecComp('y=x*2.0'))
        G3.add('C4', ExecComp('y=x*2.0'), promotes=['x'])

        root.connect('G2.G1.C2.y', 'G3.C3.x')
        G3.connect('C3.y', 'x')

        prob = Problem(root)

        try:
            prob.setup(check=False)
        except Exception as error:
            msg = "Target 'G3.C4.x' is connected to multiple unknowns: ['G2.C1.x', 'G3.C3.y']"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")
示例#8
0
    def test_conflicting_promotions(self):
        # verify we get an error if we have conflicting promotions
        root = Group()

        # promoting G1.x will create an implicit connection to G3.x
        # this is a conflict because G3.x (aka G3.C4.x) is already connected
        # to G3.C3.x
        G2 = root.add('G2', Group())
        G2.add('C1', ParamComp('x', 5.), promotes=['x'])

        G1 = G2.add('G1', Group(), promotes=['x'])
        G1.add('C2', ExecComp('y=x*2.0'), promotes=['x'])

        G3 = root.add('G3', Group(), promotes=['x'])
        G3.add('C3', ExecComp('y=x*2.0'), promotes=['y'])  # promoting y
        G3.add('C4', ExecComp('y=x*2.0'),
               promotes=['x', 'y'])  # promoting y again.. BAD

        prob = Problem(root)

        try:
            prob.setup(check=False)
        except Exception as error:
            msg = "Promoted name 'G3.y' matches multiple unknowns: ['G3.C3.y', 'G3.C4.y']"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")
    def test_heat_exchanger(self): 
        comp = HeatExchanger()
        g = Group()
        g.add('comp', comp)
        p = Problem(root=g)
        p.setup()

        comp.params['flow_in:in:Tt'] = 1423.8
        comp.params['flow_in:in:Pt'] = 0.302712118187
        comp.params['flow_in:in:W'] = 1.0
        comp.params['dPqP'] = 0.0
        comp.params['design'] = True
        p.run()
        
        TOL = 0.005
        assert_rel_error(self, comp.unknowns['flow_out:out:Tt'], 539.94, TOL)
        assert_rel_error(self, comp.unknowns['Qreleased'], 327.22, TOL)
        assert_rel_error(self, comp.unknowns['Qabsorbed'], 327.22, TOL)
        assert_rel_error(self, comp.unknowns['Qmax'], 335.1, TOL)
        assert_rel_error(self, comp.unknowns['T_cold_out'], 749.96, TOL)
        
        #check off design 
        comp.params['design'] = False
        
        p.run()

        assert_rel_error(self, comp.unknowns['flow_out:out:Tt'], 539.94, TOL)
        assert_rel_error(self, comp.unknowns['Qreleased'], 327.22, TOL)
        assert_rel_error(self, comp.unknowns['Qabsorbed'], 327.22, TOL)
        assert_rel_error(self, comp.unknowns['Qmax'], 335.1, TOL)
        assert_rel_error(self, comp.unknowns['T_cold_out'], 749.96, TOL)
示例#10
0
    def test_conflicting_connections(self):
        # verify we get an error if we have conflicting implicit and explicit connections
        root = Group()

        # promoting G1.x will create an implicit connection to G3.x
        # this is a conflict because G3.x (aka G3.C4.x) is already connected
        # to G3.C3.x
        G2 = root.add('G2', Group(), promotes=['x'])  # BAD PROMOTE
        G2.add('C1', ParamComp('x', 5.), promotes=['x'])

        G1 = G2.add('G1', Group(), promotes=['x'])
        G1.add('C2', ExecComp('y=x*2.0'), promotes=['x'])

        G3 = root.add('G3', Group(), promotes=['x'])
        G3.add('C3', ExecComp('y=x*2.0'))
        G3.add('C4', ExecComp('y=x*2.0'), promotes=['x'])

        root.connect('G2.G1.C2.y', 'G3.C3.x')
        G3.connect('C3.y', 'x')

        prob = Problem(root)

        try:
            prob.setup(check=False)
        except Exception as error:
            msg = "Target 'G3.C4.x' is connected to multiple unknowns: ['G2.C1.x', 'G3.C3.y']"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")
    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)
    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', IndepVarComp('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)
示例#13
0
    def test_calc_gradient(self):
        root = Group()
        parm = root.add("parm", ParamComp("x", np.array([1.0, 1.0, 1.0, 1.0])))
        comp = root.add("comp", RosenSuzuki())

        root.connect("parm.x", "comp.x")

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

        param_list = ["parm.x"]
        unknown_list = ["comp.f", "comp.g"]

        # check that calc_gradient returns proper dict value when mode is 'fwd'
        J = prob.calc_gradient(param_list, unknown_list, mode="fwd", return_format="dict")
        np.testing.assert_almost_equal(J["comp.f"]["parm.x"], np.array([[-3.0, -3.0, -17.0, 9.0]]))
        np.testing.assert_almost_equal(
            J["comp.g"]["parm.x"], np.array([[3.0, 1.0, 3.0, 1.0], [1.0, 4.0, 2.0, 3.0], [6.0, 1.0, 2.0, -1.0]])
        )

        # check that calc_gradient returns proper array value when mode is 'fwd'
        J = prob.calc_gradient(param_list, unknown_list, mode="fwd", return_format="array")
        np.testing.assert_almost_equal(
            J, np.array([[-3.0, -3.0, -17.0, 9.0], [3.0, 1.0, 3.0, 1.0], [1.0, 4.0, 2.0, 3.0], [6.0, 1.0, 2.0, -1.0]])
        )

        # check that calc_gradient returns proper dict value when mode is 'rev'
        J = prob.calc_gradient(param_list, unknown_list, mode="rev", return_format="dict")
        np.testing.assert_almost_equal(J["comp.f"]["parm.x"], np.array([[-3.0, -3.0, -17.0, 9.0]]))
        np.testing.assert_almost_equal(
            J["comp.g"]["parm.x"], np.array([[3.0, 1.0, 3.0, 1.0], [1.0, 4.0, 2.0, 3.0], [6.0, 1.0, 2.0, -1.0]])
        )

        # check that calc_gradient returns proper array value when mode is 'rev'
        J = prob.calc_gradient(param_list, unknown_list, mode="rev", return_format="array")
        np.testing.assert_almost_equal(
            J, np.array([[-3.0, -3.0, -17.0, 9.0], [3.0, 1.0, 3.0, 1.0], [1.0, 4.0, 2.0, 3.0], [6.0, 1.0, 2.0, -1.0]])
        )

        # check that calc_gradient returns proper dict value when mode is 'fd'
        J = prob.calc_gradient(param_list, unknown_list, mode="fd", return_format="dict")
        np.testing.assert_almost_equal(J["comp.f"]["parm.x"], np.array([[-3.0, -3.0, -17.0, 9.0]]), decimal=5)
        np.testing.assert_almost_equal(
            J["comp.g"]["parm.x"],
            np.array([[3.0, 1.0, 3.0, 1.0], [1.0, 4.0, 2.0, 3.0], [6.0, 1.0, 2.0, -1.0]]),
            decimal=5,
        )

        # check that calc_gradient returns proper array value when mode is 'fd'
        J = prob.calc_gradient(param_list, unknown_list, mode="fd", return_format="array")
        np.testing.assert_almost_equal(
            J,
            np.array([[-3.0, -3.0, -17.0, 9.0], [3.0, 1.0, 3.0, 1.0], [1.0, 4.0, 2.0, 3.0], [6.0, 1.0, 2.0, -1.0]]),
            decimal=5,
        )
示例#14
0
    def test_variables(self):
        group = Group()
        group.add('C1', ExecComp('y=x*2.0'), promotes=['x'])
        group.add("C2", ExecComp('y=x*2.0'), promotes=['y'])

        # paths must be initialized prior to calling _setup_variables
        group._setup_paths('')
        params_dict, unknowns_dict = group._setup_variables()

        self.assertEqual(list(params_dict.keys()), ['C1.x', 'C2.x'])
        self.assertEqual(list(unknowns_dict.keys()), ['C1.y', 'C2.y'])

        self.assertEqual([m['promoted_name'] for n,m in params_dict.items()], ['x', 'C2.x'])
        self.assertEqual([m['promoted_name'] for n,m in unknowns_dict.items()], ['C1.y', 'y'])
示例#15
0
    def test_variables(self):
        group = Group()
        group.add("C1", ExecComp("y=x*2.0"), promotes=["x"])
        group.add("C2", ExecComp("y=x*2.0"), promotes=["y"])

        # paths must be initialized prior to calling _setup_variables
        group._setup_paths("")
        params_dict, unknowns_dict = group._setup_variables()

        self.assertEqual(list(params_dict.keys()), ["C1.x", "C2.x"])
        self.assertEqual(list(unknowns_dict.keys()), ["C1.y", "C2.y"])

        self.assertEqual([m["promoted_name"] for n, m in params_dict.items()], ["x", "C2.x"])
        self.assertEqual([m["promoted_name"] for n, m in unknowns_dict.items()], ["C1.y", "y"])
示例#16
0
    def setUp(self):
        self.comp = comp = Nozzle()
        g = Group()
        g.add('comp', comp)
        self.p = p = Problem(root=g)
        p.setup(check=False)
        
        comp.params['flow_in:in:W'] = 100.0
        comp.params['flow_in:in:Tt'] = 700.0
        comp.params['flow_in:in:Pt'] = 50.0
        comp.params['flow_in:in:Mach'] = 0.40
        comp.params['back_Ps'] = 15.0
        comp.params['design'] = True

        p.run()
示例#17
0
def build_sequence(child_factory, num_children, conns=(), parent=None):
    if parent is None:
        parent = Group()

    cnames = []
    for i in range(num_children):
        child = child_factory()
        cname = _child_name(child, i)
        parent.add(cname, child)
        if i:
            for u, v in conns:
                parent.connect('.'.join((cnames[-1], u)), '.'.join((cname, v)))
        cnames.append(cname)

    return parent
示例#18
0
    def test_multiple_connect(self):
        root = Group()
        C1 = root.add("C1", ExecComp("y=x*2.0"))
        C2 = root.add("C2", ExecComp("y=x*2.0"))
        C3 = root.add("C3", ExecComp("y=x*2.0"))

        root.connect("C1.y", ["C2.x", "C3.x"])

        root._setup_paths("")
        params_dict, unknowns_dict = root._setup_variables()

        # verify we get correct connection information
        connections = root._get_explicit_connections()
        expected_connections = {"C2.x": ["C1.y"], "C3.x": ["C1.y"]}
        self.assertEqual(connections, expected_connections)
示例#19
0
    def test_multiple_connect(self):
        root = Group()
        C1 = root.add('C1', ExecComp('y=x*2.0'))
        C2 = root.add('C2', ExecComp('y=x*2.0'))
        C3 = root.add('C3', ExecComp('y=x*2.0'))

        root.connect('C1.y', ['C2.x', 'C3.x'])

        root._setup_paths('')
        params_dict, unknowns_dict = root._setup_variables()

        # verify we get correct connection information
        connections = root._get_explicit_connections()
        expected_connections = {'C2.x': ['C1.y'], 'C3.x': ['C1.y']}
        self.assertEqual(connections, expected_connections)
示例#20
0
    def test_splitterW(self):
        g = Group()
        p = Problem(root=g)
        comp = g.add('comp', SplitterW())
        p.setup(check=False)
        
        comp.params['W1_des'] = 1.08
        comp.params['MNexit1_des'] = 1.0
        comp.params['MNexit2_des'] = 1.0
        comp.params['design'] = True

        comp.params['flow_in:in:W'] = 3.48771299
        comp.params['flow_in:in:Tt'] = 630.74523
        comp.params['flow_in:in:Pt'] = 0.0271945
        comp.params['flow_in:in:Mach'] = 1.0
        p.run()
        self.check(comp)

        comp.params['design'] = False
        comp.params['flow_out_1:in:is_super'] = True
        comp.params['flow_out_2:in:is_super'] = True
        p.run()
        self.check(comp)

        comp.params['flow_in:in:W'] *= 0.95
        comp.params['flow_out_1:in:is_super'] = False
        comp.params['flow_out_2:in:is_super'] = False
        p.run()
        TOL = 0.001
        assert_rel_error(self, comp.unknowns['flow_out_1:out:Mach'], 0.76922, TOL)
        assert_rel_error(self, comp.unknowns['flow_out_2:out:Mach'], 0.76922, TOL)
示例#21
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)
示例#22
0
def build_sequence(child_factory, num_children, conns=(), parent=None):
    if parent is None:
        parent = Group()

    cnames = []
    for i in range(num_children):
        child = child_factory()
        cname = _child_name(child, i)
        parent.add(cname, child)
        if i:
            for u,v in conns:
                parent.connect('.'.join((cnames[-1],u)),
                               '.'.join((cname,v)))
        cnames.append(cname)

    return parent
    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)
示例#24
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)
示例#25
0
    def test_simple_matvec(self):
        group = Group()
        group.add('x_param', IndepVarComp('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)
示例#26
0
    def test_nozzle_very_low_temperatures(self): 
        comp = Nozzle()
        g = Group()
        g.add('comp', comp)
        p = Problem(root=g)
        p.setup(check=False)

        comp.params['flow_in:in:W'] = 0.639
        comp.params['flow_in:in:Tt'] = 540.0
        comp.params['flow_in:in:Pt'] = 0.34
        comp.params['flow_in:in:Mach'] = 0.4
        comp.params['back_Ps'] = 0.0272
        comp.params['design'] = True
        
        p.run()

        TOL = 0.01 #this test needs larger tollerance due to exteremely low temperatures
        assert_rel_error(self, comp.unknowns['flow_out:out:W'], 0.639, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Pt'], 0.34, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Tt'], 540.0, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Mach'], 2.7092, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:area'], 264.204, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:rhos'], .000177443, TOL)
        assert_rel_error(self, comp.unknowns['Fg'], 38.98, TOL)

        #off design calcs
        comp.params['design'] = False
        p.run()

        self.assertEqual(comp.unknowns['switchRegime'], 'PERFECTLY_EXPANDED')
        assert_rel_error(self, comp.unknowns['flow_out:out:W'], 0.639, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Pt'], 0.34, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Tt'], 540.0, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Mach'], 2.7092, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:area'], 264.204, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:rhos'], 0.000177443, TOL)

        comp.params['back_Ps'] = 0.03
        p.run()

        self.assertEqual(comp.unknowns['switchRegime'], 'OVEREXPANDED')

        comp.params['back_Ps'] = 0.026
        p.run()

        self.assertEqual(comp.unknowns['switchRegime'], 'UNDEREXPANDED')
示例#27
0
    def test_simple_in_group_matvec(self):
        group = Group()
        sub = group.add('sub', Group(), promotes=['x', 'y'])
        group.add('x_param', ParamComp('x', 1.0), promotes=['*'])
        sub.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])

        prob = Problem()
        prob.root = group
        prob.root.ln_solver = ExplicitSolver()
        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)
示例#28
0
    def test_compressor(self):
        comp = Compressor()
        g = Group()
        g.add('comp', comp)
        p = Problem(root=g)
        p.setup()

        comp.params['PR_des'] = 12.47
        comp.params['MNexit_des'] = 0.4
        comp.params['eff_des'] = 0.8
        comp.params['flow_in:in:W'] = 1.08
        comp.params['flow_in:in:Tt'] = 630.74523
        comp.params['flow_in:in:Pt'] = 0.0271945
        comp.params['flow_in:in:Mach'] = 0.6
        comp.params['design'] = True

        p.run()

        TOL = 0.001
        assert_rel_error(self, comp.unknowns['flow_out:out:W'], 1.08, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Pt'], 0.33899, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Tt'], 1424.01, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:rhos'], 0.000594, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Mach'], 0.4 ,TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:area'], 364.7, TOL)
        assert_rel_error(self, comp.unknowns['pwr'], 303.2, TOL)
        assert_rel_error(self, comp.unknowns['eff_poly'], 0.8545, TOL)

        # run off design
        comp.params['design'] = False
        p.run()

        # values should remain unchanged in off-design at design condition
        assert_rel_error(self, comp.unknowns['flow_out:out:W'], 1.08, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Pt'], 0.33899, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Tt'], 1424.01, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:rhos'], 0.000594, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Mach'], 0.4 ,TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:area'], 364.7, TOL)
        assert_rel_error(self, comp.unknowns['pwr'], 303.2, TOL)
        assert_rel_error(self, comp.unknowns['eff_poly'], 0.8545, TOL)

        # try changing something
        comp.params['flow_in:in:W'] *= 1.1
        p.run()
        assert_rel_error(self, comp.unknowns['PR'], 13.52995, TOL)
示例#29
0
    def test_variables(self):
        group = Group()
        group.add('C1', ExecComp('y=x*2.0'), promotes=['x'])
        group.add("C2", ExecComp('y=x*2.0'), promotes=['y'])

        # paths must be initialized prior to calling _setup_variables
        group._setup_paths('')
        params_dict, unknowns_dict = group._setup_variables()

        self.assertEqual(list(params_dict.keys()), ['C1.x', 'C2.x'])
        self.assertEqual(list(unknowns_dict.keys()), ['C1.y', 'C2.y'])

        self.assertEqual([m['promoted_name'] for n, m in params_dict.items()],
                         ['x', 'C2.x'])
        self.assertEqual(
            [m['promoted_name'] for n, m in unknowns_dict.items()],
            ['C1.y', 'y'])
示例#30
0
    def test_multiple_connect(self):
        root = Group()
        C1 = root.add('C1', ExecComp('y=x*2.0'))
        C2 = root.add('C2', ExecComp('y=x*2.0'))
        C3 = root.add('C3', ExecComp('y=x*2.0'))

        root.connect('C1.y',['C2.x', 'C3.x'])

        root._setup_paths('')
        params_dict, unknowns_dict = root._setup_variables()

        # verify we get correct connection information
        connections = root._get_explicit_connections()
        expected_connections = {
            'C2.x': ['C1.y'],
            'C3.x': ['C1.y']
        }
        self.assertEqual(connections, expected_connections)
示例#31
0
    def test_conflicting_promoted_state_vars(self):
        # verify we get an error if we have conflicting promoted state variables
        root = Group()

        comp1 = SimpleImplicitComp()
        comp2 = SimpleImplicitComp()

        root.add('c1', comp1, promotes=['z'])  # promote the state, z
        root.add('c2', comp2, promotes=['z'])  # promote the state, z, again.. BAD

        prob = Problem(root)

        with self.assertRaises(RuntimeError) as err:
            prob.setup(check=False)

        expected_msg = "Promoted name 'z' matches multiple unknowns: ['c1.z', 'c2.z']"

        self.assertEqual(str(err.exception), expected_msg)
示例#32
0
    def test_inlet(self):
        comp = Inlet()
        g = Group()
        g.add('comp', comp)
        p = Problem(root=g)
        p.setup()

        comp.params['ram_recovery'] = 1.0
        comp.params['MNexit_des'] = 0.6
        comp.params['flow_in:in:W'] = 1.08
        comp.params['flow_in:in:Tt'] = 630.75
        comp.params['flow_in:in:Pt'] = 0.0272
        comp.params['flow_in:in:Mach'] = 1.0
        comp.params['design'] = True
        p.run()

        TOL = 0.005
        assert_rel_error(self, comp.unknowns['flow_out:out:W'], 1.080, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Pt'], 0.0272, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Tt'], 630.75, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:rhos'], 0.000098, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Mach'], 0.6, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:area'], 2230.8, TOL)

        #check off design
        comp.params['design'] = False
        p.run()

        assert_rel_error(self, comp.unknowns['flow_out:out:W'], 1.080, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Pt'], 0.0272, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Tt'], 630.75, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:rhos'], 0.000098, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Mach'], 0.6, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:area'], 2230.8, TOL)

        #vary something
        comp.params['flow_in:in:W'] = 0.9
        p.run()

        assert_rel_error(self, comp.unknowns['flow_out:out:W'], 0.9, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Pt'], 0.0272, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Tt'], 630.75, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:Mach'], 0.45955, TOL)
        assert_rel_error(self, comp.unknowns['flow_out:out:area'], 2230.8, TOL)
    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)
示例#34
0
    def test_conflicting_promoted_state_vars(self):
        # verify we get an error if we have conflicting promoted state variables
        root = Group()

        comp1 = SimpleImplicitComp()
        comp2 = SimpleImplicitComp()

        root.add('c1', comp1, promotes=['z'])  # promote the state, z
        root.add('c2', comp2,
                 promotes=['z'])  # promote the state, z, again.. BAD

        prob = Problem(root)

        with self.assertRaises(RuntimeError) as err:
            prob.setup(check=False)

        expected_msg = "Promoted name 'z' matches multiple unknowns: ['c1.z', 'c2.z']"

        self.assertEqual(str(err.exception), expected_msg)
示例#35
0
    def test_array2D(self):
        group = Group()
        group.add('x_param', IndepVarComp('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)
示例#36
0
    def test_two_simple(self):
        group = Group()
        group.add('x_param', IndepVarComp('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)
    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)
示例#38
0
    def test_calc_gradient_interface_errors(self):

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

        try:
            prob.calc_gradient(['comp.x'], ['comp.y'], mode='junk')
        except Exception as error:
            msg = "mode must be 'auto', 'fwd', 'rev', or 'fd'"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")

        try:
            prob.calc_gradient(['comp.x'], ['comp.y'], return_format='junk')
        except Exception as error:
            msg = "return_format must be 'array' or 'dict'"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")
示例#39
0
    def test_calc_gradient_interface_errors(self):

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

        try:
            prob.calc_gradient(['comp.x'], ['comp.y'], mode='junk')
        except Exception as error:
            msg = "mode must be 'auto', 'fwd', 'rev', or 'fd'"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")

        try:
            prob.calc_gradient(['comp.x'], ['comp.y'], return_format='junk')
        except Exception as error:
            msg = "return_format must be 'array' or 'dict'"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")
示例#40
0
    def test_add(self):

        group = Group()
        comp = ExecComp('y=x*2.0')
        group.add('mycomp', comp)

        subs = list(group.subsystems())
        self.assertEqual(len(subs), 1)
        self.assertEqual(subs[0], comp)
        self.assertEqual(subs[0].name, 'mycomp')

        comp2 = ExecComp('y=x*2.0')
        group.add("nextcomp", comp2)

        subs = list(group.subsystems())
        self.assertEqual(len(subs), 2)
        self.assertEqual(subs[0], comp)
        self.assertEqual(subs[1], comp2)

        with self.assertRaises(RuntimeError) as cm:
            group.add('mycomp', comp)

        expected_msg = "Group '' already contains a subsystem with name 'mycomp'."

        self.assertEqual(str(cm.exception), expected_msg)
示例#41
0
    def test_add(self):

        group = Group()
        comp = ExecComp('y=x*2.0')
        group.add('mycomp', comp)

        subs = list(group.subsystems())
        self.assertEqual(len(subs), 1)
        self.assertEqual(subs[0], comp)
        self.assertEqual(subs[0].name, 'mycomp')

        comp2 = ExecComp('y=x*2.0')
        group.add("nextcomp", comp2)

        subs = list(group.subsystems())
        self.assertEqual(len(subs), 2)
        self.assertEqual(subs[0], comp)
        self.assertEqual(subs[1], comp2)

        with self.assertRaises(RuntimeError) as cm:
            group.add('mycomp', comp)

        expected_msg = "Group '' already contains a subsystem with name 'mycomp'."

        self.assertEqual(str(cm.exception), expected_msg)
示例#42
0
    def test_too_few_procs(self):
        size = 3
        group = Group()
        group.add('P', IndepVarComp('x', numpy.ones(size)))
        group.add('C1', DistribExecComp(['y=2.0*x'], arr_size=size,
                                           x=numpy.zeros(size),
                                           y=numpy.zeros(size)))
        group.add('C2', ExecComp(['z=3.0*y'], y=numpy.zeros(size),
                                           z=numpy.zeros(size)))

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.connect('P.x', 'C1.x')
        prob.root.connect('C1.y', 'C2.y')

        try:
            prob.setup(check=False)
        except Exception as err:
            self.assertEqual(str(err),
                             "This problem was given 1 MPI processes, "
                             "but it requires between 2 and 2.")
        else:
            if MPI:  # pragma: no cover
                self.fail("Exception expected")
示例#43
0
    def test_src_indices_error(self):
        size = 3
        group = Group()
        group.add('P', IndepVarComp('x', numpy.ones(size)))
        group.add('C1', DistribExecComp(['y=2.0*x'], arr_size=size,
                                           x=numpy.zeros(size),
                                           y=numpy.zeros(size)))
        group.add('C2', ExecComp(['z=3.0*y'], y=numpy.zeros(size),
                                           z=numpy.zeros(size)))

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = LinearGaussSeidel()
        prob.root.connect('P.x', 'C1.x')
        prob.root.connect('C1.y', 'C2.y')

        prob.driver.add_desvar('P.x')
        prob.driver.add_objective('C1.y')

        try:
            prob.setup(check=False)
        except Exception as err:
            self.assertEqual(str(err),
               "'C1.y' is a distributed variable and may not be used as a "
               "design var, objective, or constraint.")
        else:
            if MPI:  # pragma: no cover
                self.fail("Exception expected")
示例#44
0
    def test_indices(self):
        size = 10

        root = Group()

        root.add('P1', ParamComp('x', np.zeros(size)))
        root.add('C1', ExecComp('y = x * 2.', y=np.zeros(size//2), x=np.zeros(size//2)))
        root.add('C2', ExecComp('y = x * 3.', y=np.zeros(size//2), x=np.zeros(size//2)))

        root.connect('P1.x', "C1.x", src_indices=list(range(size//2)))
        root.connect('P1.x', "C2.x", src_indices=list(range(size//2, size)))

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

        root.P1.unknowns['x'][0:size//2] += 1.0
        root.P1.unknowns['x'][size//2:size] -= 1.0

        prob.run()

        assert_rel_error(self, root.C1.params['x'], np.ones(size//2), 0.0001)
        assert_rel_error(self, root.C2.params['x'], -np.ones(size//2), 0.0001)
示例#45
0
    def test_simple_matvec_subbed_like_multipoint(self):
        group = Group()
        group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])

        prob = Problem()
        prob.root = Group()
        prob.root.add('sub', group, promotes=['*'])
        prob.root.sub.add('x_param', ParamComp('x', 1.0), promotes=['*'])

        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)

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

        J = prob.calc_gradient(['x'], ['y'], mode='fd', return_format='array')
        assert_rel_error(self, J[0][0], 2.0, 1e-6)
示例#46
0
        # plt.title('Optimum Magnet Thickness')
        # plt.ylabel('Number of Magnets M')
        # plt.xlabel('Magnet Thickness d as %/ lamda')
        ay = fig.add_subplot(212)
        ay.plot(lamda2, Lh2)
        plt.title('Maximum Levitation Height for Wavelength')
        plt.xlabel('Wavelength lamda')
        plt.ylabel('Levitation Height y')
        plt.show()


if __name__ == "__main__":
    from openmdao.core.problem import Problem

    root = Group()
    root.add('lift', Lift())

    p = Problem(root)

    recorder = SqliteRecorder('maglev')
    recorder.options['record_params'] = True
    recorder.options['record_metadata'] = True
    p.driver.add_recorder(recorder)

    p.setup()
    p.run()
    p.root.dump()

    import sqlitedict
    from pprint import pprint
示例#47
0
    if 'petsc' in sys.argv:
        from openmdao.core.petsc_impl import PetscImpl
        impl = PetscImpl
    else:
        from openmdao.core.basic_impl import BasicImpl
        impl = BasicImpl

    g = Group()
    p = Problem(impl=impl, root=g)

    if 'gmres' in sys.argv:
        from openmdao.solvers.scipy_gmres import ScipyGMRES
        p.root.ln_solver = ScipyGMRES()

    g.add("P", IndepVarComp('x', numpy.ones(vec_size)))

    p.driver.add_desvar("P.x")

    par = g.add("par", ParallelGroup())
    for pt in range(pts):
        ptname = "G%d" % pt
        ptg = par.add(ptname, Group())
        create_dyncomps(ptg,
                        num_comps,
                        2,
                        2,
                        2,
                        var_factory=lambda: numpy.zeros(vec_size))
        g.connect("P.x", "par.%s.C0.p0" % ptname)
示例#48
0
        unknowns['Qout_tot'] = unknowns['Qradiated_tot'] + unknowns['Qradiated_nat_convection_per_area']
        unknowns['Qin_tot'] = unknowns['Qsolar_tot'] + unknowns['heat_rate_tot']
        unknowns['Q_resid'] = abs(unknowns['Qout_tot'] - unknowns['Qin_tot'])

if __name__ == '__main__':
    from openmdao.core.group import Group
    from openmdao.core.problem import Problem
    from openmdao.drivers.scipy_optimizer import ScipyOptimizer
    from openmdao.components.param_comp import ParamComp
    from openmdao.components.constraint import ConstraintComp

    g = Group()
    p = Problem(root=g, driver=ScipyOptimizer())
    p.driver.options['optimizer'] = 'COBYLA'

    g.add('temp_boundary', ParamComp('T', 340.0))
    g.add('tube_wall', TubeWallTemp())
    g.connect('temp_boundary.T', 'tube_wall.temp_boundary')
    g.add('con', ConstraintComp('temp_boundary > 305.7', out='out'))
    g.connect('temp_boundary.T', 'con.temp_boundary')
    
    p.driver.add_param('temp_boundary.T', low=0.0, high=10000.0)
    p.driver.add_objective('tube_wall.Q_resid')
    p.driver.add_constraint('con.out')

    p.setup()

    g.tube_wall.params['flow_nozzle:in:Tt'] = 1710.0
    g.tube_wall.params['flow_nozzle:in:Pt'] = 0.304434211
    g.tube_wall.params['flow_nozzle:in:W'] = 1.08
    g.tube_wall.params['flow_bearings:in:W'] = 0.0
示例#49
0
    def test_calc_gradient(self):
        root = Group()
        parm = root.add('parm', ParamComp('x', np.array([1., 1., 1., 1.])))
        comp = root.add('comp', RosenSuzuki())

        root.connect('parm.x', 'comp.x')

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

        param_list = ['parm.x']
        unknown_list = ['comp.f', 'comp.g']

        # check that calc_gradient returns proper dict value when mode is 'fwd'
        J = prob.calc_gradient(param_list,
                               unknown_list,
                               mode='fwd',
                               return_format='dict')
        np.testing.assert_almost_equal(J['comp.f']['parm.x'],
                                       np.array([
                                           [-3., -3., -17., 9.],
                                       ]))
        np.testing.assert_almost_equal(
            J['comp.g']['parm.x'],
            np.array([
                [3., 1., 3., 1.],
                [1., 4., 2., 3.],
                [6., 1., 2., -1.],
            ]))

        # check that calc_gradient returns proper array value when mode is 'fwd'
        J = prob.calc_gradient(param_list,
                               unknown_list,
                               mode='fwd',
                               return_format='array')
        np.testing.assert_almost_equal(
            J,
            np.array([
                [-3., -3., -17., 9.],
                [3., 1., 3., 1.],
                [1., 4., 2., 3.],
                [6., 1., 2., -1.],
            ]))

        # check that calc_gradient returns proper dict value when mode is 'rev'
        J = prob.calc_gradient(param_list,
                               unknown_list,
                               mode='rev',
                               return_format='dict')
        np.testing.assert_almost_equal(J['comp.f']['parm.x'],
                                       np.array([
                                           [-3., -3., -17., 9.],
                                       ]))
        np.testing.assert_almost_equal(
            J['comp.g']['parm.x'],
            np.array([
                [3., 1., 3., 1.],
                [1., 4., 2., 3.],
                [6., 1., 2., -1.],
            ]))

        # check that calc_gradient returns proper array value when mode is 'rev'
        J = prob.calc_gradient(param_list,
                               unknown_list,
                               mode='rev',
                               return_format='array')
        np.testing.assert_almost_equal(
            J,
            np.array([
                [-3., -3., -17., 9.],
                [3., 1., 3., 1.],
                [1., 4., 2., 3.],
                [6., 1., 2., -1.],
            ]))

        # check that calc_gradient returns proper dict value when mode is 'fd'
        J = prob.calc_gradient(param_list,
                               unknown_list,
                               mode='fd',
                               return_format='dict')
        np.testing.assert_almost_equal(J['comp.f']['parm.x'],
                                       np.array([
                                           [-3., -3., -17., 9.],
                                       ]),
                                       decimal=5)
        np.testing.assert_almost_equal(J['comp.g']['parm.x'],
                                       np.array([
                                           [3., 1., 3., 1.],
                                           [1., 4., 2., 3.],
                                           [6., 1., 2., -1.],
                                       ]),
                                       decimal=5)

        # check that calc_gradient returns proper array value when mode is 'fd'
        J = prob.calc_gradient(param_list,
                               unknown_list,
                               mode='fd',
                               return_format='array')
        np.testing.assert_almost_equal(J,
                                       np.array([
                                           [-3., -3., -17., 9.],
                                           [3., 1., 3., 1.],
                                           [1., 4., 2., 3.],
                                           [6., 1., 2., -1.],
                                       ]),
                                       decimal=5)