Пример #1
0
    def test_record_solver_nonlinear_nonlinear_run_once(self, m):
        self.setup_endpoints(m)
        self.setup_sellar_model()

        self.prob.model.nonlinear_solver = NonlinearRunOnce()
        self.prob.model.nonlinear_solver.add_recorder(self.recorder)

        self.prob.setup(check=False)

        t0, t1 = run_driver(self.prob)

        self.prob.cleanup()
        upload(self.filename, self._accepted_token)

        # No norms so no expected norms
        expected_abs_error = 0.0
        expected_rel_error = 0.0
        expected_solver_residuals = None
        expected_solver_output = [
            {'name': 'px.x', 'values': [1.]},
            {'name': 'pz.z', 'values': [5., 2.]},
            {'name': 'd1.y1', 'values': [27.8]},
            {'name': 'd2.y2', 'values': [12.27257053]},
            {'name': 'obj_cmp.obj', 'values': [30.80000468]},
            {'name': 'con_cmp1.con1', 'values': [-24.64]},
            {'name': 'con_cmp2.con2', 'values': [-11.72742947]}
        ]

        solver_iteration = json.loads(self.solver_iterations)

        self.assertEqual(expected_abs_error, solver_iteration['abs_err'])
        self.assertEqual(expected_rel_error, solver_iteration['rel_err'])
        self.assertEqual(solver_iteration['solver_residuals'], [])
        for o in expected_solver_output:
            self.assert_array_close(o, solver_iteration['solver_output'])
    def test_record_solver_nonlinear_nonlinear_run_once(self, m):
        self.setup_endpoints(m)
        recorder = WebRecorder(self._accepted_token, suppress_output=True)
        self.setup_sellar_model()

        self.prob.model.nonlinear_solver = NonlinearRunOnce()
        self.prob.model.nonlinear_solver.add_recorder(recorder)

        self.prob.setup(check=False)

        t0, t1 = run_driver(self.prob)

        self.prob.cleanup()

        # No norms so no expected norms
        expected_abs_error = 0.0
        expected_rel_error = 0.0
        expected_solver_residuals = None
        expected_solver_output = None

        solver_iteration = json.loads(self.solver_iterations)

        self.assertEqual(expected_abs_error, solver_iteration['abs_err'])
        self.assertEqual(expected_rel_error, solver_iteration['rel_err'])
        self.assertEqual(solver_iteration['solver_residuals'], [])
        self.assertEqual(len(solver_iteration['solver_output']), 7)
Пример #3
0
    def test_set_order(self):

        order_list = []
        prob = Problem()
        model = prob.model
        model.nonlinear_solver = NonlinearRunOnce()
        model.add_subsystem('indeps', IndepVarComp('x', 1.))
        model.add_subsystem('C1', ReportOrderComp(order_list))
        model.add_subsystem('C2', ReportOrderComp(order_list))
        model.add_subsystem('C3', ReportOrderComp(order_list))
        model.connect('indeps.x', 'C1.x')
        model.connect('C1.y', 'C2.x')
        model.connect('C2.y', 'C3.x')
        prob.set_solver_print(level=0)

        self.assertEqual(['indeps', 'C1', 'C2', 'C3'],
                         [s.name for s in model._static_subsystems_allprocs])

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

        self.assertEqual(['C1', 'C2', 'C3'], order_list)

        order_list[:] = []

        # Big boy rules
        model.set_order(['indeps', 'C2', 'C1', 'C3'])

        prob.setup(check=False)
        prob.run_model()
        self.assertEqual(['C2', 'C1', 'C3'], order_list)

        # Extra
        with self.assertRaises(ValueError) as cm:
            model.set_order(['indeps', 'C2', 'junk', 'C1', 'C3'])

        self.assertEqual(str(cm.exception),
                         ": subsystem(s) ['junk'] found in subsystem order but don't exist.")

        # Missing
        with self.assertRaises(ValueError) as cm:
            model.set_order(['indeps', 'C2', 'C3'])

        self.assertEqual(str(cm.exception),
                         ": ['C1'] expected in subsystem order and not found.")

        # Extra and Missing
        with self.assertRaises(ValueError) as cm:
            model.set_order(['indeps', 'C2', 'junk', 'C1', 'junk2'])

        self.assertEqual(str(cm.exception),
                         ": ['C3'] expected in subsystem order and not found.\n"
                         ": subsystem(s) ['junk', 'junk2'] found in subsystem order but don't exist.")

        # Dupes
        with self.assertRaises(ValueError) as cm:
            model.set_order(['indeps', 'C2', 'C1', 'C3', 'C1'])

        self.assertEqual(str(cm.exception),
                         ": Duplicate name(s) found in subsystem order list: ['C1']")
