Example #1
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', IndepVarComp('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")
Example #2
0
    def test_generate_numpydocstring(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 = ScipyGMRES()

        test_string = prob.root.ln_solver.generate_docstring()

        original_string = \
"""    \"\"\"

    Options
    -------
    options['atol'] : float(1e-12)
        Absolute convergence tolerance.
    options['err_on_maxiter'] : bool(False)
        If True, raise an AnalysisError if not converged at maxiter.
    options['iprint'] : int(0)
        Set to 0 to disable printing, set to 1 to print the residual to stdout each iteration, set to 2 to print subiteration residuals as well.
    options['maxiter'] : int(1000)
        Maximum number of iterations.
    options['mode'] : str('auto')
        Derivative calculation mode, set to 'fwd' for forward mode, 'rev' for reverse mode, or 'auto' to let OpenMDAO determine the best mode.
    options['restart'] : int(20)
        Number of iterations between restarts. Larger values increase iteration cost, but may be necessary for convergence

    \"\"\"
"""
        for sorig, stest in zip(original_string.split('\n'),
                                test_string.split('\n')):
            self.assertEqual(sorig, stest)
Example #3
0
    def test_double_arraycomp(self):
        # Mainly testing a bug in the array return for multiple arrays

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

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = PetscKSP()
        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)
Example #4
0
    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)
def example():

    # simple test of module

    root = Group()
    root.add('bos_opex_test', FUSED_OpenMDAO(opex_csm_fused()), promotes=['*'])

    prob = Problem(root)
    prob.setup()

    prob[
        'machine_rating'] = 5000.0  # Need to manipulate input or underlying cprob[onent will not execute
    prob['net_aep'] = 1701626526.28
    prob['sea_depth'] = 20.0
    prob['year'] = 2009
    prob['month'] = 12
    prob['turbine_number'] = 100

    prob.run()
    print(
        "Average annual operational expenditures for an offshore wind plant with 100 NREL 5 MW turbines"
    )
    for io in root.unknowns:
        print(io + ' ' + str(root.unknowns[io]))

    prob['sea_depth'] = 0.0
    prob.run()
    print(
        "Average annual operational expenditures for an land-based wind plant with 100 NREL 5 MW turbines"
    )
    for io in root.unknowns:
        print(io + ' ' + str(root.unknowns[io]))
    def test_simple_matvec(self):
        class VerificationComp(SimpleCompDerivMatVec):
            def linearize(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)
    def test_simple_matvec(self):

        class VerificationComp(SimpleCompDerivMatVec):

            def linearize(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)
def example():

    # openmdao example of execution
    root = Group()
    root.add('bos_csm_test', FUSED_OpenMDAO(bos_csm_fused()), promotes=['*'])
    prob = Problem(root)
    prob.setup()

    prob['machine_rating'] = 5000.0
    prob['rotor_diameter'] = 126.0
    prob['turbine_cost'] = 5950209.28
    prob['hub_height'] = 90.0
    prob['RNA_mass'] = 256634.5  # RNA mass is not used in this simple model
    prob['turbine_number'] = 100
    prob['sea_depth'] = 20.0
    prob['year'] = 2009
    prob['month'] = 12
    prob['multiplier'] = 1.0

    prob.run()
    print(
        "Balance of Station Costs for an offshore wind plant with 100 NREL 5 MW turbines"
    )
    for io in root.unknowns:
        print(io + ' ' + str(root.unknowns[io]))

    prob['sea_depth'] = 0.0
    prob['turbine_cost'] = 5229222.77

    prob.run()
    print(
        "Balance of Station Costs for an land-based wind plant with 100 NREL 5 MW turbines"
    )
    for io in root.unknowns:
        print(io + ' ' + str(root.unknowns[io]))
