def test_simple_paraboloid_equality(self): prob = Problem() root = prob.root = Group() root.add("p1", ParamComp("x", 50.0), promotes=["*"]) root.add("p2", ParamComp("y", 50.0), promotes=["*"]) root.add("comp", Paraboloid(), promotes=["*"]) root.add("con", ExecComp("c = 15.0 - x + y"), promotes=["*"]) prob.driver = ScipyOptimizer() prob.driver.options["optimizer"] = "SLSQP" prob.driver.options["tol"] = 1.0e-8 prob.driver.add_param("x", low=-50.0, high=50.0) prob.driver.add_param("y", low=-50.0, high=50.0) prob.driver.add_objective("f_xy") prob.driver.add_constraint("c", ctype="ineq") prob.setup(check=False) prob.run() # Minimum should be at (7.166667, -7.833334) assert_rel_error(self, prob["x"], 7.16667, 1e-6) assert_rel_error(self, prob["y"], -7.833334, 1e-6)
def test_simple_paraboloid_constrained_COBYLA_upper(self): prob = Problem() root = prob.root = Group() root.add('p1', IndepVarComp('x', 50.0), promotes=['*']) root.add('p2', IndepVarComp('y', 50.0), promotes=['*']) root.add('comp', Paraboloid(), promotes=['*']) root.add('con', ExecComp('c = y - x'), promotes=['*']) prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'COBYLA' prob.driver.options['tol'] = 1.0e-8 prob.driver.add_desvar('x', low=-50.0, high=50.0) prob.driver.add_desvar('y', low=-50.0, high=50.0) prob.driver.add_objective('f_xy') prob.driver.add_constraint('c', upper=-15.0) prob.driver.options['disp'] = False prob.setup(check=False) prob.run() # Minimum should be at (7.166667, -7.833334) assert_rel_error(self, prob['x'], 7.16667, 1e-6) assert_rel_error(self, prob['y'], -7.833334, 1e-6)
def test_index_array_param(self): prob = Problem() prob.root = SellarStateConnection() prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.add_desvar('z', low=np.array([-10.0]), high=np.array([10.0]), indices=[0]) prob.driver.add_desvar('x', low=0.0, high=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.driver.options['disp'] = False prob.setup(check=False) prob['z'][1] = 5.0 prob.run() assert_rel_error(self, prob['z'][0], 0.1005, 1e-3) assert_rel_error(self, prob['z'][1], 5.0, 1e-3) assert_rel_error(self, prob['x'], 0.0, 1e-3)
def test_index_error_messages_con(self): prob = Problem() prob.root = Group() prob.root.fd_options['force_fd'] = True prob.root.ln_solver.options['mode'] = 'auto' prob.root.add('myparams', IndepVarComp('x', np.zeros(4))) prob.root.add('rosen', Rosenbrock(4)) prob.root.connect('myparams.x', 'rosen.x') prob.driver = MySimpleDriver() prob.driver.add_desvar('myparams.x') prob.driver.add_constraint('rosen.xxx', upper=0.0, indices=[4]) prob.setup(check=False) # Make sure we can't do this with self.assertRaises(IndexError) as cm: prob.run() msg = "Index for constraint 'rosen.xxx' is out of bounds. " msg += "Requested index: [4], " msg += "shape: (4,)." raised_error = str(cm.exception) raised_error = raised_error.replace('(4L,', '(4,') self.assertEqual(msg, raised_error)
def test_index_error_messages_con(self): prob = Problem() prob.root = Group() prob.root.fd_options['force_fd'] = True prob.root.ln_solver.options['mode'] = 'auto' prob.root.add('myparams', ParamComp('x', np.zeros(4))) prob.root.add('rosen', Rosenbrock(4)) prob.root.connect('myparams.x', 'rosen.x') prob.driver = MySimpleDriver() prob.driver.add_param('myparams.x') prob.driver.add_constraint('rosen.xxx', indices=[4]) prob.setup(check=False) # Make sure we can't do this with self.assertRaises(IndexError) as cm: prob.run() msg = "Index for constraint 'rosen.xxx' is out of bounds. " msg += "Requested index: [4], " msg += "Parameter shape: (4,)." raised_error = str(cm.exception) raised_error = raised_error.replace('(4L,', '(4,') self.assertEqual(msg, raised_error)
def test_eq_ineq_error_messages(self): prob = Problem() root = prob.root = SellarDerivatives() prob.driver = MySimpleDriver() # Don't try this at home, kids prob.driver.supports['equality_constraints'] = False with self.assertRaises(RuntimeError) as cm: prob.driver.add_constraint('con1', ctype='eq') self.assertEqual( str(cm.exception), "Driver does not support equality constraint 'con1'.") # Don't try this at home, kids prob.driver.supports['inequality_constraints'] = False with self.assertRaises(RuntimeError) as cm: prob.driver.add_constraint('con1', ctype='ineq') self.assertEqual( str(cm.exception), "Driver does not support inequality constraint 'con1'.")
def run(typ="adjoint", m=300): t = time.time() model = Problem(impl=impl) model.root = MPPT_MDP(m) # add optimizer model.driver = pyOptSparseDriver() model.driver.options['optimizer'] = "SNOPT" model.driver.options['print_results'] = False model.driver.opt_settings = { 'Major optimality tolerance': 1e-3, 'Major feasibility tolerance': 1.0e-5, 'Iterations limit': 500000000, "Verify level" : -1 } model.driver.add_objective("perf.result") model.driver.add_desvar("pt0.param.CP_Isetpt", lower=0., upper=0.4) #model.driver.add_desvar("pt1.param.CP_Isetpt", lower=0., upper=0.4) if typ == "fd": model.root.fd_options['force_fd'] = True elif typ == "fwd": model.root.ln_solver.options['mode'] = "fwd" else: model.root.ln_solver.options['mode'] = "rev" model.setup(check=False) model.run() #os.rename("SNOPT_summary.out", "SNOPT_summary_%s_%d.out" % (typ, m)) return time.time() - t
def test_simple_paraboloid_equality(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', 50.0), promotes=['*']) root.add('p2', ParamComp('y', 50.0), promotes=['*']) root.add('comp', Paraboloid(), promotes=['*']) root.add('con', ExecComp('c = 15.0 - x + y'), promotes=['*']) prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_param('y', low=-50.0, high=50.0) prob.driver.add_objective('f_xy') prob.driver.add_constraint('c', ctype='ineq') prob.driver.options['disp'] = False prob.setup(check=False) prob.run() # Minimum should be at (7.166667, -7.833334) assert_rel_error(self, prob['x'], 7.16667, 1e-6) assert_rel_error(self, prob['y'], -7.833334, 1e-6)
def test_driver_param_indices_snopt(self): """ Test driver param indices with pyOptSparse and force_fd=False """ prob = Problem() prob.root = SellarStateConnection() prob.root.fd_options['force_fd'] = False prob.driver = pyOptSparseDriver() prob.driver.add_desvar('z', low=np.array([-10.0]), high=np.array([10.0]),indices=[0]) prob.driver.add_desvar('x', low=0.0, high=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.setup(check=False) prob['z'][1] = 0.0 prob.run() assert_rel_error(self, prob['z'][0], 1.9776, 1e-3) assert_rel_error(self, prob['z'][1], 0.0, 1e-3) assert_rel_error(self, prob['x'], 0.0, 1e-3)
def test_Sellar_state_SLSQP(self): """ Baseline Sellar test case without specifying indices. """ prob = Problem() prob.root = SellarStateConnection() prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.add_desvar('z', low=np.array([-10.0, 0.0]), high=np.array([10.0, 10.0])) prob.driver.add_desvar('x', low=0.0, high=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.driver.options['disp'] = False prob.setup(check=False) prob.run() assert_rel_error(self, prob['z'][0], 1.9776, 1e-3) assert_rel_error(self, prob['z'][1], 0.0, 1e-3) assert_rel_error(self, prob['x'], 0.0, 1e-3)
def test_simple_array_comp(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', np.zeros([2])), promotes=['*']) root.add('comp', SimpleArrayComp(), promotes=['*']) root.add('con', ExecComp('c = y - 20.0', c=np.array([0.0, 0.0]), y=np.array([0.0, 0.0])), promotes=['*']) root.add('obj', ExecComp('o = y[0]', y=np.array([0.0, 0.0])), promotes=['*']) prob.driver = pyOptSparseDriver() prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_objective('o') prob.driver.add_constraint('c', ctype='eq') prob.setup(check=False) prob.run() obj = prob['o'] assert_rel_error(self, obj, 20.0, 1e-6)
def test_driver_param_indices_slsqp_force_fd(self): """ Test driver param indices with ScipyOptimizer SLSQP and force_fd=True """ prob = Problem() prob.root = SellarStateConnection() prob.root.fd_options['force_fd'] = True prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.add_desvar('z', low=np.array([-10.0]), high=np.array([10.0]),indices=[0]) prob.driver.add_desvar('x', low=0.0, high=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) #prob.driver.options['disp'] = False prob.setup(check=False) prob['z'][1] = 0.0 prob.run() assert_rel_error(self, prob['z'][0], 1.9776, 1e-3) assert_rel_error(self, prob['z'][1], 0.0, 1e-3) assert_rel_error(self, prob['x'], 0.0, 1e-3)
def test_simple_array_comp2D(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', np.zeros((2, 2))), promotes=['*']) root.add('comp', ArrayComp2D(), promotes=['*']) root.add('con', ExecComp('c = y - 20.0', c=np.zeros((2, 2)), y=np.zeros((2, 2))), promotes=['*']) root.add('obj', ExecComp('o = y[0, 0]', y=np.zeros((2, 2))), promotes=['*']) prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_objective('o') prob.driver.add_constraint('c', ctype='eq') prob.driver.options['disp'] = False prob.setup(check=False) prob.run() obj = prob['o'] assert_rel_error(self, obj, 20.0, 1e-6)
def test_rosenbrock(self): prob = Problem() root = prob.root = Group() root.add("rosen", Rosenbrock(), promotes=["x", "obj"]) root.add("desvars", IndepVarComp("x", np.ones(2) * -1.0), promotes=["x"]) prob.driver = KonaOptimizer() prob.driver.options["algorithm"] = ReducedSpaceQuasiNewton # prob.driver.options['algorithm'] = Verifier optns = { "verify": { "primal_vec": True, "state_vec": True, "dual_vec": True, "gradients": True, "pde_jac": True, "cnstr_jac": True, "red_grad": True, "lin_solve": True, "out_file": sys.stdout, # 'kona_verify.dat', } } prob.driver.options["algorithm_options"] = optns prob.driver.add_desvar("x") prob.driver.add_objective("obj") prob.setup(check=False) prob.run() assert_rel_error(self, prob["x"], np.ones(2), 1e-5)
def test_Sellar_state_SLSQP(self): prob = Problem() prob.root = SellarStateConnection() prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.add_param('z', low=np.array([-10.0, 0.0]), high=np.array([10.0, 10.0])) prob.driver.add_param('x', low=0.0, high=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1') prob.driver.add_constraint('con2') prob.driver.options['disp'] = False prob.setup(check=False) prob.run() assert_rel_error(self, prob['z'][0], 1.9776, 1e-3) assert_rel_error(self, prob['z'][1], 0.0, 1e-3) assert_rel_error(self, prob['x'], 0.0, 1e-3)
def test_record_derivs_dicts(self): if OPT is None: raise unittest.SkipTest("pyoptsparse is not installed") if OPTIMIZER is None: raise unittest.SkipTest( "pyoptsparse is not providing SNOPT or SLSQP") prob = Problem() prob.root = SellarDerivativesGrouped() prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.opt_settings['ACC'] = 1e-9 prob.driver.options['print_results'] = False prob.driver.add_desvar('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) prob.driver.add_desvar('x', lower=0.0, upper=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.driver.add_recorder(self.recorder) self.recorder.options['record_metadata'] = False self.recorder.options['record_derivs'] = True prob.setup(check=False) prob.run() prob.cleanup() hdf = h5py.File(self.filename, 'r') deriv_group = hdf['rank0:SLSQP|1']['Derivs'] self.assertEqual(deriv_group.attrs['success'], 1) self.assertEqual(deriv_group.attrs['msg'], '') J1 = deriv_group['Derivatives'] Jbase = {} Jbase['con1'] = {} Jbase['con1']['x'] = -0.98061433 Jbase['con1']['z'] = np.array([-9.61002285, -0.78449158]) Jbase['con2'] = {} Jbase['con2']['x'] = 0.09692762 Jbase['con2']['z'] = np.array([1.94989079, 1.0775421]) Jbase['obj'] = {} Jbase['obj']['x'] = 2.98061392 Jbase['obj']['z'] = np.array([9.61001155, 1.78448534]) for key1, val1 in Jbase.items(): for key2, val2 in val1.items(): assert_rel_error(self, J1[key1][key2][:], val2, .00001) hdf.close()
def test_record_derivs_dicts(self): if OPT is None: raise unittest.SkipTest("pyoptsparse is not installed") if OPTIMIZER is None: raise unittest.SkipTest("pyoptsparse is not providing SNOPT or SLSQP") prob = Problem() prob.root = SellarDerivativesGrouped() prob.driver = pyOptSparseDriver() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.opt_settings['ACC'] = 1e-9 prob.driver.options['print_results'] = False prob.driver.add_desvar('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) prob.driver.add_desvar('x', lower=0.0, upper=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.driver.add_recorder(self.recorder) self.recorder.options['record_metadata'] = False self.recorder.options['record_derivs'] = True prob.setup(check=False) prob.run() prob.cleanup() hdf = h5py.File(self.filename, 'r') deriv_group = hdf['rank0:SLSQP|1']['Derivs'] self.assertEqual(deriv_group.attrs['success'],1) self.assertEqual(deriv_group.attrs['msg'],'') J1 = deriv_group['Derivatives'] Jbase = {} Jbase['con1'] = {} Jbase['con1']['x'] = -0.98061433 Jbase['con1']['z'] = np.array([-9.61002285, -0.78449158]) Jbase['con2'] = {} Jbase['con2']['x'] = 0.09692762 Jbase['con2']['z'] = np.array([1.94989079, 1.0775421 ]) Jbase['obj'] = {} Jbase['obj']['x'] = 2.98061392 Jbase['obj']['z'] = np.array([9.61001155, 1.78448534]) for key1, val1 in Jbase.items(): for key2, val2 in val1.items(): assert_rel_error(self, J1[key1][key2][:], val2, .00001) hdf.close()
def test_simple_driver_recording(self, m): self.setup_endpoints(m) recorder = WebRecorder(self._accepted_token, suppress_output=True) prob = Problem() model = prob.model = Group() model.add_subsystem('p1', IndepVarComp('x', 50.0), promotes=['*']) model.add_subsystem('p2', IndepVarComp('y', 50.0), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) model.add_subsystem('con', ExecComp('c = - x + y'), promotes=['*']) model.suppress_solver_output = True prob.driver = pyOptSparseDriver() prob.driver.add_recorder(recorder) prob.driver.recording_options['record_desvars'] = True prob.driver.recording_options['record_responses'] = True prob.driver.recording_options['record_objectives'] = True prob.driver.recording_options['record_constraints'] = True prob.driver.options['optimizer'] = OPTIMIZER if OPTIMIZER == 'SLSQP': prob.driver.opt_settings['ACC'] = 1e-9 model.add_design_var('x', lower=-50.0, upper=50.0) model.add_design_var('y', lower=-50.0, upper=50.0) model.add_objective('f_xy') model.add_constraint('c', upper=-15.0) prob.setup(check=False) t0, t1 = run_driver(prob) prob.cleanup() driver_iteration_data = json.loads(self.driver_iteration_data) expected_desvars = [ {'name': 'p1.x', 'values': [7.1666666]}, {'name': 'p2.y', 'values': [-7.8333333]} ] expected_objectives = [ {'name': 'comp.f_xy', 'values': [-27.083333]} ] expected_constraints = [ {'name': 'con.c', 'values': [-15.0]} ] for d in expected_desvars: self.assert_array_close(d, driver_iteration_data['desvars']) for o in expected_objectives: self.assert_array_close(o, driver_iteration_data['objectives']) for c in expected_constraints: self.assert_array_close(c, driver_iteration_data['constraints'])
def test_exponential_constrained_ieq(self): prob = Problem() root = prob.root = Group() root.add("sc", ExponentialConstrained(), promotes=["x", "f", "h"]) root.add("desvars", IndepVarComp("x", np.array([1.0, 1.0])), promotes=["x"]) prob.driver = KonaOptimizer() prob.driver.add_desvar("x") # TODO report bug if this variable is promoted prob.driver.add_objective("f") prob.driver.add_constraint("h", lower=0) prob.driver.options["algorithm"] = ConstrainedRSNK # prob.driver.options['algorithm'] = Verifier optns = { "info_file": "kona_info.dat", "max_iter": 30, "primal_tol": 1e-5, "constraint_tol": 1e-5, "trust": {"init_radius": 1.0, "max_radius": 10.0, "min_radius": 1e-4}, "aug_lag": {"mu_init": 1.0, "mu_pow": 0.5, "mu_max": 1e5}, "reduced": { "precond": None, "product_fac": 0.001, "lambda": 0.0, "scale": 0.0, "nu": 0.95, "dynamic_tol": False, }, "krylov": {"out_file": "kona_krylov.dat", "max_iter": 10, "rel_tol": 0.0095, "check_res": True}, "verify": { "primal_vec": True, "state_vec": True, "dual_vec": True, "gradients": True, "pde_jac": True, "cnstr_jac": True, "red_grad": True, "lin_solve": True, "out_file": sys.stdout, # 'kona_verify.dat', }, } prob.driver.options["algorithm_options"] = optns prob.setup(check=False) prob.run() # print(prob['x']) assert_rel_error(self, prob["x"], np.zeros(2), 1e-5)
def test_record_derivs_lists(self): prob = Problem() prob.root = SellarDerivativesGrouped() prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.options['disp'] = False prob.driver.add_desvar('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) prob.driver.add_desvar('x', lower=0.0, upper=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.driver.add_recorder(self.recorder) self.recorder.options['record_metadata'] = False self.recorder.options['record_derivs'] = True prob.setup(check=False) prob.run() prob.cleanup() hdf = h5py.File(self.filename, 'r') deriv_group = hdf['rank0:SLSQP|1']['Derivs'] self.assertEqual(deriv_group.attrs['success'], 1) self.assertEqual(deriv_group.attrs['msg'], '') J1 = deriv_group['Derivatives'] assert_rel_error(self, J1[0][0], 9.61001155, .00001) assert_rel_error(self, J1[0][1], 1.78448534, .00001) assert_rel_error(self, J1[0][2], 2.98061392, .00001) assert_rel_error(self, J1[1][0], -9.61002285, .00001) assert_rel_error(self, J1[1][1], -0.78449158, .00001) assert_rel_error(self, J1[1][2], -0.98061433, .00001) assert_rel_error(self, J1[2][0], 1.94989079, .00001) assert_rel_error(self, J1[2][1], 1.0775421, .00001) assert_rel_error(self, J1[2][2], 0.09692762, .00001) hdf.close()
def test_record_derivs_lists(self): prob = Problem() prob.root = SellarDerivativesGrouped() prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.options['disp'] = False prob.driver.add_desvar('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) prob.driver.add_desvar('x', lower=0.0, upper=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.driver.add_recorder(self.recorder) self.recorder.options['record_metadata'] = False self.recorder.options['record_derivs'] = True prob.setup(check=False) prob.run() prob.cleanup() hdf = h5py.File(self.filename, 'r') deriv_group = hdf['rank0:SLSQP|1']['Derivs'] self.assertEqual(deriv_group.attrs['success'],1) self.assertEqual(deriv_group.attrs['msg'],'') J1 = deriv_group['Derivatives'] assert_rel_error(self, J1[0][0], 9.61001155, .00001) assert_rel_error(self, J1[0][1], 1.78448534, .00001) assert_rel_error(self, J1[0][2], 2.98061392, .00001) assert_rel_error(self, J1[1][0], -9.61002285, .00001) assert_rel_error(self, J1[1][1], -0.78449158, .00001) assert_rel_error(self, J1[1][2], -0.98061433, .00001) assert_rel_error(self, J1[2][0], 1.94989079, .00001) assert_rel_error(self, J1[2][1], 1.0775421, .00001) assert_rel_error(self, J1[2][2], 0.09692762, .00001) hdf.close()
def test_mydriver(self): prob = Problem() root = prob.root = SellarDerivatives() prob.driver = MySimpleDriver() prob.driver.add_param('z', low=-100.0, high=100.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1') prob.driver.add_constraint('con2') prob.setup(check=False) prob.run() obj = prob['obj'] self.assertLess(obj, 28.0)
def test_mydriver(self): prob = Problem() root = prob.root = SellarDerivatives() prob.driver = MySimpleDriver() prob.driver.add_desvar('z', low=-100.0, high=100.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.setup(check=False) prob.run() obj = prob['obj'] self.assertLess(obj, 28.0)
def test_mydriver(self): prob = Problem() root = prob.root = SellarDerivatives() prob.driver = MySimpleDriver() prob.driver.add_param("z", low=-100.0, high=100.0) prob.driver.add_objective("obj") prob.driver.add_constraint("con1") prob.driver.add_constraint("con2") prob.setup(check=False) prob.run() obj = prob["obj"] self.assertLess(obj, 28.0)
def test_generate_numpydocstring(self): prob = Problem() prob.root = SellarStateConnection() prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.options['tol'] = 1.0e-8 prob.driver.add_desvar('z', low=np.array([-10.0]), high=np.array([10.0]), indices=[0]) prob.driver.add_desvar('x', low=0.0, high=10.0) prob.driver.add_objective('obj') prob.driver.add_constraint('con1', upper=0.0) prob.driver.add_constraint('con2', upper=0.0) prob.driver.options['disp'] = False test_string = prob.driver.generate_docstring() original_string = ' """\n\n Options\n -------\n options[\'disp\'] : bool(False)\n Set to False to prevent printing of Scipy convergence messages\n options[\'maxiter\'] : int(200)\n Maximum number of iterations.\n options[\'optimizer\'] : str(\'SLSQP\')\n Name of optimizer to use\n options[\'tol\'] : float(1e-08)\n Tolerance for termination. For detailed control, use solver-specific options.\n\n """\n' self.assertEqual(original_string, test_string)
def test_fan_out(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', 1.0)) root.add('p2', ParamComp('x', 1.0)) root.add('comp1', ExecComp('y = 3.0*x')) root.add('comp2', ExecComp('y = 5.0*x')) root.add('obj', ExecComp('o = i1 + i2')) root.add('con1', ExecComp('c = 15.0 - x')) root.add('con2', ExecComp('c = 15.0 - x')) # hook up non explicitly root.connect('p1.x', 'comp1.x') root.connect('p2.x', 'comp2.x') root.connect('comp1.y', 'obj.i1') root.connect('comp2.y', 'obj.i2') root.connect('comp1.y', 'con1.x') root.connect('comp2.y', 'con2.x') prob.driver = pyOptSparseDriver() prob.driver.add_param('p1.x', low=-50.0, high=50.0) prob.driver.add_param('p2.x', low=-50.0, high=50.0) prob.driver.add_objective('obj.o') prob.driver.add_constraint('con1.c', ctype='eq') prob.driver.add_constraint('con2.c', ctype='eq') prob.setup(check=False) prob.run() obj = prob['obj.o'] assert_rel_error(self, obj, 30.0, 1e-6) # Verify that pyOpt has the correct wrt names con1 = prob.driver.pyopt_solution.constraints['con1.c'] self.assertEqual(con1.wrt, ['p1.x']) con2 = prob.driver.pyopt_solution.constraints['con2.c'] self.assertEqual(con2.wrt, ['p2.x'])
def test_simple_array_comp2D_array_lo_hi(self): prob = Problem() root = prob.root = Group() root.add('p1', IndepVarComp('x', np.zeros((2, 2))), promotes=['*']) root.add('comp', ArrayComp2D(), promotes=['*']) root.add('con', ExecComp('c = y - 20.0', c=np.zeros((2, 2)), y=np.zeros((2, 2))), promotes=['*']) root.add('obj', ExecComp('o = y[0, 0]', y=np.zeros((2, 2))), promotes=['*']) prob.driver = pyOptSparseDriver() prob.driver.add_desvar('x', low=-50.0*np.ones((2, 2)), high=50.0*np.ones((2, 2))) prob.driver.add_objective('o') prob.driver.add_constraint('c', equals=0.0) prob.setup(check=False) prob.run() obj = prob['o'] assert_rel_error(self, obj, 20.0, 1e-6)
def test_eq_ineq_error_messages(self): prob = Problem() root = prob.root = SellarDerivatives() prob.driver = MySimpleDriver() with self.assertRaises(RuntimeError) as cm: prob.driver.add_constraint('con1') self.assertEqual(str(cm.exception), "Constraint 'con1' needs to define lower, upper, or equals.") with self.assertRaises(RuntimeError) as cm: prob.driver.add_constraint('con1', lower=0.0, upper=1.1, equals=2.2) self.assertEqual(str(cm.exception), "Constraint 'con1' cannot be both equality and inequality.") # Don't try this at home, kids prob.driver.supports['two_sided_constraints'] = False with self.assertRaises(RuntimeError) as cm: prob.driver.add_constraint('con1', lower=0.0, upper=1.1) self.assertEqual(str(cm.exception), "Driver does not support 2-sided constraint 'con1'.") # Don't try this at home, kids prob.driver.supports['equality_constraints'] = False with self.assertRaises(RuntimeError) as cm: prob.driver.add_constraint('con1', equals=0.0) self.assertEqual(str(cm.exception), "Driver does not support equality constraint 'con1'.") # Don't try this at home, kids prob.driver.supports['inequality_constraints'] = False with self.assertRaises(RuntimeError) as cm: prob.driver.add_constraint('con1', upper=0.0) self.assertEqual(str(cm.exception), "Driver does not support inequality constraint 'con1'.")
def test_eq_ineq_error_messages(self): prob = Problem() root = prob.root = SellarDerivatives() prob.driver = MySimpleDriver() # Don't try this at home, kids prob.driver.supports['Equality Constraints'] = False with self.assertRaises(RuntimeError) as cm: prob.driver.add_constraint('con1', ctype='eq') self.assertEqual(str(cm.exception), "Driver does not support equality constraint 'con1'.") # Don't try this at home, kids prob.driver.supports['Inequality Constraints'] = False with self.assertRaises(RuntimeError) as cm: prob.driver.add_constraint('con1', ctype='ineq') self.assertEqual(str(cm.exception), "Driver does not support inequality constraint 'con1'.")
def test_Sellar_state_SLSQP(self): prob = Problem() prob.root = SellarStateConnection() prob.driver = ScipyOptimizer() prob.driver.options["optimizer"] = "SLSQP" prob.driver.options["tol"] = 1.0e-8 prob.driver.add_param("z", low=np.array([-10.0, 0.0]), high=np.array([10.0, 10.0])) prob.driver.add_param("x", low=0.0, high=10.0) prob.driver.add_objective("obj") prob.driver.add_constraint("con1") prob.driver.add_constraint("con2") prob.setup(check=False) prob.run() assert_rel_error(self, prob["z"][0], 1.9776, 1e-3) assert_rel_error(self, prob["z"][1], 0.0, 1e-3) assert_rel_error(self, prob["x"], 0.0, 1e-3)
def benchmark_mppt(self): model = Problem(impl=impl) model.root = MPPT_MDP() # add optimizer model.driver = pyOptSparseDriver() model.driver.options['optimizer'] = "SNOPT" model.driver.opt_settings = { 'Major optimality tolerance': 1e-3, 'Major feasibility tolerance': 1.0e-5, 'Iterations limit': 500000000, 'New basis file': 10 } model.driver.add_objective("perf.result") model.driver.add_desvar("pt0.param.CP_Isetpt", lower=0., upper=0.4) model.driver.add_desvar("pt1.param.CP_Isetpt", lower=0., upper=0.4) model.setup(check=False) model.run() assert_rel_error(self, model["perf.result"], -9.4308562238E+03, 1e-6)
def test_simple_paraboloid_double_sided_high(self): prob = Problem() root = prob.root = Group() root.add('p1', IndepVarComp('x', 50.0), promotes=['*']) root.add('p2', IndepVarComp('y', 50.0), promotes=['*']) root.add('comp', Paraboloid(), promotes=['*']) root.add('con', ExecComp('c = x - y'), promotes=['*']) prob.driver = pyOptSparseDriver() prob.driver.add_desvar('x', low=-50.0, high=50.0) prob.driver.add_desvar('y', low=-50.0, high=50.0) prob.driver.add_objective('f_xy') prob.driver.add_constraint('c', lower=10.0, upper=11.0) prob.setup(check=False) prob.run() # Minimum should be at (7.166667, -7.833334) assert_rel_error(self, prob['x'] - prob['y'], 11.0, 1e-6)
def test_simple_array_comp2D(self): prob = Problem() root = prob.root = Group() root.add("p1", ParamComp("x", np.zeros((2, 2))), promotes=["*"]) root.add("comp", ArrayComp2D(), promotes=["*"]) root.add("con", ExecComp("c = y - 20.0", c=np.zeros((2, 2)), y=np.zeros((2, 2))), promotes=["*"]) root.add("obj", ExecComp("o = y[0, 0]", y=np.zeros((2, 2))), promotes=["*"]) prob.driver = ScipyOptimizer() prob.driver.options["optimizer"] = "SLSQP" prob.driver.add_param("x", low=-50.0, high=50.0) prob.driver.add_objective("o") prob.driver.add_constraint("c", ctype="eq") prob.setup(check=False) prob.run() obj = prob["o"] assert_rel_error(self, obj, 20.0, 1e-6)
def test_simple_paraboloid_unconstrained_SLSQP(self): prob = Problem() root = prob.root = Group() root.add("p1", ParamComp("x", 50.0), promotes=["*"]) root.add("p2", ParamComp("y", 50.0), promotes=["*"]) root.add("comp", Paraboloid(), promotes=["*"]) prob.driver = ScipyOptimizer() prob.driver.options["optimizer"] = "SLSQP" prob.driver.add_param("x", low=-50.0, high=50.0) prob.driver.add_param("y", low=-50.0, high=50.0) prob.driver.add_objective("f_xy") prob.setup(check=False) prob.run() # Optimal solution (minimum): x = 6.6667; y = -7.3333 assert_rel_error(self, prob["x"], 6.666667, 1e-6) assert_rel_error(self, prob["y"], -7.333333, 1e-6)
def test_simple_paraboloid_unconstrained_SLSQP(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', 50.0), promotes=['*']) root.add('p2', ParamComp('y', 50.0), promotes=['*']) root.add('comp', Paraboloid(), promotes=['*']) prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_param('y', low=-50.0, high=50.0) prob.driver.add_objective('f_xy') prob.driver.options['disp'] = False prob.setup(check=False) prob.run() # Optimal solution (minimum): x = 6.6667; y = -7.3333 assert_rel_error(self, prob['x'], 6.666667, 1e-6) assert_rel_error(self, prob['y'], -7.333333, 1e-6)
def test_simple_paraboloid_unconstrained_SLSQP_bounds(self): # Make sure we don't go past high/low when set. prob = Problem() root = prob.root = Group() root.add("p1", ParamComp("x", 50.0), promotes=["*"]) root.add("p2", ParamComp("y", 50.0), promotes=["*"]) root.add("comp", Paraboloid(), promotes=["*"]) root.add("obj_comp", ExecComp("obj = -f_xy"), promotes=["*"]) prob.driver = ScipyOptimizer() prob.driver.options["optimizer"] = "SLSQP" prob.driver.add_param("x", low=-50.0, high=50.0) prob.driver.add_param("y", low=-50.0, high=50.0) prob.driver.add_objective("obj") prob.setup(check=False) prob.run() assert_rel_error(self, prob["x"], 50.0, 1e-6) assert_rel_error(self, prob["y"], 50.0, 1e-6)
def test_simple_paraboloid(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', 50.0), promotes=['*']) root.add('p2', ParamComp('y', 50.0), promotes=['*']) root.add('comp', Paraboloid(), promotes=['*']) root.add('con', ExecComp('c = 15.0 - x + y'), promotes=['*']) prob.driver = pyOptSparseDriver() prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_param('y', low=-50.0, high=50.0) prob.driver.add_objective('f_xy') prob.driver.add_constraint('c') prob.setup(check=False) prob.run() # Minimum should be at (7.166667, -7.833334) assert_rel_error(self, prob['x'], 7.16667, 1e-6) assert_rel_error(self, prob['y'], -7.833334, 1e-6)
def test_fan_out(self): prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', 1.0)) root.add('p2', ParamComp('x', 1.0)) root.add('comp1', ExecComp('y = 3.0*x')) root.add('comp2', ExecComp('y = 5.0*x')) root.add('obj', ExecComp('o = i1 + i2')) root.add('con1', ExecComp('c = 15.0 - x')) root.add('con2', ExecComp('c = 15.0 - x')) # hook up non explicitly root.connect('p1.x', 'comp1.x') root.connect('p2.x', 'comp2.x') root.connect('comp1.y', 'obj.i1') root.connect('comp2.y', 'obj.i2') root.connect('comp1.y', 'con1.x') root.connect('comp2.y', 'con2.x') prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.add_param('p1.x', low=-50.0, high=50.0) prob.driver.add_param('p2.x', low=-50.0, high=50.0) prob.driver.add_objective('obj.o') prob.driver.add_constraint('con1.c', ctype='eq') prob.driver.add_constraint('con2.c', ctype='eq') prob.driver.options['disp'] = False prob.setup(check=False) prob.run() obj = prob['obj.o'] assert_rel_error(self, obj, 30.0, 1e-6)
def test_simple_paraboloid_unconstrained_SLSQP_bounds(self): # Make sure we don't go past high/low when set. prob = Problem() root = prob.root = Group() root.add('p1', ParamComp('x', 50.0), promotes=['*']) root.add('p2', ParamComp('y', 50.0), promotes=['*']) root.add('comp', Paraboloid(), promotes=['*']) root.add('obj_comp', ExecComp('obj = -f_xy'), promotes=['*']) prob.driver = ScipyOptimizer() prob.driver.options['optimizer'] = 'SLSQP' prob.driver.add_param('x', low=-50.0, high=50.0) prob.driver.add_param('y', low=-50.0, high=50.0) prob.driver.add_objective('obj') prob.driver.options['disp'] = False prob.setup(check=False) prob.run() assert_rel_error(self, prob['x'], 50.0, 1e-6) assert_rel_error(self, prob['y'], 50.0, 1e-6)
m = 300 npts = 6 restart = False # These numbers are for quick testing #n = 150 #m = 6 #npts = 2 # Instantiate model = Problem(impl=impl) root = model.root = CADRE_MDP_Group(n=n, m=m, npts=npts) # add SNOPT driver model.driver = pyOptSparseDriver() model.driver.options['optimizer'] = "SNOPT" model.driver.opt_settings = {'Major optimality tolerance': 1e-3, 'Major feasibility tolerance': 1.0e-5, 'Iterations limit': 500000000, "New basis file": 10} # Restart File if restart is True and os.path.exists("fort.10"): model.driver.opt_settings["Old basis file"] = 10 # Add parameters and constraints to each CADRE instance. names = ['pt%s' % i for i in range(npts)] for i, name in enumerate(names): # add parameters to driver
if __name__ == '__main__': # Setup and run the model. from openmdao.core.problem import Problem from openmdao.drivers.scipy_optimizer import ScipyOptimizer from openmdao.api import pyOptSparseDriver from openmdao.api import SqliteRecorder top = Problem() top.root = SellarDerivatives() # top.driver = ScipyOptimizer() # top.driver.options['optimizer'] = 'SLSQP' # top.driver.options['tol'] = 1.0e-8 top.driver = pyOptSparseDriver() top.driver.options['optimizer'] = 'SNOPT' top.driver.add_desvar('z', lower=np.array([-10.0, 0.0]), upper=np.array([10.0, 10.0])) top.driver.add_desvar('x', lower=0.0, upper=10.0) top.driver.add_objective('obj') top.driver.add_constraint('con1', upper=0.0) top.driver.add_constraint('con2', upper=0.0) rec = SqliteRecorder('sellar_snopt.db') top.driver.add_recorder(rec) rec.options['record_derivs'] = True top.setup()
root = top.root = Group() root.add('simprop', IndepVarComp('simtime', val="100")) root.add('p1', IndepVarComp('rho', val=1.0)) root.add('p2', IndepVarComp('jturbine', val=1.0)) root.add('p3', IndepVarComp('ratio', val=1.0)) root.add( 'modelica', OMModelWrapper( 'WindPowerPlants.Examples.GenericPlantRayleigh', '/Users/adam/repo/WindPowerPlants/WindPowerPlants/package.mo')) root.add('tl_peakPowerOutput', TakeLast()) root.add('tl_integratedEnergy', TakeLast()) top.driver = UniformDriver(5000) top.driver.add_desvar('p1.rho', low=1.0, high=1.5) top.driver.add_desvar('p2.jturbine', low=13000000 * 0.7, high=130000000 * 1.3) top.driver.add_desvar('p3.ratio', low=80.0, high=120.0) top.driver.add_objective('tl_peakPowerOutput.output') top.driver.add_objective('tl_integratedEnergy.output') root.connect('simprop.simtime', 'modelica.stopTime') root.connect('p1.rho', 'modelica.rho') root.connect('p2.jturbine', 'modelica.jturbine') root.connect('p3.ratio', 'modelica.ratio') root.connect('modelica.peakPowerOutput', 'tl_peakPowerOutput.input') root.connect('modelica.integratedEnergy', 'tl_integratedEnergy.input')
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)