Пример #4
0
    def test_set_order_feature(self):
        from openmdao.api import Problem, IndepVarComp, NonlinearRunOnce
        from openmdao.core.tests.test_group import ReportOrderComp

        # this list will record the execution order of our C1, C2, and C3 components
        order_list = []
        prob = Problem()
        model = prob.model
        model.nonlinear_solver = NonlinearRunOnce()
        model.add_subsystem('indeps', IndepVarComp('x', 1.))
        model.add_subsystem('C1', ReportOrderComp(order_list))
        model.add_subsystem('C2', ReportOrderComp(order_list))
        model.add_subsystem('C3', ReportOrderComp(order_list))

        prob.set_solver_print(level=0)

        self.assertEqual(['indeps', 'C1', 'C2', 'C3'],
                         [s.name for s in model._static_subsystems_allprocs])

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

        self.assertEqual(['C1', 'C2', 'C3'], order_list)

        # reset the shared order list
        order_list[:] = []

        # now swap C2 and C1 in the order
        model.set_order(['indeps', 'C2', 'C1', 'C3'])

        # after changing the order, we must call setup again
        prob.setup(check=False)
        prob.run_model()
        self.assertEqual(['C2', 'C1', 'C3'], order_list)
Пример #5
0
    def test_simple_implicit_self_solve(self):

        prob = Problem(Group())
        prob.model.add_subsystem('p1', IndepVarComp('x', 0.5))
        comp = prob.model.add_subsystem('comp', SimpleImplicitComp())
        comp.self_solve = True

        prob.model.linear_solver = ScipyKrylov()
        prob.model.nonlinear_solver = NonlinearRunOnce()

        prob.set_solver_print(level=0)

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

        prob.setup(check=False, mode='fwd')
        prob.run_model()

        assert_rel_error(self, prob['comp.z'], 2.666, 1e-3)
        self.assertLess(prob.model.nonlinear_solver._iter_count, 5)

        J = prob.compute_totals(of=['comp.y', 'comp.z'], wrt=['p1.x'])
        assert_rel_error(self, J[('comp.y', 'p1.x')][0][0], -2.5555511, 1e-5)
        assert_rel_error(self, J[('comp.z', 'p1.x')][0][0], -1.77777777, 1e-5)

        prob.setup(check=False, mode='rev')
        prob.run_model()

        assert_rel_error(self, prob['comp.z'], 2.666, 1e-3)
        self.assertLess(prob.model.nonlinear_solver._iter_count, 5)

        J = prob.compute_totals(of=['comp.y', 'comp.z'], wrt=['p1.x'])
        assert_rel_error(self, J[('comp.y', 'p1.x')][0][0], -2.5555511, 1e-5)
        assert_rel_error(self, J[('comp.z', 'p1.x')][0][0], -1.77777777, 1e-5)

        # Check partials
        data = prob.check_partials()

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

        assert_rel_error(self, data['comp'][('y', 'x')]['J_fwd'][0][0], 1.0,
                         1e-6)
        assert_rel_error(self, data['comp'][('y', 'z')]['J_fwd'][0][0], 2.0,
                         1e-6)
        assert_rel_error(self, data['comp'][('z', 'x')]['J_fwd'][0][0],
                         2.66666667, 1e-6)
        assert_rel_error(self, data['comp'][('z', 'z')]['J_fwd'][0][0], 1.5,
                         1e-6)
Пример #6
0
    def test_zero_src_indices(self):
        prob = Problem()
        model = prob.model
        model.nonlinear_solver = NonlinearRunOnce()
        model.linear_solver = LinearRunOnce()

        model.add_subsystem('comp1', Comp())
        model.add_subsystem('comp2', Comp())
        model.connect('comp1.y', 'comp2.x')
        model.connect('comp2.y', 'comp1.x')

        prob.setup()
        prob.run_model()

        if model.comm.rank == 1:
            np.testing.assert_almost_equal(model.comp1._outputs['y'],
                                           np.array([]))
            np.testing.assert_almost_equal(model.comp2._outputs['y'],
                                           np.array([]))
        else:
            np.testing.assert_almost_equal(model.comp1._outputs['y'],
                                           np.ones(3) * 2.)
            np.testing.assert_almost_equal(model.comp2._outputs['y'],
                                           np.ones(3) * 3.)