Example #9
0
    def test_case1_vs_npss(self):

        root = Group()
        root.add('p', breakpoint_levitation.BreakPointDrag())
        root.add('q', breakpoint_levitation.MagMass())
        prob = Problem(root)
        prob.setup()

        prob['p.m_pod'] = 3000.0
        prob['p.b_res'] = 1.48
        prob['p.num_mag_hal'] = 4.0
        prob['p.mag_thk'] = .15
        prob['p.l_pod'] = 22.0
        prob['p.gamma'] = 1.0
        prob['p.w_mag'] = 3.0
        prob['p.spacing'] = 0.0
        prob['p.d_pod'] = 1.0
        prob['p.w_strip'] = .005
        prob['p.num_sheets'] = 1.0
        prob['p.delta_c'] = .0005334
        prob['p.strip_c'] = .0105
        prob['p.rc'] = 1.713e-8
        prob['p.MU0'] = 4.0 * np.pi * (1.0e-7)
        prob['p.track_factor'] = .75
        prob['p.vel_b'] = 23.0
        prob['p.h_lev'] = .01
        prob['p.g'] = 9.81

        prob['q.m_pod'] = 3000.0
        prob['q.mag_thk'] = .15
        prob['q.rho_mag'] = 7500.0
        prob['q.l_pod'] = 22.0
        prob['q.gamma'] = 1.0
        prob['q.cost_per_kg'] = 44.0
        prob['q.w_mag'] = 3.0
        prob['q.d_pod'] = 1.0
        prob['q.track_factor'] = .75

        prob.run()

        # Print Statement for debugging
        # print('track_ind is %12.12f' % prob['comp.Drag.track_ind'])

        # Test Values

        assert np.isclose(prob['q.mag_area'], 16.500000, rtol=.01)
        assert np.isclose(prob['q.m_mag'], 18562.500000, rtol=.01)
        assert np.isclose(prob['q.cost'], 816750.000000, rtol=.01)
        assert np.isclose(prob['q.total_pod_mass'], 21562.500000, rtol=.01)
        assert np.isclose(prob['p.lam'], 0.600000, rtol=.01)
        assert np.isclose(prob['p.track_ind'], 4.28571e-6, rtol=.01)
        assert np.isclose(prob['p.b0'], 1.055475, rtol=.01)
        assert np.isclose(prob['p.mag_area'], 16.500000, rtol=.01)
        assert np.isclose(prob['p.omegab'], 240.855437, rtol=.01)
        assert np.isclose(prob['p.w_track'], .75, rtol=.01)
        assert np.isclose(prob['p.fyu'], 520814.278077, rtol=.01)
        assert np.isclose(prob['p.fxu'], 2430517.899848, rtol=.01)
        assert np.isclose(prob['p.ld_ratio'], 0.214281, rtol=.01)
        assert np.isclose(prob['p.pod_weight'], 29430.000000, rtol=.01)
        assert np.isclose(prob['p.track_res'], 0.004817, rtol=.01)
def example_turbine():

    # openmdao example of execution
    root = Group()
    root.add('tcc_csm_test', FUSED_OpenMDAO(tcc_csm_fused()), promotes=['*'])
    prob = Problem(root)
    prob.setup()

    # simple test of module
    prob['rotor_diameter'] = 126.0
    prob['blade_number'] = 3
    prob['hub_height'] = 90.0    
    prob['machine_rating'] = 5000.0

    # Rotor force calculations for nacelle inputs
    maxTipSpd = 80.0
    maxEfficiency = 0.90201
    ratedWindSpd = 11.5064
    thrustCoeff = 0.50
    airDensity = 1.225

    ratedHubPower  = prob['machine_rating'] / maxEfficiency 
    rotorSpeed     = (maxTipSpd/(0.5*prob['rotor_diameter'])) * (60.0 / (2*np.pi))
    prob['rotor_thrust']  = airDensity * thrustCoeff * np.pi * prob['rotor_diameter']**2 * (ratedWindSpd**2) / 8
    prob['rotor_torque'] = ratedHubPower/(rotorSpeed*(np.pi/30))*1000
    
    prob['year'] = 2009
    prob['month'] = 12

    prob.run()
    
    print("The results for the NREL 5 MW Reference Turbine in an offshore 20 m water depth location are:")
    for io in root.unknowns:
        print(io + ' ' + str(root.unknowns[io]))
Example #11
0
def example_finance():

    # simple test of module

    # openmdao example of execution
    root = Group()
    root.add('fin_csm_test', FUSED_OpenMDAO(fin_csm_fused(fixed_charge_rate = 0.12, construction_finance_rate=0.0, tax_rate = 0.4, discount_rate = 0.07, \
                      construction_time = 1.0, project_lifetime = 20.0, sea_depth = 20.0)), promotes=['*'])
    prob = Problem(root)
    prob.setup()

    prob['turbine_cost'] = 6087803.555 / 50
    prob['turbine_number'] = 50
    preventative_opex = 401819.023
    lease_opex = 22225.395
    corrective_opex = 91048.387
    prob['avg_annual_opex'] = preventative_opex + corrective_opex + lease_opex
    prob['bos_costs'] = 7668775.3
    prob['net_aep'] = 15756299.843
    prob['sea_depth'] = 20.0

    prob.run()
    print(
        "Overall cost of energy for an offshore wind plant with 100 NREL 5 MW turbines"
    )
    for io in root.unknowns:
        print(io + ' ' + str(root.unknowns[io]))
