Exemplo n.º 1
0
def magneplane_brachistochrone(solver='SLSQP', num_seg=3, seg_ncn=3):

    prob = Problem()
    traj = prob.add_traj(Trajectory("traj0"))

    if solver == 'SNOPT':
        if pyOptSparseDriver is None:
            raise ValueError('Requested SNOPT but pyoptsparse is not available')
        driver=pyOptSparseDriver()
        driver.options['optimizer'] = solver
        driver.opt_settings['Major iterations limit'] = 1000
        driver.opt_settings['iSumm'] = 6
        driver.opt_settings['Major step limit'] = 0.5
        driver.opt_settings["Major feasibility tolerance"] = 1.0E-6
        driver.opt_settings["Major optimality tolerance"] = 1.0E-6
        driver.opt_settings["Minor feasibility tolerance"] = 1.0E-4
        driver.opt_settings['Verify level'] = 3
    else:
        driver=ScipyOptimizer()
        driver.options['tol'] = 1.0E-6
        driver.options['disp'] = True
        driver.options['maxiter'] = 500

    prob.driver = driver

    dynamic_controls = [ {'name':'g','units':'m/s**2'},
                        {'name':'T','units':'N'},
                        {'name':'D','units':'N'},
                        {'name':'mass','units':'kg'},
                        {'name':'psi','units':'rad'},
                        {'name':'theta', 'units':'rad'},
                        {'name':'phi','units':'rad'} ]

    phase0 = CollocationPhase(name='phase0',rhs_class=MagneplaneRHS,num_seg=num_seg,seg_ncn=seg_ncn,rel_lengths="equal",
                              dynamic_controls=dynamic_controls,static_controls=None)

    traj.add_phase(phase0)

    phase0.set_state_options('x', lower=0,upper=10,ic_val=0,ic_fix=True,fc_val=10,fc_fix=True,defect_scaler=0.1)
    phase0.set_state_options('y', lower=0,upper=0,ic_val=0,ic_fix=True,fc_val=0,fc_fix=True,defect_scaler=0.1)
    phase0.set_state_options('z', lower=-10,upper=0,ic_val=-10,ic_fix=True,fc_val=-5,fc_fix=True,defect_scaler=0.1)
    phase0.set_state_options('v', lower=0, upper=np.inf,ic_val=0.0,ic_fix=True,fc_val=10.0,fc_fix=False,defect_scaler=0.1)

    phase0.set_dynamic_control_options(name='psi', val=phase0.node_space(0.0, 0.0), opt=False)
    phase0.set_dynamic_control_options(name='theta', val=phase0.node_space(-.46,-.46),opt=True,lower=-1.57,upper=1.57,scaler=1.0)
    phase0.set_dynamic_control_options(name='phi', val=phase0.node_space(0.0, 0.0), opt=False)

    phase0.set_dynamic_control_options(name='g', val=phase0.node_space(9.80665, 9.80665), opt=False)
    phase0.set_dynamic_control_options(name='T', val=phase0.node_space(0.0, 0.0), opt=False)
    phase0.set_dynamic_control_options(name='D', val=phase0.node_space(0.0, 0.0), opt=False)
    phase0.set_dynamic_control_options(name='mass', val=phase0.node_space(1000.0, 1000.0), opt=False)

    phase0.set_time_options(t0_val=0,t0_lower=0,t0_upper=0,tp_val=2.0,tp_lower=0.5,tp_upper=10.0)

    traj.add_objective(name="t",phase="phase0",place="end",scaler=1.0)

    return prob
Exemplo n.º 2
0
    def test_empty_jacobian(self):

        prob = Problem(root=Group())

        root = prob.root

        root.add(name="ivc_a",
                 system=IndepVarComp(name="a", val=5.0),
                 promotes=["a"])
        root.add(name="ivc_b",
                 system=IndepVarComp(name="b", val=10.0),
                 promotes=["b"])

        root.add(name="g", system=MyGroup())

        root.connect("a", "g.input.A")
        root.connect("b", "g.input.B")

        prob.driver = ScipyOptimizer()
        prob.driver.options["disp"] = False
        prob.driver.add_objective("g.exec.y")
        prob.driver.add_desvar(name="a")
        prob.driver.add_desvar(name="b")

        prob.setup(check=False)

        prob.run()
