def copy_module_to_module(module_from, io_from, module_to, io_to): """ Transfer CPACS file from one module to another. Function 'copy_module_to_module' copy the CPACS file form ToolInput or ToolOutput of 'module_from' to ToolInput or ToolOutput of 'module_to' Args: module_from (str): Name of the module the CPACS file is copy from io_from (str): "in" or "out", for ToolInput or ToolOutput module_to (str): Name of the module where the CPACS file will be copy io_to (str): "in" or "out", for ToolInput or ToolOutput """ in_list = [ 'in', 'In', 'IN', 'iN', 'input', 'Input', 'INPUT', 'ToolInput', 'toolinput' ] if io_from in in_list: file_copy_from = mi.get_toolinput_file_path(module_from) else: # 'out' or anything else ('out' by default) file_copy_from = mi.get_tooloutput_file_path(module_from) log.info('Copy CPACS from:' + file_copy_from) if io_to in in_list: file_copy_to = mi.get_toolinput_file_path(module_to) else: # 'out' or anything else ('out' by default) file_copy_to = mi.get_tooloutput_file_path(module_to) log.info('Copy CPACS to:' + file_copy_to) shutil.copy(file_copy_from, file_copy_to)
def compute(self, inputs, outputs): """Launches the module""" # Updating inputs in CPACS file cpacs_path = mif.get_toolinput_file_path(self.module_name) tixi = cpsf.open_tixi(cpacs_path) for name in inputs: if name in optim_var_dict: xpath = optim_var_dict[name][4] cpsf.add_float_vector(tixi, xpath, inputs[name]) cpsf.close_tixi(tixi, cpacs_path) # Running the module wkf.run_subworkflow([self.module_name]) # Feeding CPACS file restults to outputs cpacs_path = mif.get_tooloutput_file_path(self.module_name) tixi = cpsf.open_tixi(cpacs_path) for name in outputs: if name in optim_var_dict: xpath = optim_var_dict[name][4] outputs[name] = cpsf.get_value(tixi, xpath) # Copy CPACS to input folder of next module index = Rt.modules.index(self.module_name) + 1 if index != len(Rt.modules): cpacs_path = mif.get_toolinput_file_path(Rt.modules[index]) else: cpacs_path = mif.get_toolinput_file_path(Rt.modules[0]) cpsf.close_tixi(tixi, cpacs_path)
def extract_am_data(Tool): """Get training data from aeromap. Retrieve training dataset from an aeromap. The inputs are [alt, mach, aoa, aos] parameters and the outputs are [cl, cd, cs, cml, cmd, cms]. Args: Tool (Prediction_tool): Class containing the user specification. Returns: xd (4*m numpy array): Set of m points in the 4-dimensionnal design space. yd (6*m numpy array): Set of m points in the 6-dimensionnal result space. """ cpacs_path = mif.get_toolinput_file_path('SMTrain') tixi = cpsf.open_tixi(cpacs_path) Tool.df = gen_df_from_am(tixi) Aeromap = apmf.get_aeromap(tixi, Tool.aeromap_uid) xd = np.array([Aeromap.alt, Aeromap.mach, Aeromap.aoa, Aeromap.aos]) yd = np.array([ Aeromap.cl, Aeromap.cd, Aeromap.cs, Aeromap.cml, Aeromap.cmd, Aeromap.cms ]) cpsf.close_tixi(tixi, cpacs_path) return xd.transpose(), yd.transpose()
def compute(self, inputs, outputs): """Update the geometry of the CPACS""" cpacs_path = mif.get_tooloutput_file_path(Rt.modules[-1]) cpacs_path_out = mif.get_toolinput_file_path(Rt.modules[0]) for name, infos in geom_dict.items(): infos[1].append(inputs[name][0]) cpud.update_cpacs_file(cpacs_path, cpacs_path_out, geom_dict)
def compute(self, inputs, outputs): """Launches the module""" # Updating inputs in CPACS file cpacs_path = mif.get_toolinput_file_path(self.module_name) tixi = cpsf.open_tixi(cpacs_path) for name in inputs: if name in optim_var_dict: xpath = optim_var_dict[name][4] # Change only the first vector value for aeromap param if name in apmf.XSTATES: size = tixi.getVectorSize(xpath) v = list(tixi.getFloatVector(xpath, size)) v.pop(0) v.insert(0, inputs[name]) tixi.updateFloatVector(xpath, v, size, '%g') else: cpsf.add_float_vector(tixi, xpath, inputs[name]) cpsf.close_tixi(tixi, cpacs_path) # Running the module wkf.run_subworkflow([self.module_name]) # Feeding CPACS file results to outputs cpacs_path = mif.get_tooloutput_file_path(self.module_name) tixi = cpsf.open_tixi(cpacs_path) for name in outputs: if name in optim_var_dict: xpath = optim_var_dict[name][4] if name in apmf.COEF_LIST: val = cpsf.get_value(tixi, xpath) if isinstance(val, str): val = val.split(';') outputs[name] = val[0] else: outputs[name] = val else: outputs[name] = cpsf.get_value(tixi, xpath) # Copy CPACS to input folder of next module index = Rt.modules.index(self.module_name) + 1 if index != len(Rt.modules): cpacs_path = mif.get_toolinput_file_path(Rt.modules[index]) else: cpacs_path = mif.get_toolinput_file_path(Rt.modules[0]) cpsf.close_tixi(tixi, cpacs_path)
def compute(self, inputs, outputs): """Update the geometry of the CPACS""" cpacs_path = mif.get_tooloutput_file_path(Rt.modules[-1]) cpacs_path_out = mif.get_toolinput_file_path(Rt.modules[0]) for name, (val_type, listval, minval, maxval, setcommand, getcommand) in geom_dict.items(): listval.append(inputs[name][0]) cpud.update_cpacs_file(cpacs_path, cpacs_path_out, geom_dict)
def one_iteration(): """ Compute the objective function. Function 'one_iteration' will exectute in order all the module contained in '...' and extract the ... value from the last CPACS file, this value will be returned to the optimizer CPACSUpdater.... """ global counter counter += 1 # Create the parameter in CPACS with 'CPACSUpdater' module cpacs_path = mi.get_toolinput_file_path('CPACSUpdater') cpacs_out_path = mi.get_tooloutput_file_path('CPACSUpdater') tixi = cpsf.open_tixi(cpacs_path) wkdir_path = ceaf.create_new_wkdir(Rt.date) WKDIR_XPATH = '/cpacs/toolspecific/CEASIOMpy/filesPath/wkdirPath' tixi.updateTextElement(WKDIR_XPATH, wkdir_path) # TODO: improve this part! (maybe move somewhere else) # To delete coef from previous iter if opf.get_aeromap_path(Rt.modules) != 'None': xpath = opf.get_aeromap_path(Rt.modules) aeromap_uid = cpsf.get_value(tixi, xpath + '/aeroMapUID') Coef = apmf.get_aeromap(tixi, aeromap_uid) apmf.delete_aeromap(tixi, aeromap_uid) apmf.create_empty_aeromap(tixi, aeromap_uid, 'test_optim') apmf.save_parameters(tixi, aeromap_uid, Coef) cpsf.close_tixi(tixi, cpacs_path) # Update the CPACS file with the parameters contained in design_var_dict update_cpacs_file(cpacs_path, cpacs_out_path, design_var_dict) # Save the CPACS file if counter % 1 == 0: file_copy_from = mi.get_tooloutput_file_path('CPACSUpdater') shutil.copy( file_copy_from, optim_dir_path + '/Geometry/' + 'iter_{}.xml'.format(counter)) # Run optimisation sub workflow wkf.copy_module_to_module('CPACSUpdater', 'out', Rt.modules[0], 'in') wkf.run_subworkflow(Rt.modules) wkf.copy_module_to_module(Rt.modules[-1], 'out', 'CPACSUpdater', 'in') # Extract results TODO: improve this part cpacs_results_path = mi.get_tooloutput_file_path(Rt.modules[-1]) log.info('Results will be extracted from:' + cpacs_results_path) tixi = cpsf.open_tixi(cpacs_results_path) # Update the constraints values update_res_var_dict(tixi) return compute_obj()
def __init__(self): cpacs_path = mi.get_toolinput_file_path(MODULE_NAME) if os.path.isfile(cpacs_path): self.cpacs_path = cpacs_path else: self.cpacs_path = '' self.optim_method = 'None' # 'None', 'Optim', 'DoE' self.module_pre = [] self.module_optim = [] self.module_post = []
def test_get_toolinput_file_path(): """ Test that 'get_toolinput_file_path' works """ module_name = 'ModuleTemplate' toolinput_path = m.get_toolinput_file_path(module_name) # Test that the end of the path is correct assert toolinput_path.endswith( os.path.join('CEASIOMpy', 'ceasiompy', 'ModuleTemplate', 'ToolInput', 'ToolInput.xml'))
def test_get_toolinput_file_path(): """ Test that 'get_toolinput_file_path' works """ module_name = "ModuleTemplate" toolinput_path = mi.get_toolinput_file_path(module_name) # Test that the end of the path is correct assert toolinput_path.endswith( os.path.join("CEASIOMpy", "ceasiompy", "ModuleTemplate", "ToolInput", "ToolInput.xml"))
def routine_setup(modules, routine_type, modules_pre=[]): """ Set up optimisation. Retrieve the list of modules to use in the optimization loop and launches the optimization process. """ log.info('----- Start of Optimisation module -----') global Rt, design_var_dict, res_var_dict, optim_dir_path # Setup parameters of the routine Rt.type = routine_type Rt.modules = modules Rt.driver = 'COBYLA' Rt.objective = 'cl/cd' # Rt.design_vars = Rt.constraints = ['cms'] Rt.date = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') Rt.doetype = 'uniform' Rt.samplesnb = 3 cpacs_path = mi.get_toolinput_file_path('Optimisation') # Create Optim folder for results tixi = cpsf.open_tixi(cpacs_path) wkdir = ceaf.get_wkdir_or_create_new(tixi) optim_dir_path = os.path.join(wkdir, Rt.type) if not os.path.isdir(optim_dir_path): os.mkdir(optim_dir_path) os.mkdir(optim_dir_path + '/Geometry') # Initiates dictionnaries res_var_dict, design_var_dict = init_dict(cpacs_path, modules, modules_pre) # Copy to CPACSUpdater to pass to next modules wkf.copy_module_to_module('Optimisation', 'in', 'CPACSUpdater', 'in') # Display routine info log.info('------ Problem description ------') log.info('Routine type : {}'.format(routine_type)) log.info('Objective function : {}'.format(Rt.objective)) [ log.info('Design variables : {}'.format(k)) for k in design_var_dict.keys() ] [log.info('constraints : {}'.format(k)) for k in res_var_dict.keys()] run_routine() log.info('----- End of Optimisation module -----')
def compute(self, inputs, outputs): """Make a prediction""" xp = [] for name in self.xd.index: xp.append(inputs[name][0]) xp = np.array([xp]) yp = self.Model.sm.predict_values(xp) for i, name in enumerate(self.yd.index): outputs[name] = yp[0][i] # Write the inouts to the CPACS cpacs_path = mif.get_toolinput_file_path('SMUse') tixi = cpsf.open_tixi(cpacs_path) smu.write_inouts(self.xd, xp, tixi) smu.write_inouts(self.yd, yp, tixi) cpacs_path_out = mif.get_tooloutput_file_path('SMUse') cpsf.close_tixi(tixi, cpacs_path_out)
def setup(self): """Setup inputs and outputs""" # Take CPACS file from the optimisation cpacs_path = mif.get_toolinput_file_path('SMUse') tixi = cpsf.open_tixi(cpacs_path) self.Model = smu.load_surrogate(tixi) cpsf.close_tixi(tixi, cpacs_path) df = self.Model.df df.set_index('Name', inplace=True) for name in df.index: if df.loc[name, 'type'] == 'obj': self.add_output(name) elif df.loc[name, 'type'] == 'des': self.add_input(name) self.xd = df.loc[[ name for name in df.index if df.loc[name, 'type'] == 'des' ]] self.yd = df.loc[[ name for name in df.index if df.loc[name, 'type'] == 'obj' ]]
def get_user_inputs(self): """Take user inputs from the GUI.""" cpacs_path = mif.get_toolinput_file_path('SMTrain') tixi = cpsf.open_tixi(cpacs_path) # Search working directory self.wkdir = cpsf.get_value_or_default(tixi, OPTWKDIR_XPATH, '') if self.wkdir == '': self.wkdir = ceaf.get_wkdir_or_create_new(tixi) + '/SM' if not os.path.isdir(self.wkdir): os.mkdir(self.wkdir) self.type = cpsf.get_value_or_default(tixi, SMTRAIN_XPATH + 'modelType', 'KRG') obj = cpsf.get_value_or_default(tixi, SMTRAIN_XPATH + 'objective', 'cl') self.objectives = re.split(';|,', obj) self.user_file = cpsf.get_value_or_default(tixi, SMTRAIN_XPATH + 'trainFile', '') if self.user_file == '': path = cpsf.get_value_or_default(tixi, OPTWKDIR_XPATH, '') if path != '': self.user_file = path + '/Variable_history.csv' self.data_repartition = cpsf.get_value_or_default( tixi, SMTRAIN_XPATH + 'trainingPercentage', 0.9) self.show_plots = cpsf.get_value_or_default( tixi, SMTRAIN_XPATH + 'showPlots', False) self.aeromap_case = cpsf.get_value_or_default( tixi, SMTRAIN_XPATH + 'useAeromap', False) self.aeromap_uid = cpsf.get_value_or_default( tixi, SMTRAIN_XPATH + 'aeroMapUID', '') cpsf.close_tixi(tixi, cpacs_path)
def save_model(Tool): """Save trained surrogate model to a file. Create a file to which the class containing the surrogate model and its parameters will be saved in order to be re-used using the pickle module. The file is saved in the current working directory and the path to it is added to the CPACS file. Args: Tool (Prediction_tool object): Contains the model Returns: None. """ date = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') cpacs_path = mif.get_toolinput_file_path('SMTrain') cpacs_out_path = mif.get_tooloutput_file_path('SMTrain') tixi = cpsf.open_tixi(cpacs_path) filename = Tool.wkdir + '/Surrogate_Model_' + date cpsf.create_branch(tixi, SMFILE_XPATH) tixi.updateTextElement(SMFILE_XPATH, filename) cpsf.close_tixi(tixi, cpacs_out_path) Tool.df.to_csv(Tool.wkdir + '/Data_setup.csv', index=False, na_rep='-') Model = Surrogate_model() Model.df = Tool.df Model.sm = Tool.sm sm_file = open(filename, 'wb') pickle.dump(Model, sm_file)
def run_workflow(Otp): """ Run the complete Worflow Args: Opt (class): Cl cpacs_out_path (str): Path to the output CPACS file module_list (list): List of module to inclue in the GUI """ # Copy ToolInput.xml in ToolInput dir if not already there cpacs_path = mi.get_toolinput_file_path(MODULE_NAME) if not os.path.abspath(Opt.cpacs_path) == os.path.abspath(cpacs_path): shutil.copy(Opt.cpacs_path, cpacs_path) Opt.cpacs_path = os.path.abspath(cpacs_path) # Create a new wkdir tixi = cpsf.open_tixi(Opt.cpacs_path) wkdir = ceaf.get_wkdir_or_create_new(tixi) cpsf.close_tixi(tixi, Opt.cpacs_path) # Run Pre-otimisation workflow if Opt.module_pre: wkf.run_subworkflow(Opt.module_pre, Opt.cpacs_path) if not Opt.module_optim and not Opt.module_post: shutil.copy(mi.get_tooloutput_file_path(Opt.module_pre[-1]), cpacs_path_out) # Run Optimisation workflow if Opt.module_optim: if Opt.module_pre: wkf.copy_module_to_module(Opt.module_pre[-1], 'out', 'Optimisation', 'in') else: wkf.copy_module_to_module('WorkflowCreator', 'in', 'Optimisation', 'in') if Opt.optim_method != 'None': routine_launcher(Opt) else: log.warning('No optimization method has been selected!') log.warning('The modules will be run as a simple workflow') wkf.run_subworkflow(Opt.module_optim) if not Opt.module_post: shutil.copy(mi.get_tooloutput_file_path(Opt.module_optim[-1]), cpacs_path_out) # Run Post-optimisation workflow if Opt.module_post: if Opt.module_optim: wkf.copy_module_to_module(Opt.module_optim[-1], 'out', Opt.module_post[0], 'in') elif Opt.module_pre: wkf.copy_module_to_module(Opt.module_pre[-1], 'out', Opt.module_post[0], 'in') else: wkf.copy_module_to_module('WorkflowCreator', 'in', Opt.module_post[0], 'in') # wkf.copy_module_to_module('CPACSUpdater','out',Opt.module_post[0],'in') usefuel? wkf.run_subworkflow(Opt.module_post) shutil.copy(mi.get_tooloutput_file_path(Opt.module_post[-1]), cpacs_path_out)
def one_optim_iter(): """Function to evaluate the value to optimize. Function 'one_optim_iter' will exectute in order all the module contained in '...' and extract the ... value from the last CPACS file, this value will be returned to the optimizer CPACSUpdater.... """ # Create the parameter in CPACS with 'CPACSUpdater' module cpacs_path = mi.get_toolinput_file_path('CPACSUpdater') cpacs_out_path = mi.get_tooloutput_file_path('CPACSUpdater') tixi = cpsf.open_tixi(cpacs_path) wkdir_path = ceaf.create_new_wkdir() WKDIR_XPATH = '/cpacs/toolspecific/CEASIOMpy/filesPath/wkdirPath' tixi.updateTextElement(WKDIR_XPATH, wkdir_path) # TODO: improve this part! (maybe move somewhere else) # To delete coef from previous iter aeromap_uid = cpsf.get_value(tixi, SU2_XPATH + '/aeroMapUID') Coef = apmf.get_aeromap(tixi, aeromap_uid) apmf.delete_aeromap(tixi, aeromap_uid) apmf.create_empty_aeromap(tixi, aeromap_uid, 'test_optim') apmf.save_parameters(tixi, aeromap_uid, Coef) cpsf.close_tixi(tixi, cpacs_path) # Update the CPACS file with the parameters contained in optim_var_dict update_cpacs_file(cpacs_path, cpacs_out_path, optim_var_dict) # Run optimisation sub workflow wkf.copy_module_to_module('CPACSUpdater', 'out', module_optim[0], 'in') wkf.run_subworkflow(module_optim) wkf.copy_module_to_module(module_optim[-1], 'out', 'CPACSUpdater', 'in') # Extract results TODO: improve this part cpacs_results_path = mi.get_tooloutput_file_path(module_optim[-1]) log.info('Results will be extracted from:' + cpacs_results_path) tixi = cpsf.open_tixi(cpacs_results_path) mtom = cpsf.get_value( tixi, '/cpacs/vehicles/aircraft/model/analyses/massBreakdown/designMasses/mTOM/mass' ) aeromap_uid = cpsf.get_value(tixi, SU2_XPATH + '/aeroMapUID') Coef = apmf.get_aeromap(tixi, aeromap_uid) cl = Coef.cl[0] cd = Coef.cd[0] cm = Coef.cms[0] log.info('=========================') for key, (name, listval, minval, maxval, command) in optim_var_dict.items(): log.info(name, ': ', listval[-1]) log.info('Cl/Cd: ' + str(cl / cd)) log.info('Cl: ' + str(cl)) log.info('Cd: ' + str(cd)) log.info('Cd: ' + str(cm)) log.info('MTOM:' + str(mtom)) log.info('(Cl)/MTOM:' + str(cl / mtom)) log.info('=========================') # TODO: add option to choose what will be returned # return -mtom # return -cl # return cd # return -cl/cd return -cl / cd / mtom
def run_subworkflow(module_to_run, cpacs_path_in='', cpacs_path_out=''): """Function to run a list of module in order. Function 'run_subworkflow' will exectute in order all the module contained in 'module_to_run' list. Every time the resuts of one module (generaly CPACS file) will be copied as input for the next module. Args: module_to_run (list): List of mododule to run (in order) cpacs_path_in (str): Path of the CPACS file use, if not already in the ToolInput folder of the first submodule cpacs_path_out (str): Path of the output CPACS file use, if not already in the ToolInput folder of the first submodule """ if not module_to_run: log.info('No module to run') return 0 # Check non existing module submodule_list = mi.get_submodule_list() for module in module_to_run: if module not in submodule_list: raise ValueError('No module named "' + module + '"!') # Copy the cpacs file in the first module if cpacs_path_in: shutil.copy(cpacs_path_in, mi.get_toolinput_file_path(module_to_run[0])) log.info('The following modules will be executed: ') for module in module_to_run: log.info(module) for m, module in enumerate(module_to_run): log.info( '######################################################################################' ) log.info('Run module: ' + module) log.info( '######################################################################################' ) # Go to the module directory module_path = os.path.join(LIB_DIR, module) log.info('Going to ' + module_path) os.chdir(module_path) # Copy CPACS file from previous module to this one if m > 0: copy_module_to_module(module_to_run[m - 1], 'out', module, 'in') if module == 'SettingsGUI': cpacs_path = mi.get_toolinput_file_path(module) cpacs_out_path = mi.get_tooloutput_file_path(module) # Check if there is at least one other 'SettingsGUI' after this one if 'SettingsGUI' in module_to_run[m + 1:] and m + 1 != len( module_to_run): idx = module_to_run.index('SettingsGUI', m + 1) create_settings_gui(cpacs_path, cpacs_out_path, module_to_run[m:idx]) else: create_settings_gui(cpacs_path, cpacs_out_path, module_to_run[m:]) else: # Find the python file to run for file in os.listdir(module_path): if file.endswith('.py'): if not file.startswith('__'): main_python = file # Run the module error = subprocess.call(['python', main_python]) if error: raise ValueError('An error ocured in the module ' + module) # Copy the cpacs file in the first module if cpacs_path_out: shutil.copy(mi.get_tooloutput_file_path(module_to_run[-1]), cpacs_path_out)
# MAIN # ============================================================================== def main(cpacs_path, cpacs_out_path): log.info("----- Start of " + os.path.basename(__file__) + " -----") # Load the model cpacs = CPACS(cpacs_path) Model = load_surrogate(cpacs.tixi) check_aeromap(cpacs.tixi) if get_value_or_default(cpacs.tixi, SMUSE_XPATH + "/AeroMapOnly", False): aeromap_calculation(Model.sm, cpacs) else: predict_output(Model, cpacs) cpacs.save_cpacs(cpacs_out_path, overwrite=True) log.info("----- End of " + os.path.basename(__file__) + " -----") if __name__ == "__main__": cpacs_path = mi.get_toolinput_file_path("SMUse") cpacs_out_path = mi.get_tooloutput_file_path("SMUse") main(cpacs_path, cpacs_out_path)
import ceasiompy.utils.moduleinterfaces as mif import ceasiompy.CPACSUpdater.cpacsupdater as cpud from ceasiompy.utils.ceasiomlogger import get_logger log = get_logger(__file__.split('.')[0]) # ============================================================================= # GLOBALS # ============================================================================= MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) MODULE_NAME = os.path.basename(os.getcwd()) SMUSE_XPATH = '/cpacs/toolspecific/CEASIOMpy/surrogateModelUse/' SMTRAIN_XPATH = '/cpacs/toolspecific/CEASIOMpy/surrogateModel/' cpacs_path = mif.get_toolinput_file_path('SMUse') cpacs_path_out = mif.get_tooloutput_file_path('SMUse') # ============================================================================= # ClASSES # ============================================================================= class Surrogate_model(): """Class to be dumped for later use of a model""" def __init__(self): """Creates main components""" # The dataframe that contains the ordered list of variables to be given # to this model, as well as their respective XPATH. self.data = pd.DataFrame() # The trained surrogate model object
def aeromap_case_gen(modules): """ Generate a CSV file containing a dataset generated with aeromap parameters only. Args: modules (lst) : list of modules to execute. Returns: file (str) : Path to CSV file. """ file = MODULE_DIR + '/Aeromap_generated.csv' infile = mi.get_toolinput_file_path('PredictiveTool') outfile = mi.get_tooloutput_file_path('PredictiveTool') tixi = cpsf.open_tixi(infile) # Inputs alt = [0, 0] mach = [0.5, 0.5] aoa = [-10, 10] aos = [0, 0] nt = 100 bounds = np.array([alt, mach, aoa, aos]) # Sort criterion : ‘center’, ‘maximin’, ‘centermaximin’, ‘correlation’ crit = 'corr' # Generate sample points, LHS or FullFactorial sampling = smp.LHS(xlimits=bounds, criterion=crit) xd = sampling(nt) xd = xd.transpose() # Delete the other aeromaps... maybe conserve them ? for uid in apmf.get_aeromap_uid_list(tixi): apmf.delete_aeromap(tixi, uid) # Create new aeromap aeromap_uid = 'DoE_Aeromap' am_xpath = tls.get_aeromap_path(modules) apmf.create_empty_aeromap(tixi, aeromap_uid) cpsf.add_string_vector(tixi, am_xpath + '/aeroMapUID', [aeromap_uid]) # Add parameters to aeromap Param = apmf.AeroCoefficient() for i in range(0, xd.shape[1]): Param.add_param_point(xd[0][i], xd[1][i], xd[2][i], xd[3][i]) apmf.save_parameters(tixi, aeromap_uid, Param) cpsf.close_tixi(tixi, infile) wkf.run_subworkflow(modules, cpacs_path_in=infile, cpacs_path_out=outfile) # Get Aerocoefficient tixi = cpsf.open_tixi(outfile) am_xpath = tls.get_aeromap_path(modules) aeromap_uid = cpsf.get_value(tixi, am_xpath + '/aeroMapUID') AeroCoefficient = apmf.get_aeromap(tixi, aeromap_uid) cpsf.close_tixi(tixi, outfile) dct = AeroCoefficient.to_dict() # Write to CSV df = pd.DataFrame(dct) df = df.transpose() var_type = [ 'obj' if i in objectives else 'des' if i in ['alt', 'mach', 'aoa', 'aos'] else 'const' for i in df.index ] df.insert(0, 'type', var_type) df.to_csv(file, index=True) return file
import pandas as pd import ceasiompy.utils.cpacsfunctions as cpsf import ceasiompy.utils.moduleinterfaces as mif import ceasiompy.utils.workflowfunctions as wkf import ceasiompy.Optimisation.func.dictionnary as dct import ceasiompy.Optimisation.func.tools as tls from ceasiompy.utils.ceasiomlogger import get_logger log = get_logger(__file__.split('.')[0]) # ============================================================================== # GLOBALS # ============================================================================== MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) CPACS_OPTIM_PATH = mif.get_toolinput_file_path('Optimisation') CSV_PATH = MODULE_DIR + '/Variable_library.csv' WKDIR_XPATH = '/cpacs/toolspecific/CEASIOMpy/filesPath/wkdirPath' OPTWKDIR_XPATH = '/cpacs/toolspecific/CEASIOMpy/filesPath/optimPath' OPTIM_XPATH = '/cpacs/toolspecific/CEASIOMpy/Optimisation/' AEROMAP_XPATH = '/cpacs/vehicles/aircraft/model/analyses/aeroPerformance' SU2_XPATH = '/cpacs/toolspecific/CEASIOMpy/aerodynamics/su2' banned_entries = ['wing', 'delete_old_wkdirs', 'check_extract_loads'] # ============================================================================== # CLASS # ============================================================================== class Routine:
prob = om.Problem() create_om_problem(prob) ## Run the model ## prob.run_driver() generate_results(prob) if __name__ == '__main__': log.info('----- Start of ' + os.path.basename(__file__) + ' -----') log.info('Impose the aeromap of the optimisation to all other modules') cpacs_path = mif.get_toolinput_file_path('Optimisation') cpacs_out_path = mif.get_tooloutput_file_path('Optimisation') tixi = cpsf.open_tixi(cpacs_path) try: am_uid = cpsf.get_value(tixi, opf.OPTIM_XPATH + 'aeroMapUID') except: raise ValueError('No aeromap found in the file') log.info('Aeromap ' + am_uid + ' will be used') #opf.update_am_path(tixi, am_uid) cpsf.close_tixi(tixi, cpacs_out_path) log.info('----- End of ' + os.path.basename(__file__) + ' -----')
axs[0, 2].plot(grp['cd'], grp['cl'], 'x-') axs[1, 2].plot(grp['cl'], grp['cl'] / grp['cd'], 'x-') # Set subplot options subplot_options(axs[0, 0], 'CL', 'AoA') subplot_options(axs[1, 0], 'CD', 'AoA') subplot_options(axs[0, 1], 'Cm', 'AoA') subplot_options(axs[1, 1], 'CL/CD', 'AoA') subplot_options(axs[0, 2], 'CL', 'CD') subplot_options(axs[1, 2], 'CL/CD', 'CL') fig.legend(loc='upper right') plt.show() #============================================================================== # MAIN #============================================================================== if __name__ == '__main__': log.info('----- Start of ' + os.path.basename(__file__) + ' -----') MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) cpacs_path = mi.get_toolinput_file_path(MODULE_NAME) cpacs_out_path = mi.get_tooloutput_file_path(MODULE_NAME) plot_aero_coef(cpacs_path, cpacs_out_path) log.info('----- End of ' + os.path.basename(__file__) + ' -----')
def main(): log.info("Running PyTornado...") # ===== CPACS inout and output paths ===== MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) cpacs_in_path = mi.get_toolinput_file_path(MODULE_NAME) cpacs_out_path = mi.get_tooloutput_file_path(MODULE_NAME) # ===== Delete old working directories ===== settings_from_CPACS = get_pytornado_settings_from_CPACS(cpacs_in_path) if settings_from_CPACS is not None: if settings_from_CPACS.get('deleteOldWKDIRs', False): wkdirs = glob(os.path.join(DIR_MODULE, 'wkdir_*')) for wkdir in wkdirs: shutil.rmtree(wkdir, ignore_errors=True) # ===== Paths ===== dir_pyt_wkdir = os.path.join(DIR_MODULE, 'wkdir_temp') dir_pyt_aircraft = os.path.join(dir_pyt_wkdir, 'aircraft') dir_pyt_settings = os.path.join(dir_pyt_wkdir, 'settings') dir_pyt_results = os.path.join(dir_pyt_wkdir, '_results') file_pyt_aircraft = os.path.join(dir_pyt_aircraft, 'ToolInput.xml') file_pyt_settings = os.path.join(dir_pyt_settings, 'cpacs_run.json') # ===== Make directories ===== Path(dir_pyt_wkdir).mkdir(parents=True, exist_ok=True) Path(dir_pyt_aircraft).mkdir(parents=True, exist_ok=True) Path(dir_pyt_settings).mkdir(parents=True, exist_ok=True) Path(dir_pyt_results).mkdir(parents=True, exist_ok=True) # ===== Setup ===== shutil.copy(src=cpacs_in_path, dst=file_pyt_aircraft) mi.check_cpacs_input_requirements(cpacs_in_path) # ===== Get PyTornado settings ===== cpacs_settings = get_pytornado_settings(cpacs_in_path) with open(file_pyt_settings, "w") as fp: dump_pretty_json(cpacs_settings, fp) # ===== PyTornado analysis ===== pytornado = import_pytornado('pytornado.stdfun.run') #pytornado.standard_run(args=pytornado.StdRunArgs(run=file_pyt_settings, verbose=True)) results = pytornado.standard_run( args=pytornado.StdRunArgs(run=file_pyt_settings, verbose=True)) # ===== Extract load ===== tixi = cpsf.open_tixi(cpacs_in_path) extract_loads_xpath = '/cpacs/toolspecific/pytornado/save_results/extractLoads' extract_loads = cpsf.get_value_or_default(tixi, extract_loads_xpath, False) if extract_loads: _get_load_fields(results, dir_pyt_results) # ===== Clean up ===== shutil.copy(src=file_pyt_aircraft, dst=cpacs_out_path) wkdir = ceaf.get_wkdir_or_create_new(tixi) dst_pyt_wkdir = os.path.join( wkdir, 'CFD', 'PyTornado', f"wkdir_{datetime.strftime(datetime.now(), '%F_%H%M%S')}") shutil.copytree(src=dir_pyt_wkdir, dst=dst_pyt_wkdir) shutil.rmtree(dir_pyt_wkdir, ignore_errors=True) log.info("PyTornado analysis completed")