Example #12
0
    def test_double_arraycomp(self):
        # Mainly testing a bug in the array return for multiple arrays

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

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = PetscKSP()
        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)
    def test_case1_vs_npss(self):

        root = Group()
        root.add('p', breakpoint_levitation.BreakPointDrag())
        root.add('q', breakpoint_levitation.MagMass())
        prob = Problem(root)
        prob.setup()

        prob['p.m_pod'] = 3000.0
        prob['p.b_res'] = 1.48 
        prob['p.num_mag_hal'] = 4.0
        prob['p.mag_thk'] = .15
        prob['p.l_pod'] = 22.0
        prob['p.gamma'] = 1.0
        prob['p.w_mag'] = 3.0
        prob['p.spacing'] = 0.0
        prob['p.d_pod'] = 1.0
        prob['p.w_strip'] = .005
        prob['p.num_sheets'] = 1.0
        prob['p.delta_c'] = .0005334
        prob['p.strip_c'] = .0105
        prob['p.rc'] = 1.713e-8
        prob['p.MU0'] = 4.0*np.pi*(1.0e-7)
        prob['p.track_factor'] = .75
        prob['p.vel_b'] = 23.0
        prob['p.h_lev'] = .01
        prob['p.g'] = 9.81 

        prob['q.m_pod'] = 3000.0
        prob['q.mag_thk'] = .15
        prob['q.rho_mag'] = 7500.0
        prob['q.l_pod'] = 22.0
        prob['q.gamma'] = 1.0
        prob['q.cost_per_kg'] = 44.0
        prob['q.w_mag'] = 3.0
        prob['q.d_pod'] = 1.0
        prob['q.track_factor'] = .75

        prob.run()

        # Print Statement for debugging
        # print('track_ind is %12.12f' % prob['comp.Drag.track_ind'])

        # Test Values

        assert np.isclose(prob['q.mag_area'], 16.500000, rtol = .01)
        assert np.isclose(prob['q.m_mag'], 18562.500000, rtol = .01)
        assert np.isclose(prob['q.cost'], 816750.000000, rtol = .01)
        assert np.isclose(prob['q.total_pod_mass'], 21562.500000, rtol = .01)
        assert np.isclose(prob['p.lam'], 0.600000, rtol = .01)
        assert np.isclose(prob['p.track_ind'], 4.28571e-6, rtol = .01)
        assert np.isclose(prob['p.b0'], 1.055475, rtol = .01)
        assert np.isclose(prob['p.mag_area'], 16.500000, rtol = .01)
        assert np.isclose(prob['p.omegab'], 240.855437, rtol = .01)
        assert np.isclose(prob['p.w_track'], .75, rtol = .01)
        assert np.isclose(prob['p.fyu'], 520814.278077, rtol = .01)
        assert np.isclose(prob['p.fxu'], 2430517.899848, rtol = .01)
        assert np.isclose(prob['p.ld_ratio'], 0.214281, rtol = .01)
        assert np.isclose(prob['p.pod_weight'], 29430.000000, rtol = .01)
        assert np.isclose(prob['p.track_res'], 0.004817, rtol = .01)
    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)