Exemplo n.º 3
0
    def test_undefined_jacobian(self):

        prob = Problem(root=Group())

        root = prob.root

        root.add(name="ivc_a",
                 system=IndepVarComp(name="a", val=5.0),
                 promotes=["a"])
        root.add(name="ivc_b",
                 system=IndepVarComp(name="b", val=10.0),
                 promotes=["b"])

        root.add(name="g", system=MyGroup3())

        root.connect("a", "g.input.A")
        root.connect("b", "g.input.B")

        prob.driver = ScipyOptimizer()
        prob.driver.options["disp"] = False
        prob.driver.add_objective("g.exec.y")
        prob.driver.add_desvar(name="a")
        prob.driver.add_desvar(name="b")

        prob.setup(check=False)

        try:
            prob.run()
        except ValueError as err:
            self.assertEqual(str(err),
                             "No derivatives defined for Component 'g.input'")
        else:
            self.fail("expecting ValueError due to undefined linearize")
Exemplo n.º 4
0
    def test_driver_unicode_variable(self):
        # this tests that unicode design variables and objectives works in python 2.
        prob = Problem(root=Group())
        root = prob.root

        # simple paraboloid example from tutorial
        root.add('p1', IndepVarComp('x0', 3.0), promotes=['*'])
        root.add('p2', IndepVarComp('y0', -4.0), promotes=['*'])
        root.add(
            'p',
            ExecComp('f_xy = (x0 - 3.0)**2 + x0 * y0 + (y0 + 4.0)**2 - 3.0'),
            promotes=['*'])

        prob.driver = ScipyOptimizer()
        prob.driver.options['optimizer'] = 'SLSQP'

        prob.driver.add_desvar(u'x0', lower=-50, upper=50)
        prob.driver.add_desvar(u'y0', lower=-50, upper=50)
        prob.driver.add_objective(u'f_xy')
        prob.driver.options['disp'] = False

        prob.setup(check=False)

        prob['x0'] = 3.0
        prob['y0'] = -4.0

        prob.run()

        assert_rel_error(self, prob['f_xy'], -27.33333, 1e-3)
Exemplo n.º 5
0
    def test_array_scaler_bug(self):
        class Paraboloid(Component):
            def __init__(self):
                super(Paraboloid, self).__init__()

                self.add_param('X', val=np.array([0.0, 0.0]))
                self.add_output('f_xy', val=0.0)

            def solve_nonlinear(self, params, unknowns, resids):
                X = params['X']
                x = X[0]
                y = X[1]
                unknowns['f_xy'] = (1000. * x - 3.)**2 + (1000. * x) * (
                    0.01 * y) + (0.01 * y + 4.)**2 - 3.

            def linearize(self, params, unknowns, resids):
                """ Jacobian for our paraboloid."""
                X = params['X']
                J = {}

                x = X[0]
                y = X[1]

                J['f_xy', 'X'] = np.array([[
                    2000000.0 * x - 6000.0 + 10.0 * y,
                    0.0002 * y + 0.08 + 10.0 * x
                ]])
                return J

        top = Problem()

        root = top.root = Group()
        root.deriv_options['type'] = 'fd'

        root.add('p1', IndepVarComp('X', np.array([3.0, -4.0])))
        root.add('p', Paraboloid())

        root.connect('p1.X', 'p.X')

        top.driver = ScipyOptimizer()
        top.driver.options['optimizer'] = 'SLSQP'
        top.driver.options['tol'] = 1e-12

        top.driver.add_desvar('p1.X',
                              lower=np.array([-1000.0, -1000.0]),
                              upper=np.array([1000.0, 1000.0]),
                              scaler=np.array([1000., 0.01]))
        top.driver.add_objective('p.f_xy')

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

        # Optimal solution (minimum): x = 6.6667; y = -7.3333
        # Note: this scaling isn't so great, but at least we know it works
        # and the bug is fixed.
        assert_rel_error(self, top['p1.X'][0], 6.666667 / 1000.0, 1e-3)
        assert_rel_error(self, top['p1.X'][1], -7.333333 / 0.01, 1e-3)

