def compute(self, inputs, outputs): """Compute the objective expression""" global counter counter += 1 cpacs_path = mif.get_tooloutput_file_path(Rt.modules[-1]) # Save the CPACS file for this iteration if counter % Rt.save_iter == 0: loc = optim_dir_path + '/Geometry/' + 'iter_{}.xml'.format(counter) shutil.copy(cpacs_path, loc) # Add new variables to dictionnary tixi = cpsf.open_tixi(cpacs_path) dct.update_dict(tixi, optim_var_dict) # Change local wkdir for the next iteration tixi.updateTextElement(opf.WKDIR_XPATH, ceaf.create_new_wkdir(Rt.date, Rt.type)) for obj in Rt.objective: var_list = splt('[+*/-]', obj) for v in var_list: if not v.isdigit() and v != '': exec('{} = inputs["{}"]'.format(v, v)) result = eval(obj) if Rt.minmax == 'min': outputs['Objective function ' + obj] = -result else: outputs['Objective function ' + obj] = result cpsf.close_tixi(tixi, cpacs_path)
def setup(self): """ Setup inputs and outputs""" declared = [] for obj in Rt.objective: var_list = splt('[+*/-]', obj) for v in var_list: if v not in declared: self.add_input(v) declared.append(v) self.add_output('Objective function ' + obj)
def var_and_signs( csin ): # Ex: if csin = 'Qsol+Qr-Qlat-Qsens' (or '+Qsol+Qr-Qlat-Qsens') # this function will return: # ['Qsol', 'Qr', 'Qlat', 'Qsens'] , [1.0, 1.0, -1.0, -1.0] from re import split as splt # sgn1 = '+' cvar = splt('\-|\+',csin) if cvar[0] == '': if csin[0] == '-': sgn1 = '-' cvar = cvar[1:] ccum = '' for cc in cvar: ccum=ccum+'|'+cc ccum = ccum+'|' ctt=splt("'"+ccum+"'",csin) csgn = ctt[:-1] isgn = [] for cs in csgn: isgn.append(float(cs+'1')) return cvar, isgn
def extract_data_set(Tool): """Get training data from file. Retrieve training dataset from a file or generates it automatically. The file format must be a CSV with each variable parameters and values are in a row. The file must also contain a 'Name' and a 'type' column which are needed to describe the variable. Args: Tool (Prediction_tool object): Returns: x (n*m numpy array): Set of m points in the n-dimensionnal design space. y (p*m numpy array): Set of m points in the p-dimensionnal result space. """ df = pd.read_csv(Tool.user_file) df = df.rename(columns={'Unnamed: 0': 'Name'}) # Separate the input and output points x = df.loc[[i for i, v in enumerate(df['type']) if v == 'des']] y = df.loc[[i for i, v in enumerate(df['type']) if v == 'obj']] df = df.loc[[i for i, v in enumerate(df['type']) if v in ['obj', 'des']]] df_data = df[['Name', 'type', 'getcmd', 'setcmd']] df = df.set_index('Name') y = y.set_index('Name') # Extract the iteration results only x = x[[i for i in x.columns if i.isdigit()]] df = df[[i for i in df.columns if i.isdigit()]] # Add user-specified objectives for obj in Tool.objectives: if obj not in df.index: var_list = splt('[+*/-]', obj) for v in var_list: if not v.isdigit() and v != '' and v in df.index: exec('{} = df.loc["{}"]'.format(v, v)) df_data = Tool.df.append({ 'Name': obj, 'type': 'obj' }, ignore_index=True) y.loc[obj] = eval(obj) Tool.objectives = y.index Tool.df = pd.concat([Tool.df, df_data], ignore_index=True) y = y[[i for i in y.columns if i.isdigit()]] log.info('Set extracted') return x.transpose().to_numpy(), y.transpose().to_numpy()
def extract_data_set(file): """Get training data from file. Retrieve training dataset from a file or generates it automatically. The file format must be a CSV with each variable parameters and values are in a row. The file must also contain a 'Name' and a 'type' column which are needed to describe the variable. Args: file (str) : Path to user-specified file (CSV format) Returns: x (DataFrame) : Set of points in the design space y (DataFrame) : Set of points in the result space TODO: * Maybe better deal with the dataframe, case of multiple objective functions ? """ df = pd.read_csv(file) df = df.rename(columns={'Unnamed: 0': 'Name'}) # Drop duplicate (first and second columns are the same) df = df.drop('0', 1) # Separate the input and output points x = df.loc[[i for i, v in enumerate(df['type']) if v == 'des']] y = df.loc[[i for i, v in enumerate(df['type']) if v == 'obj']] df = df.set_index('Name') # Extract the iteration results only x = x[[i for i in x.columns if i.isdigit()]] df = df[[i for i in df.columns if i.isdigit()]] # Compute the objectives in the aeromap case, else they are already given if 'Variable_history' not in file: y = pd.DataFrame() for i, obj_expr in enumerate(objectives): for name in splt('[+*/-]', obj_expr): obj_expr = obj_expr.replace(name, 'df.loc["{}"]'.format(name)) exec('y["{}"] = {}'.format(objectives[i], obj_expr)) else: y = y[[i for i in y.columns if i.isdigit()]].transpose() return x.transpose().to_numpy(), y.to_numpy()
def compute_obj(): """ Interpret the objective variable command. Get all the values needed to compute the objective function and evaluates its expression. Returns ------- None. """ # Get variable keys from objective function string var_list = splt('[+*/-]', Rt.objective) # Create local variable and assign value for v in var_list: exec('{} = res_var_dict["{}"][1][-1]'.format(v, v)) result = eval(Rt.objective) log.info('Objective function {} : {}'.format(Rt.objective, result)) # Evaluate objective function expression return -result