Example #15
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', IndepVarComp('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.assertTrue(msg in str(error))
        else:
            self.fail("Error expected")
    def test_generate_numpydocstring(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 = ScipyGMRES()

        test_string = prob.root.ln_solver.generate_docstring()

        original_string = """    \"\"\"

    Options
    -------
    options['atol'] : float(1e-12)
        Absolute convergence tolerance.
    options['err_on_maxiter'] : bool(False)
        If True, raise an AnalysisError if not converged at maxiter.
    options['iprint'] : int(0)
        Set to 0 to disable printing, set to 1 to print iteration totals to stdout, set to 2 to print the residual each iteration to stdout.
    options['maxiter'] : int(1000)
        Maximum number of iterations.
    options['mode'] : str('auto')
        Derivative calculation mode, set to 'fwd' for forward mode, 'rev' for reverse mode, or 'auto' to let OpenMDAO determine the best mode.
    options['restart'] : int(20)
        Number of iterations between restarts. Larger values increase iteration cost, but may be necessary for convergence

    \"\"\"
"""
        for sorig, stest in zip(original_string.split("\n"), test_string.split("\n")):
            self.assertEqual(sorig, stest)
    def test_double_arraycomp(self):
        # Mainly testing a bug in the array return for multiple arrays

        group = Group()
        group.add("x_param1", IndepVarComp("x1", np.ones((2))), promotes=["*"])
        group.add("x_param2", IndepVarComp("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)
Example #18
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', IndepVarComp('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 = "'G3': promoted name 'y' matches multiple unknowns: ('G3.C3.y', 'G3.C4.y')"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")
Example #19
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', IndepVarComp('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 = "'G3': promoted name 'y' matches multiple unknowns: ('G3.C3.y', 'G3.C4.y')"
            self.assertEqual(text_type(error), msg)
        else:
            self.fail("Error expected")
    def test_case1_vs_inductrack(self):

        root = Group()
        root.add('lev', levitation_group.LevGroup())
        prob = Problem(root)

        params = (('m_pod', 3000.0, {'units': 'kg'}),
              ('l_pod', 22.0, {'units': 'm'}),
              ('d_pod', 1.0, {'units': 'm'}),
              ('vel_b', 23.0, {'units': 'm/s'}),
              ('h_lev', 0.01, {'unit': 'm'}),
              ('vel', 350.0, {'units': 'm/s'}))

        prob.root.add('input_vars', IndepVarComp(params))

        prob.root.connect('input_vars.m_pod', 'lev.m_pod')
        prob.root.connect('input_vars.l_pod', 'lev.l_pod')
        prob.root.connect('input_vars.d_pod', 'lev.d_pod')
        prob.root.connect('input_vars.vel_b', 'lev.vel_b')
        prob.root.connect('input_vars.h_lev', 'lev.h_lev')
        prob.root.connect('input_vars.vel', 'lev.vel')

        prob.setup()

        prob['lev.Drag.b_res'] = 1.48
        prob['lev.Drag.num_mag_hal'] = 4.0
        prob['lev.Drag.gamma'] = 1.0
        prob['lev.Drag.w_mag'] = 3.0
        prob['lev.Drag.spacing'] = 0.0
        prob['lev.Drag.w_strip'] = .005
        prob['lev.Drag.num_sheets'] = 1.0
        prob['lev.Drag.delta_c'] = .0005334
        prob['lev.Drag.strip_c'] = .0105
        prob['lev.Drag.rc'] = 1.713e-8
        prob['lev.Drag.MU0'] = 4.0*np.pi*(1.0e-7)
        prob['lev.Drag.track_factor'] = .75
        prob['lev.Drag.g'] = 9.81 
        prob['lev.Drag.mag_thk'] = .15

        prob['lev.Mass.mag_thk'] = .15
        prob['lev.Mass.rho_mag'] = 7500.0
        prob['lev.Mass.gamma'] = 1.0
        prob['lev.Mass.cost_per_kg'] = 44.0
        prob['lev.Mass.w_mag'] = 3.0
        prob['lev.Mass.track_factor'] = .75

        prob.run()

        # Print Statements for debugging
        # print('Mag Mass %f' % prob['lev.m_mag'])
        # print('Mag Drag is %f' % prob['lev.mag_drag'])

        # Test Values

        assert np.isclose(prob['lev.mag_drag'], 9025.39, rtol=.01)
        assert np.isclose(prob['lev.total_pod_mass'], 21562.50, rtol=.01)
Example #21
0
 def test_bad_sysname(self):
     group = Group()
     try:
         group.add('0', ExecComp('y=x*2.0'), promotes=['x'])
     except NameError as err:
         self.assertEqual(str(err), ": '0' is not a valid system name.")
     try:
         group.add('foo:bar', ExecComp('y=x*2.0'), promotes=['x'])
     except NameError as err:
         self.assertEqual(str(err), ": 'foo:bar' is not a valid system name.")
Example #22
0
 def test_bad_sysname(self):
     group = Group()
     try:
         group.add("0", ExecComp("y=x*2.0"), promotes=["x"])
     except NameError as err:
         self.assertEqual(str(err), ": '0' is not a valid system name.")
     try:
         group.add("foo:bar", ExecComp("y=x*2.0"), promotes=["x"])
     except NameError as err:
         self.assertEqual(str(err), ": 'foo:bar' is not a valid system name.")
Example #23
0
 def test_bad_sysname(self):
     group = Group()
     try:
         group.add('0', ExecComp('y=x*2.0'), promotes=['x'])
     except NameError as err:
         self.assertEqual(str(err), ": '0' is not a valid system name.")
     try:
         group.add('foo:bar', ExecComp('y=x*2.0'), promotes=['x'])
     except NameError as err:
         self.assertEqual(str(err),
                          ": 'foo:bar' is not a valid system name.")
Example #24
0
    def test_multiple_connect_alt(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'))

        with self.assertRaises(TypeError) as err:
            root.connect('C1.y', 'C2.x', 'C3.x')

        msg = "src_indices must be an index array, did you mean connect('C1.y', ['C2.x', 'C3.x'])?"

        self.assertEqual(msg, str(err.exception))
Example #25
0
    def test_multiple_connect_alt(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"))

        with self.assertRaises(TypeError) as err:
            root.connect("C1.y", "C2.x", "C3.x")

        msg = "src_indices must be an index array, did you mean connect('C1.y', ['C2.x', 'C3.x'])?"

        self.assertEqual(msg, str(err.exception))
Example #26
0
    def test_calc_gradient(self):
        root = Group()
        root.add('indep', IndepVarComp('x', np.array([1., 1., 1., 1.])))
        root.add('comp', RosenSuzuki())

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

        subprob = Problem(root)
        subprob.driver.add_desvar('indep.x', lower=-10, upper=99)
        subprob.driver.add_objective('comp.f')
        subprob.driver.add_constraint('comp.g', upper=0.)

        prob = Problem(root=Group())
        prob.root.add('desvars', IndepVarComp('x', np.ones(4)))
        prob.root.add('subprob', SubProblem(subprob,
                                            params=['indep.x'],
                                            unknowns=['comp.f', 'comp.g']))
        prob.root.connect('desvars.x', 'subprob.indep.x')

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

        indep_list = ['desvars.x']
        unknown_list = ['subprob.comp.f', 'subprob.comp.g']

        # check that calc_gradient returns proper dict value when mode is 'fwd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')
        assert_almost_equal(J['subprob.comp.f']['desvars.x'],
                           expectedJ['subprob.comp.f']['desvars.x'])
        assert_almost_equal(J['subprob.comp.g']['desvars.x'],
                            expectedJ['subprob.comp.g']['desvars.x'])

        # check that calc_gradient returns proper array value when mode is 'fwd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='array')
        assert_almost_equal(J, expectedJ_array)

        # check that calc_gradient returns proper dict value when mode is 'rev'
        J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')
        assert_almost_equal(J['subprob.comp.f']['desvars.x'], expectedJ['subprob.comp.f']['desvars.x'])
        assert_almost_equal(J['subprob.comp.g']['desvars.x'], expectedJ['subprob.comp.g']['desvars.x'])

        # check that calc_gradient returns proper array value when mode is 'rev'
        J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='array')
        assert_almost_equal(J, expectedJ_array)

        # check that calc_gradient returns proper dict value when mode is 'fd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict')
        assert_almost_equal(J['subprob.comp.f']['desvars.x'], expectedJ['subprob.comp.f']['desvars.x'], decimal=5)
        assert_almost_equal(J['subprob.comp.g']['desvars.x'], expectedJ['subprob.comp.g']['desvars.x'], decimal=5)

        # check that calc_gradient returns proper array value when mode is 'fd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='array')
        assert_almost_equal(J, expectedJ_array, decimal=5)
Example #27
0
    def test_generate_numpydocstring(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 = ScipyGMRES()

        test_string = prob.root.ln_solver.generate_docstring()
        original_string = '    """\n\n    Options\n    -------\n    options[\'atol\'] :  float(1e-12)\n        Absolute convergence tolerance.\n    options[\'iprint\'] :  int(0)\n        Set to 0 to disable printing, set to 1 to print the residual to stdout each iteration, set to 2 to print subiteration residuals as well.\n    options[\'maxiter\'] :  int(1000)\n        Maximum number of iterations.\n    options[\'mode\'] :  str(\'auto\')\n        Derivative calculation mode, set to \'fwd\' for forward mode, \'rev\' for reverse mode, or \'auto\' to let OpenMDAO determine the best mode.\n    options[\'precondition\'] :  bool(False)\n        Set to True to turn on preconditioning.\n    options[\'restart\'] :  int(20)\n        Number of iterations between restarts. Larger values increase iteration cost, but may be necessary for convergence\n\n    """\n'
        self.assertEqual(original_string, test_string)
Example #28
0
    def test_calc_gradient_with_qoi_indices(self):
        q_idxs = [0, 2]

        root = Group()
        root.add('parm', IndepVarComp('x', np.array([1., 1., 1., 1.])))
        root.add('comp', RosenSuzuki())

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

        prob = Problem(root)
        prob.driver.add_desvar('parm.x', lower=-10, upper=99)
        prob.driver.add_objective('comp.f')
        prob.driver.add_constraint('comp.g', upper=0., indices=q_idxs)
        prob.setup(check=False)
        prob.run()

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

        # override expected array value to reflect qoi indices
        expectedJ_array = np.concatenate((
            expectedJ['comp.f']['parm.x'],
            expectedJ['comp.g']['parm.x'][q_idxs, :]
        ))

        # check that calc_gradient returns proper dict value when mode is 'fwd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='dict')
        assert_almost_equal(J['comp.f']['parm.x'], expectedJ['comp.f']['parm.x'])
        assert_almost_equal(J['comp.g']['parm.x'], expectedJ['comp.g']['parm.x'][q_idxs, :])

        # check that calc_gradient returns proper array value when mode is 'fwd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fwd', return_format='array')
        assert_almost_equal(J, expectedJ_array)

        # check that calc_gradient returns proper dict value when mode is 'rev'
        J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='dict')
        assert_almost_equal(J['comp.f']['parm.x'], expectedJ['comp.f']['parm.x'])
        assert_almost_equal(J['comp.g']['parm.x'], expectedJ['comp.g']['parm.x'][q_idxs, :])

        # check that calc_gradient returns proper array value when mode is 'rev'
        J = prob.calc_gradient(indep_list, unknown_list, mode='rev', return_format='array')
        assert_almost_equal(J, expectedJ_array)

        # check that calc_gradient returns proper dict value when mode is 'fd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='dict')
        assert_almost_equal(J['comp.f']['parm.x'], expectedJ['comp.f']['parm.x'],            decimal=5)
        assert_almost_equal(J['comp.g']['parm.x'], expectedJ['comp.g']['parm.x'][q_idxs, :], decimal=5)

        # check that calc_gradient returns proper array value when mode is 'fd'
        J = prob.calc_gradient(indep_list, unknown_list, mode='fd', return_format='array')
        assert_almost_equal(J, expectedJ_array, decimal=5)
Example #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'])

        prob = Problem()
        # paths must be initialized prior to calling _setup_variables
        group._init_sys_data('', prob._probdata)
        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'])
Example #30
0
    def test_simple_jac(self):
        group = Group()
        group.add("x_param", IndepVarComp("x", 1.0), promotes=["*"])
        group.add("mycomp", ExecComp(["y=2.0*x"]), promotes=["x", "y"])

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = PetscKSP()
        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)
Example #31
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)
Example #32
0
    def test_simple(self):
        group = Group()
        group.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])
        group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = PetscKSP()
        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)