if __name__ == "__main__":

    top = Problem()

    root = top.root = Group()

    root.add('p1', ParamComp('x', 3.0))
    root.add('p2', ParamComp('y', -4.0))
    root.add('p', Paraboloid())

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

    top.driver = ScipyOptimizer()
    top.driver.options['optimizer'] = 'SLSQP'

    top.driver.add_param('p1.x', low=-50, high=50)
    top.driver.add_param('p2.y', low=-50, high=50)
    top.driver.add_objective('p.f_xy')

    top.setup()
    top.run()

    print('\n')
    print('Minimum of %f found at (%f, %f)' %
          (top['p.f_xy'], top['p.x'], top['p.y']))

    # Expected Output
    # Minimum of -27.333333 found at (6.666667, -7.333333)
Exemplo n.º 7
0
def magneplane_brachistochrone(solver='SLSQP', num_seg=3, seg_ncn=3):

    prob = Problem()
    traj = prob.add_traj(Trajectory("traj0"))

    if solver == 'SNOPT':
        if pyOptSparseDriver is None:
            raise ValueError(
                'Requested SNOPT but pyoptsparse is not available')
        driver = pyOptSparseDriver()
        driver.options['optimizer'] = solver
        driver.opt_settings['Major iterations limit'] = 1000
        driver.opt_settings['iSumm'] = 6
        driver.opt_settings['Major step limit'] = 0.5
        driver.opt_settings["Major feasibility tolerance"] = 1.0E-6
        driver.opt_settings["Major optimality tolerance"] = 1.0E-6
        driver.opt_settings["Minor feasibility tolerance"] = 1.0E-4
        driver.opt_settings['Verify level'] = 3
    else:
        driver = ScipyOptimizer()
        driver.options['tol'] = 1.0E-6
        driver.options['disp'] = True
        driver.options['maxiter'] = 500

    prob.driver = driver

    dynamic_controls = [{
        'name': 'g',
        'units': 'm/s**2'
    }, {
        'name': 'T',
        'units': 'N'
    }, {
        'name': 'D',
        'units': 'N'
    }, {
        'name': 'mass',
        'units': 'kg'
    }, {
        'name': 'psi',
        'units': 'rad'
    }, {
        'name': 'theta',
        'units': 'rad'
    }, {
        'name': 'phi',
        'units': 'rad'
    }]

    phase0 = CollocationPhase(name='phase0',
                              rhs_class=MagneplaneRHS,
                              num_seg=num_seg,
                              seg_ncn=seg_ncn,
                              rel_lengths="equal",
                              dynamic_controls=dynamic_controls,
                              static_controls=None)

    traj.add_phase(phase0)

    phase0.set_state_options('x',
                             lower=0,
                             upper=10,
                             ic_val=0,
                             ic_fix=True,
                             fc_val=10,
                             fc_fix=True,
                             defect_scaler=0.1)
    phase0.set_state_options('y',
                             lower=0,
                             upper=0,
                             ic_val=0,
                             ic_fix=True,
                             fc_val=0,
                             fc_fix=True,
                             defect_scaler=0.1)
    phase0.set_state_options('z',
                             lower=-10,
                             upper=0,
                             ic_val=-10,
                             ic_fix=True,
                             fc_val=-5,
                             fc_fix=True,
                             defect_scaler=0.1)
    phase0.set_state_options('v',
                             lower=0,
                             upper=np.inf,
                             ic_val=0.0,
                             ic_fix=True,
                             fc_val=10.0,
                             fc_fix=False,
                             defect_scaler=0.1)

    phase0.set_dynamic_control_options(name='psi',
                                       val=phase0.node_space(0.0, 0.0),
                                       opt=False)
    phase0.set_dynamic_control_options(name='theta',
                                       val=phase0.node_space(-.46, -.46),
                                       opt=True,
                                       lower=-1.57,
                                       upper=1.57,
                                       scaler=1.0)
    phase0.set_dynamic_control_options(name='phi',
                                       val=phase0.node_space(0.0, 0.0),
                                       opt=False)

    phase0.set_dynamic_control_options(name='g',
                                       val=phase0.node_space(9.80665, 9.80665),
                                       opt=False)
    phase0.set_dynamic_control_options(name='T',
                                       val=phase0.node_space(0.0, 0.0),
                                       opt=False)
    phase0.set_dynamic_control_options(name='D',
                                       val=phase0.node_space(0.0, 0.0),
                                       opt=False)
    phase0.set_dynamic_control_options(name='mass',
                                       val=phase0.node_space(1000.0, 1000.0),
                                       opt=False)

    phase0.set_time_options(t0_val=0,
                            t0_lower=0,
                            t0_upper=0,
                            tp_val=2.0,
                            tp_lower=0.5,
                            tp_upper=10.0)

    traj.add_objective(name="t", phase="phase0", place="end", scaler=1.0)

    return prob