Пример #7
0
    def test_circuit_voltage_source(self):
        from openmdao.api import ArmijoGoldsteinLS, Problem, IndepVarComp, BalanceComp, ExecComp
        from openmdao.api import NewtonSolver, DirectSolver, NonlinearRunOnce, LinearRunOnce

        from openmdao.test_suite.scripts.circuit_analysis import Circuit

        p = Problem()
        model = p.model

        model.add_subsystem('ground', IndepVarComp('V', 0., units='V'))

        # replacing the fixed current source with a BalanceComp to represent a fixed Voltage source
        # model.add_subsystem('source', IndepVarComp('I', 0.1, units='A'))
        model.add_subsystem('batt', IndepVarComp('V', 1.5, units='V'))
        bal = model.add_subsystem('batt_balance', BalanceComp())
        bal.add_balance('I', units='A', eq_units='V')

        model.add_subsystem('circuit', Circuit())
        model.add_subsystem(
            'batt_deltaV',
            ExecComp('dV = V1 - V2',
                     V1={'units': 'V'},
                     V2={'units': 'V'},
                     dV={'units': 'V'}))

        # current into the circuit is now the output state from the batt_balance comp
        model.connect('batt_balance.I', 'circuit.I_in')
        model.connect('ground.V', ['circuit.Vg', 'batt_deltaV.V2'])
        model.connect('circuit.n1.V', 'batt_deltaV.V1')

        # set the lhs and rhs for the battery residual
        model.connect('batt.V', 'batt_balance.rhs:I')
        model.connect('batt_deltaV.dV', 'batt_balance.lhs:I')

        p.setup()

        ###################
        # Solver Setup
        ###################

        # change the circuit solver to RunOnce because we're
        # going to converge at the top level of the model with newton instead
        p.model.circuit.nonlinear_solver = NonlinearRunOnce()
        p.model.circuit.linear_solver = LinearRunOnce()

        # Put Newton at the top so it can also converge the new BalanceComp residual
        newton = p.model.nonlinear_solver = NewtonSolver()
        p.model.linear_solver = DirectSolver()
        newton.options['iprint'] = 2
        newton.options['maxiter'] = 20
        newton.options['solve_subsystems'] = True
        newton.linesearch = ArmijoGoldsteinLS()
        newton.linesearch.options['maxiter'] = 10
        newton.linesearch.options['iprint'] = 2

        # set initial guesses from the current source problem
        p['circuit.n1.V'] = 9.8
        p['circuit.n2.V'] = .7

        p.run_model()

        assert_rel_error(self, p['circuit.n1.V'], 1.5, 1e-5)
        assert_rel_error(self, p['circuit.n2.V'], 0.676232, 1e-5)
        assert_rel_error(self, p['circuit.R1.I'], 0.015, 1e-5)
        assert_rel_error(self, p['circuit.R2.I'], 8.23767999e-05, 1e-5)
        assert_rel_error(self, p['circuit.D1.I'], 8.23767999e-05, 1e-5)
        prob.model.add_constraint('frequencyNP_margin', upper=0.)
        prob.model.add_constraint('frequency1P_margin', upper=0.)
        prob.model.add_constraint('ground_clearance', lower=20.0)
        # ----------------------

        # --- Recorder ---
        prob.driver.add_recorder(SqliteRecorder('log_opt.sql'))
        prob.driver.recording_options['includes'] = [
            'AEP', 'rc.total_blade_cost', 'lcoe', 'tip_deflection_ratio'
        ]
        prob.driver.recording_options['record_objectives'] = True
        prob.driver.recording_options['record_constraints'] = True
        prob.driver.recording_options['record_desvars'] = True
        # ----------------------

    prob.setup(check=True)

    prob = Init_LandBasedAssembly(prob, blade, Nsection_Tow)
    prob.model.nonlinear_solver = NonlinearRunOnce()
    prob.model.linear_solver = DirectSolver()

    if not MPI:
        prob.model.approx_totals()

    # prob.run_model()
    # prob.model.list_inputs(units=True)
    # prob.model.list_outputs(units=True)

    prob.run_driver()
    # prob.check_partials(compact_print=True, method='fd', step=1e-6, form='central')
    def test_continuity_comp_connected_scalar_no_iteration_fwd(self):
        num_seg = 4
        state_options = {
            'y': {
                'shape': (1, ),
                'units': 'm',
                'targets': ['y'],
                'defect_scaler': None,
                'defect_ref': None,
                'lower': None,
                'upper': None,
                'connected_initial': True
            }
        }

        p = Problem(model=Group())

        ivc = p.model.add_subsystem('ivc',
                                    IndepVarComp(),
                                    promotes_outputs=['*'])
        ivc.add_output('initial_states:y', units='m', shape=(1, 1))

        p.model.add_subsystem('continuity_comp',
                              RungeKuttaStateContinuityComp(
                                  num_segments=num_seg,
                                  state_options=state_options),
                              promotes_inputs=['*'],
                              promotes_outputs=['*'])

        p.model.nonlinear_solver = NonlinearRunOnce()
        p.model.linear_solver = DirectSolver()

        p.setup(check=True, force_alloc_complex=True)

        p['initial_states:y'] = 0.5

        p['states:y'] = np.array([[0.50000000], [1.425130208333333],
                                  [2.639602661132812], [4.006818970044454],
                                  [5.301605229265987]])

        p['state_integrals:y'] = np.array([[1.0], [1.0], [1.0], [1.0]])

        p.run_model()
        p.model.run_apply_nonlinear()

        # Test that the residuals of the states are the expected values
        outputs = p.model.list_outputs(print_arrays=True,
                                       residuals=True,
                                       out_stream=None)

        y_f = p['states:y'][1:, ...]
        y_i = p['states:y'][:-1, ...]
        dy_given = y_f - y_i
        dy_computed = p['state_integrals:y']

        expected_resids = np.zeros((num_seg + 1, 1))
        expected_resids[1:, ...] = dy_given - dy_computed

        op_dict = dict([op for op in outputs])
        assert_rel_error(self, op_dict['continuity_comp.states:y']['resids'],
                         expected_resids)

        # Test the partials
        cpd = p.check_partials(method='cs')

        J_fwd = cpd['continuity_comp']['states:y',
                                       'state_integrals:y']['J_fwd']
        J_rev = cpd['continuity_comp']['states:y',
                                       'state_integrals:y']['J_rev']
        J_fd = cpd['continuity_comp']['states:y', 'state_integrals:y']['J_fd']
        assert_rel_error(self, J_fwd, J_rev)
        assert_rel_error(self, J_fwd, J_fd)

        J_fwd = cpd['continuity_comp']['states:y', 'states:y']['J_fwd']
        J_rev = cpd['continuity_comp']['states:y', 'states:y']['J_rev']
        J_fd = cpd['continuity_comp']['states:y', 'states:y']['J_fd']

        J_fd[0, 0] = -1.0

        assert_rel_error(self, J_fwd, J_rev)
        assert_rel_error(self, J_fwd, J_fd)