Example #33
0
    def test_simple_jac(self):
        group = Group()
        group.add('x_param', IndepVarComp('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)
Example #34
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"])

        prob = Problem()
        root._init_sys_data("", prob._probdata)
        params_dict, unknowns_dict = root._setup_variables()

        # verify we get correct connection information
        connections = root._get_explicit_connections()
        expected_connections = {"C2.x": [("C1.y", None)], "C3.x": [("C1.y", None)]}
        self.assertEqual(connections, expected_connections)
Example #35
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"])

        prob = Problem(root=group)
        prob.setup(check=False)
        params_dict = prob.root._params_dict
        unknowns_dict = prob.root._unknowns_dict

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

        to_prom_name = prob.root._sysdata.to_prom_name
        self.assertEqual([to_prom_name[n] for n in params_dict], ["x", "C2.x"])
        self.assertEqual([to_prom_name[n] for n in unknowns_dict], ["C1.y", "y"])
Example #36
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'])

        prob = Problem(root=group)
        prob.setup(check=False)
        params_dict = prob.root._params_dict
        unknowns_dict = prob.root._unknowns_dict

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

        to_prom_name = prob.root._sysdata.to_prom_name
        self.assertEqual([to_prom_name[n] for n in params_dict], ['x', 'C2.x'])
        self.assertEqual([to_prom_name[n] for n in unknowns_dict], ['C1.y', 'y'])
    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 = 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)
Example #38
0
    def test_simple_jac(self):
        group = Group()
        group.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])
        group.add('mycomp', ExecComp(['y=2.0*x']), promotes=['x', 'y'])

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = PetscKSP()
        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)