Exemplo n.º 8
0
def magneplane_brachistochrone(solver="SLSQP", num_seg=3, seg_ncn=3):

    prob = Problem()
    traj = prob.add_traj(Trajectory("traj0"))

    if solver == "SNOPT":
        if pyOptSparseDriver is None:
            raise ValueError("Requested SNOPT but pyoptsparse is not available")
        driver = pyOptSparseDriver()
        driver.options["optimizer"] = solver
        driver.opt_settings["Major iterations limit"] = 1000
        driver.opt_settings["iSumm"] = 6
        driver.opt_settings["Major step limit"] = 0.5
        driver.opt_settings["Major feasibility tolerance"] = 1.0e-6
        driver.opt_settings["Major optimality tolerance"] = 1.0e-6
        driver.opt_settings["Minor feasibility tolerance"] = 1.0e-4
        driver.opt_settings["Verify level"] = 3
    else:
        driver = ScipyOptimizer()
        driver.options["tol"] = 1.0e-6
        driver.options["disp"] = True
        driver.options["maxiter"] = 500

    prob.driver = driver

    dynamic_controls = [
        {"name": "g", "units": "m/s**2"},
        {"name": "T", "units": "N"},
        {"name": "D", "units": "N"},
        {"name": "mass", "units": "kg"},
        {"name": "psi", "units": "rad"},
        {"name": "theta", "units": "rad"},
        {"name": "phi", "units": "rad"},
    ]

    phase0 = CollocationPhase(
        name="phase0",
        rhs_class=MagneplaneRHS,
        num_seg=num_seg,
        seg_ncn=seg_ncn,
        rel_lengths="equal",
        dynamic_controls=dynamic_controls,
        static_controls=None,
    )

    traj.add_phase(phase0)

    phase0.set_state_options("x", lower=0, upper=10, ic_val=0, ic_fix=True, fc_val=10, fc_fix=True, defect_scaler=0.1)
    phase0.set_state_options("y", lower=0, upper=0, ic_val=0, ic_fix=True, fc_val=0, fc_fix=True, defect_scaler=0.1)
    phase0.set_state_options(
        "z", lower=-10, upper=0, ic_val=-10, ic_fix=True, fc_val=-5, fc_fix=True, defect_scaler=0.1
    )
    phase0.set_state_options(
        "v", lower=0, upper=np.inf, ic_val=0.0, ic_fix=True, fc_val=10.0, fc_fix=False, defect_scaler=0.1
    )

    phase0.set_dynamic_control_options(name="psi", val=phase0.node_space(0.0, 0.0), opt=False)
    phase0.set_dynamic_control_options(
        name="theta", val=phase0.node_space(-0.46, -0.46), opt=True, lower=-1.57, upper=1.57, scaler=1.0
    )
    phase0.set_dynamic_control_options(name="phi", val=phase0.node_space(0.0, 0.0), opt=False)

    phase0.set_dynamic_control_options(name="g", val=phase0.node_space(9.80665, 9.80665), opt=False)
    phase0.set_dynamic_control_options(name="T", val=phase0.node_space(0.0, 0.0), opt=False)
    phase0.set_dynamic_control_options(name="D", val=phase0.node_space(0.0, 0.0), opt=False)
    phase0.set_dynamic_control_options(name="mass", val=phase0.node_space(1000.0, 1000.0), opt=False)

    phase0.set_time_options(t0_val=0, t0_lower=0, t0_upper=0, tp_val=2.0, tp_lower=0.5, tp_upper=10.0)

    traj.add_objective(name="t", phase="phase0", place="end", scaler=1.0)

    return prob
Exemplo n.º 9
0
        unknowns['radiating_area'] = unknowns['convection_area']
        unknowns['Qradiated_per_area'] = params['sb_const'] * params['emissivity'] * (params['temp_boundary'] ** 4 - params['temp_ambient'] ** 4) # P / A = SB * emmisitivity * (T ** 4 - To ** 4)
        unknowns['Qradiated_tot'] = unknowns['radiating_area'] * unknowns['Qradiated_per_area']
        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