Пример #10
0
    model.connect('ground.V', ['circuit.Vg','batt_deltaV.V2'])
    model.connect('circuit.n1.V', 'batt_deltaV.V1')

    # set the lhs and rhs for the battery residual
    model.connect('batt.V', 'batt_balance.rhs:I')
    model.connect('batt_deltaV.dV', 'batt_balance.lhs:I')

    p.setup()

    ###################
    # Solver Setup
    ###################

    # change the circuit solver to RunOnce because we're
    # going to converge at the top level of the model with newton instead
    p.model.circuit.nonlinear_solver = NonlinearRunOnce()
    p.model.circuit.linear_solver = LinearRunOnce()

    # Put Newton at the top so it can also converge the new BalanceComp residual
    newton = p.model.nonlinear_solver = NewtonSolver()
    p.model.linear_solver = DirectSolver()
    newton.options['iprint'] = 2
    newton.options['maxiter'] = 20
    newton.options['solve_subsystems'] = True
    newton.linesearch = ArmijoGoldsteinLS()
    newton.linesearch.options['maxiter'] = 10
    newton.linesearch.options['iprint'] = 2

    # set initial guesses from the current source problem
    p['circuit.n1.V'] = 9.8
    p['circuit.n2.V'] = .7
    def test_continuity_comp_no_iteration(self):
        num_seg = 4
        state_options = {'y': {'shape': (1,), 'units': 'm', 'targets': ['y'], 'fix_initial': True,
                               'fix_final': False, 'propagation': 'forward', 'defect_scaler': None,
                               'defect_ref': None, 'lower': None, 'upper': None,
                               'connected_initial': False}}

        p = Problem(model=Group())

        ivc = p.model.add_subsystem('ivc', IndepVarComp(), promotes_outputs=['*'])

        ivc.add_output('time', val=np.array([0.00, 0.25, 0.25, 0.50,
                                             0.50, 0.75, 0.75, 1.00,
                                             1.00, 1.25, 1.25, 1.50,
                                             1.50, 1.75, 1.75, 2.00]), units='s')

        ivc.add_output('h', val=np.array([0.5, 0.5, 0.5, 0.5]), units='s')

        p.model.add_subsystem('cnty_iter_group',
                              RungeKuttaStateContinuityIterGroup(
                                  num_segments=num_seg,
                                  method='RK4',
                                  state_options=state_options,
                                  time_units='s',
                                  ode_class=TestODE,
                                  ode_init_kwargs={},
                                  k_solver_class=NonlinearRunOnce),
                              promotes_outputs=['states:*'])

        p.model.connect('h', 'cnty_iter_group.h')
        p.model.connect('time', 'cnty_iter_group.ode.t')

        src_idxs = np.arange(16, dtype=int).reshape((num_seg, 4, 1))
        p.model.connect('cnty_iter_group.ode.ydot', 'cnty_iter_group.k_comp.f:y',
                        src_indices=src_idxs, flat_src_indices=True)

        p.model.nonlinear_solver = NonlinearRunOnce()
        p.model.linear_solver = DirectSolver()

        p.setup(check=True, force_alloc_complex=True)

        p['states:y'] = np.array([[0.50000000],
                                  [1.425130208333333],
                                  [2.639602661132812],
                                  [4.006818970044454],
                                  [5.301605229265987]])

        p['cnty_iter_group.k_comp.k:y'] = np.array([[[0.75000000],
                                                     [0.90625000],
                                                     [0.94531250],
                                                     [1.09765625]],

                                                    [[1.087565104166667],
                                                     [1.203206380208333],
                                                     [1.232116699218750],
                                                     [1.328623453776042]],

                                                    [[1.319801330566406],
                                                     [1.368501663208008],
                                                     [1.380676746368408],
                                                     [1.385139703750610]],

                                                    [[1.378409485022227],
                                                     [1.316761856277783],
                                                     [1.301349949091673],
                                                     [1.154084459568063]]])

        p.run_model()
        p.model.run_apply_nonlinear()

        # Test that the residuals of the states are the expected values
        outputs = p.model.list_outputs(print_arrays=True, residuals=True, out_stream=None)

        expected_resids = np.zeros((num_seg + 1, 1))

        op_dict = dict([op for op in outputs])
        assert_rel_error(self, op_dict['cnty_iter_group.continuity_comp.states:y']['resids'],
                         expected_resids)

        # Test the partials
        cpd = p.check_partials(method='cs', out_stream=None)

        J_fwd = cpd['cnty_iter_group.continuity_comp']['states:y', 'state_integrals:y']['J_fwd']
        J_rev = cpd['cnty_iter_group.continuity_comp']['states:y', 'state_integrals:y']['J_rev']
        J_fd = cpd['cnty_iter_group.continuity_comp']['states:y', 'state_integrals:y']['J_fd']
        assert_rel_error(self, J_fwd, J_rev)
        assert_rel_error(self, J_fwd, J_fd)

        J_fwd = cpd['cnty_iter_group.continuity_comp']['states:y', 'states:y']['J_fwd']
        J_rev = cpd['cnty_iter_group.continuity_comp']['states:y', 'states:y']['J_rev']
        J_fd = cpd['cnty_iter_group.continuity_comp']['states:y', 'states:y']['J_fd']

        J_fd[0, 0] = -1.0

        assert_rel_error(self, J_fwd, J_rev)
        assert_rel_error(self, J_fwd, J_fd)