Example #39
0
    def test_linear_system(self):
        root = Group()

        lingrp = root.add('lingrp', Group(), promotes=['*'])
        lingrp.add('lin', LinearSystem(3))
        lingrp.ln_solver = ScipyGMRES()

        x = np.array([1, 2, -3])
        A = np.array([[5.0, -3.0, 2.0], [1.0, 7.0, -4.0], [1.0, 0.0, 8.0]])
        b = A.dot(x)

        root.add('p1', IndepVarComp('A', A))
        root.add('p2', IndepVarComp('b', b))
        root.connect('p1.A', 'lin.A')
        root.connect('p2.b', 'lin.b')

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

        # Make sure it gets the right answer
        assert_rel_error(self, prob['lin.x'], x, .0001)
        assert_rel_error(self, np.linalg.norm(prob.root.resids.vec), 0.0,
                         1e-10)

        # Compare against calculated derivs
        Ainv = np.linalg.inv(A)
        dx_dA = np.outer(Ainv, -x).reshape(3, 9)
        dx_db = Ainv

        J = prob.calc_gradient(['p1.A', 'p2.b'], ['lin.x'],
                               mode='fwd',
                               return_format='dict')
        assert_rel_error(self, J['lin.x']['p1.A'], dx_dA, .0001)
        assert_rel_error(self, J['lin.x']['p2.b'], dx_db, .0001)

        J = prob.calc_gradient(['p1.A', 'p2.b'], ['lin.x'],
                               mode='rev',
                               return_format='dict')
        assert_rel_error(self, J['lin.x']['p1.A'], dx_dA, .0001)
        assert_rel_error(self, J['lin.x']['p2.b'], dx_db, .0001)

        J = prob.calc_gradient(['p1.A', 'p2.b'], ['lin.x'],
                               mode='fd',
                               return_format='dict')
        assert_rel_error(self, J['lin.x']['p1.A'], dx_dA, .0001)
        assert_rel_error(self, J['lin.x']['p2.b'], dx_db, .0001)
