def driver_setup(prob): """Change settings of the driver Here the type of the driver has to be selected, wether it will be an optimisation driver or a DoE driver. In both cases there are multiple options to choose from to tune the driver. Two recorders are then attached to the driver for results and N2 plotting. Args: prob (om.Problem object) : Instance of the Problem class that is used to define the current routine. """ if Rt.type == 'Optim': # TBD : Genetic algorithm # if len(Rt.objective) > 1 and False: # log.info("""More than 1 objective function, the driver will # automatically be set to NSGA2""") # prob.driver = om.pyOptSparseDriver() # multifunc driver : NSGA2 # prob.driver.options['optimizer'] = 'NSGA2' # prob.driver.opt_settings['PopSize'] = 7 # prob.driver.opt_settings['maxGen'] = Rt.max_iter # else: prob.driver = om.ScipyOptimizeDriver() prob.driver.options['optimizer'] = Rt.driver prob.driver.options['maxiter'] = Rt.max_iter prob.driver.options['tol'] = Rt.tol prob.driver.options['disp'] = True elif Rt.type == 'DoE': if Rt.doedriver == 'Uniform': driver_type = om.UniformGenerator(num_samples=Rt.samplesnb) elif Rt.doedriver == 'LatinHypercube': driver_type = om.LatinHypercubeGenerator(samples=Rt.samplesnb) elif Rt.doedriver == 'FullFactorial': driver_type = om.FullFactorialGenerator(levels=Rt.samplesnb) elif Rt.doedriver == 'CSVGenerated': file = opf.gen_doe_csv(Rt.user_config) driver_type = om.CSVGenerator(file) prob.driver = om.DOEDriver(driver_type) prob.driver.options['run_parallel'] = True prob.driver.options['procs_per_model'] = 1 else: log.error('Type of optimisation not recognize!!!') ## Attaching a recorder and a diagramm visualizer ## prob.driver.recording_options['record_inputs'] = True prob.driver.add_recorder( om.SqliteRecorder(optim_dir_path + '/circuit.sqlite')) prob.driver.add_recorder( om.SqliteRecorder(optim_dir_path + '/Driver_recorder.sql'))
def set_driver(self, wt_opt): folder_output = self.opt["general"]["folder_output"] if self.opt["driver"]["optimization"]["flag"]: step_size = self._get_step_size() # Solver has specific meaning in OpenMDAO wt_opt.model.approx_totals(method="fd", step=step_size, form=self.opt["driver"]["optimization"]["form"]) # Set optimization solver and options. First, Scipy's SLSQP if self.opt["driver"]["optimization"]["solver"] == "SLSQP": wt_opt.driver = om.ScipyOptimizeDriver() wt_opt.driver.options["optimizer"] = self.opt["driver"]["optimization"]["solver"] wt_opt.driver.options["tol"] = self.opt["driver"]["optimization"]["tol"] wt_opt.driver.options["maxiter"] = self.opt["driver"]["optimization"]["max_iter"] # The next two optimization methods require pyOptSparse. elif self.opt["driver"]["optimization"]["solver"] == "CONMIN": try: from openmdao.api import pyOptSparseDriver except: raise ImportError( "You requested the optimization solver CONMIN, but you have not installed the pyOptSparseDriver. Please do so and rerun." ) wt_opt.driver = pyOptSparseDriver() wt_opt.driver.options["optimizer"] = self.opt["driver"]["optimization"]["solver"] wt_opt.driver.opt_settings["ITMAX"] = self.opt["driver"]["optimization"]["max_iter"] elif self.opt["driver"]["optimization"]["solver"] == "SNOPT": try: from openmdao.api import pyOptSparseDriver except: raise ImportError( "You requested the optimization solver SNOPT, but you have not installed the pyOptSparseDriver. Please do so and rerun." ) wt_opt.driver = pyOptSparseDriver() try: wt_opt.driver.options["optimizer"] = self.opt["driver"]["optimization"]["solver"] except: raise ImportError( "You requested the optimization solver SNOPT, but you have not installed it within the pyOptSparseDriver. Please do so and rerun." ) wt_opt.driver.opt_settings["Major optimality tolerance"] = float( self.opt["driver"]["optimization"]["tol"] ) wt_opt.driver.opt_settings["Major iterations limit"] = int( self.opt["driver"]["optimization"]["max_major_iter"] ) wt_opt.driver.opt_settings["Iterations limit"] = int( self.opt["driver"]["optimization"]["max_minor_iter"] ) wt_opt.driver.opt_settings["Major feasibility tolerance"] = float( self.opt["driver"]["optimization"]["tol"] ) wt_opt.driver.opt_settings["Summary file"] = os.path.join(folder_output, "SNOPT_Summary_file.txt") wt_opt.driver.opt_settings["Print file"] = os.path.join(folder_output, "SNOPT_Print_file.txt") if "hist_file_name" in self.opt["driver"]["optimization"]: wt_opt.driver.hist_file = self.opt["driver"]["optimization"]["hist_file_name"] if "verify_level" in self.opt["driver"]["optimization"]: wt_opt.driver.opt_settings["Verify level"] = self.opt["driver"]["optimization"]["verify_level"] else: wt_opt.driver.opt_settings["Verify level"] = -1 # wt_opt.driver.declare_coloring() if "hotstart_file" in self.opt["driver"]["optimization"]: wt_opt.driver.hotstart_file = self.opt["driver"]["optimization"]["hotstart_file"] else: raise ValueError( "The optimizer " + self.opt["driver"]["optimization"]["solver"] + "is not yet supported!" ) elif self.opt["driver"]["design_of_experiments"]["flag"]: if self.opt["driver"]["design_of_experiments"]["generator"].lower() == "uniform": generator = om.UniformGenerator( num_samples=self.opt["driver"]["design_of_experiments"]["num_samples"], seed=self.opt["driver"]["design_of_experiments"]["seed"], ) elif self.opt["driver"]["design_of_experiments"]["generator"].lower() == "fullfact": generator = om.FullFactorialGenerator(levels=self.opt["driver"]["design_of_experiments"]["num_samples"]) elif self.opt["driver"]["design_of_experiments"]["generator"].lower() == "plackettburman": generator = om.PlackettBurmanGenerator() elif self.opt["driver"]["design_of_experiments"]["generator"].lower() == "boxbehnken": generator = om.BoxBehnkenGenerator() elif self.opt["driver"]["design_of_experiments"]["generator"].lower() == "latinhypercube": generator = om.LatinHypercubeGenerator( samples=self.opt["driver"]["design_of_experiments"]["num_samples"], criterion=self.opt["driver"]["design_of_experiments"]["criterion"], seed=self.opt["driver"]["design_of_experiments"]["seed"], ) else: raise Exception( "The generator type {} is unsupported.".format( self.opt["driver"]["design_of_experiments"]["generator"] ) ) # Initialize driver wt_opt.driver = om.DOEDriver(generator) # options wt_opt.driver.options["run_parallel"] = self.opt["driver"]["design_of_experiments"]["run_parallel"] else: raise Exception( "Design variables are set to be optimized or studied, but no driver is selected. Please enable a driver." ) return wt_opt
import openmdao.api as om from openmdao.test_suite.components.paraboloid import Paraboloid prob = om.Problem() model = prob.model model.add_subsystem('p1', om.IndepVarComp('x', 0.), promotes=['*']) model.add_subsystem('p2', om.IndepVarComp('y', 0.), promotes=['*']) model.add_subsystem('comp', Paraboloid(), promotes=['*']) model.add_design_var('x', lower=-10, upper=10) model.add_design_var('y', lower=-10, upper=10) model.add_objective('f_xy') prob.driver = om.DOEDriver(om.UniformGenerator(num_samples=10)) #prob.driver = om.DOEDriver(om.LatinHypercubeGenerator(samples=10)) prob.driver.add_recorder(om.SqliteRecorder("cases.sql")) prob.setup() prob.run_driver() prob.cleanup() cr = om.CaseReader("cases.sql") cases = cr.list_cases('driver') print(len(cases)) values = [] for case in cases: outputs = cr.get_case(case).outputs values.append((outputs['x'], outputs['y'], outputs['f_xy']))
def run_routine(): """ Run optimisation with openmdao. Function 'run_routine' is used to define the optimisation problem for openmdao. The different parameter to define variables are passed through a global dictionnay (for now). Source: *http://openmdao.org/twodocs/versions/latest/getting_started/index.html """ # sInitialize dictionnaries # init_dict() # Build the model prob = om.Problem() model = prob.model # Build model components indeps = model.add_subsystem('indeps', om.IndepVarComp()) model.add_subsystem('objective', objective_function()) model.add_subsystem('const', constraint()) # Choose between optimizer or driver if Rt.type == 'DoE': if Rt.doetype == 'uniform': driver = prob.driver = om.DOEDriver( om.UniformGenerator(num_samples=Rt.samplesnb)) elif Rt.doetype == 'fullfact': # 2->9 3->81 driver = prob.driver = om.DOEDriver( om.FullFactorialGenerator(Rt.samplesnb)) elif Rt.type == 'Optim': driver = prob.driver = om.ScipyOptimizeDriver() # SLSQP,COBYLA,shgo,TNC driver.options['optimizer'] = Rt.driver # driver.options['maxiter'] = 20 driver.options['tol'] = 1e-2 if Rt.driver == 'COBYLA': driver.opt_settings['catol'] = 0.06 # Connect problem components to model components # Design variable for key, (name, listval, minval, maxval, setcommand, getcommand) in design_var_dict.items(): norm = int(np.log10(abs(listval[0]) + 1) + 1) indeps.add_output(key, listval[0], ref=norm, ref0=0) model.connect('indeps.' + key, 'objective.' + key) model.add_design_var('indeps.' + key, lower=minval, upper=maxval) # Constraints for key, (name, listval, minval, maxval, getcommand) in res_var_dict.items(): # Select only one constrain if name in Rt.constraints: norm = int(np.log10(abs(listval[0]) + 1) + 1) model.add_constraint('const.' + name, ref=norm, lower=-0.25, upper=0.25) # Objective function model.add_objective('objective.{}'.format(Rt.objective)) # Recorder path = optim_dir_path driver.add_recorder(om.SqliteRecorder(path + '/Driver_recorder.sql')) # Run prob.setup() prob.run_driver() prob.cleanup() # Results log.info('=========================================') log.info('min = ' + str(prob['objective.{}'.format(Rt.objective)])) for key, (name, listval, minval, maxval, setcommand, getcommand) in design_var_dict.items(): log.info(name + ' = ' + str(prob['indeps.' + key]) + '\n Min :' + str(minval) + ' Max : ' + str(maxval)) log.info('Variable history') for key, (name, listval, minval, maxval, setcommand, getcommand) in design_var_dict.items(): log.info(name + ' => ' + str(listval)) log.info('=========================================') # Generate plots, maybe make a dynamic plot opf.read_results(optim_dir_path, Rt.type)