Example #40
0
    def test_simple_choose_different_alg(self):
        group = Group()
        group.add('x_param', IndepVarComp('x', 1.0), promotes=['*'])
        group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = PetscKSP()
        prob.root.ln_solver.options['ksp_type'] = 'gmres'
        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)
Example #41
0
    def test_simple_choose_different_alg(self):
        group = Group()
        group.add("x_param", IndepVarComp("x", 1.0), promotes=["*"])
        group.add("mycomp", SimpleCompDerivMatVec(), promotes=["x", "y"])

        prob = Problem(impl=impl)
        prob.root = group
        prob.root.ln_solver = PetscKSP()
        prob.root.ln_solver.options["ksp_type"] = "gmres"
        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)
Example #42
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'])

        prob = Problem(root=group)
        prob.setup(check=False)
        params_dict = prob.root._params_dict
        unknowns_dict = prob.root._unknowns_dict

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

        to_prom_name = prob.root._sysdata.to_prom_name
        self.assertEqual([to_prom_name[n] for n in params_dict], ['x', 'C2.x'])
        self.assertEqual([to_prom_name[n] for n in unknowns_dict],
                         ['C1.y', 'y'])
Example #43
0
def example():

    root = Group()
    root.add('aep_test', FUSED_OpenMDAO(aep_csm_fused()), promotes=['*'])

    prob = Problem(root)
    prob.setup()

    prob[
        'machine_rating'] = 5000.0  #Float(units = 'kW', iotype='in', desc= 'rated machine power in kW')
    prob[
        'max_tip_speed'] = 80.0  #Float(units = 'm/s', iotype='in', desc= 'maximum allowable tip speed for the rotor')
    prob[
        'rotor_diameter'] = 126.0  #Float(units = 'm', iotype='in', desc= 'rotor diameter of the machine')
    prob[
        'max_power_coefficient'] = 0.488  #Float(iotype='in', desc= 'maximum power coefficient of rotor for operation in region 2')
    prob[
        'opt_tsr'] = 7.525  #Float(iotype='in', desc= 'optimum tip speed ratio for operation in region 2')
    prob[
        'cut_in_wind_speed'] = 3.0  #Float(units = 'm/s', iotype='in', desc= 'cut in wind speed for the wind turbine')
    prob[
        'cut_out_wind_speed'] = 25.0  #Float(units = 'm/s', iotype='in', desc= 'cut out wind speed for the wind turbine')
    prob[
        'hub_height'] = 90.0  #Float(units = 'm', iotype='in', desc= 'hub height of wind turbine above ground / sea level')
    prob[
        'altitude'] = 0.0  #Float(units = 'm', iotype='in', desc= 'altitude of wind plant')
    prob[
        'air_density'] = 0  #Float(units = 'kg / (m * m * m)', iotype='in', desc= 'air density at wind plant site')  # default air density value is 0.0 - forces aero csm to calculate air density in model
    prob[
        'max_efficiency'] = 0.902  #Float(iotype='in', desc = 'maximum efficiency of rotor and drivetrain - at rated power')
    prob[
        'thrust_coefficient'] = 0.5  #Float(iotype='in', desc='thrust coefficient at rated power')
    prob['soiling_losses'] = 0.0
    prob['array_losses'] = 0.1
    prob['availability'] = 0.941
    prob['turbine_number'] = 100
    prob['shear_exponent'] = 0.1
    prob['wind_speed_50m'] = 8.02
    prob['weibull_k'] = 2.15

    prob.run()

    print("AEP output")
    for io in root.unknowns:
        print(io + ' ' + str(root.unknowns[io]))
    def test_simple_matvec_subbed(self):
        group = Group()
        group.add('mycomp', SimpleCompDerivMatVec(), promotes=['x', 'y'])

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

        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)
Example #45
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)
Example #46
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'])

        prob = Problem()
        root._init_sys_data('', prob._probdata)
        params_dict, unknowns_dict = root._setup_variables()

        # verify we get correct connection information
        connections = root._get_explicit_connections()
        expected_connections = {
            'C2.x': [('C1.y', None)],
            'C3.x': [('C1.y', None)]
        }
        self.assertEqual(connections, expected_connections)
Example #47
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'])

        prob = Problem()
        root._init_sys_data('', prob._probdata)
        params_dict, unknowns_dict = root._setup_variables()

        # verify we get correct connection information
        connections = root._get_explicit_connections()
        expected_connections = {
            'C2.x': [('C1.y', None)],
            'C3.x': [('C1.y', None)]
        }
        self.assertEqual(connections, expected_connections)
Example #48
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(impl=impl)
        prob.root = group
        prob.root.ln_solver = PetscKSP()
        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)
Example #49
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 = ScipyGMRES()
        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)
    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 = ScipyGMRES()
        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)
Example #51
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)
Example #52
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 = DirectSolver()
        prob.root.ln_solver.options['jacobian_method'] = 'assemble'
        prob.setup(check=False)
        prob.run()

        with self.assertRaises(RuntimeError) as cm:
            J = prob.calc_gradient(['x'], ['y'], mode='fwd', return_format='dict')

        expected_msg = "The 'assemble' jacobian_method is not supported when " + \
                       "'apply_linear' is used on a component (mycomp)."

        self.assertEqual(str(cm.exception), expected_msg)
Example #53
0
    def test_group_add(self):
        model = Group()
        ecomp = ExecComp('b=2.0*a', a=3.0, b=6.0)

        msg = "The 'add' method provides backwards compatibility with OpenMDAO <= 1.x ; " \
              "use 'add_subsystem' instead."

        with assert_warning(DeprecationWarning, msg):
            comp1 = model.add('comp1', ecomp)

        self.assertTrue(ecomp is comp1)
Example #54
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)
Example #55
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")
Example #56
0
    def test_array2D_no_decompose(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 = DirectSolver()
        prob.root.ln_solver.options['jacobian_method'] = 'assemble'
        prob.root.ln_solver.options['save_LU_decomposition'] = False
        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)
Example #57
0
    def test_src_indices(self):
        size = 10

        root = Group()

        root.add('P1', IndepVarComp('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)