def dymola_simulation(model_info, path_dymola, solver, printInfo = True): ''' ''' # Retrieving model information root_path = model_info['root_path'] library_path = model_info['library_path'] model_path = model_info['model_path'] model_name = model_info['model_name'] output_path = model_info['output_path'] dymola = None try: if printInfo: print("Creating and starting Dymola instance") # Creating dymola instance dymola = DymolaInterface(dymolapath = path_dymola) if printInfo: print(f"Using Dymola port:" + str(dymola._portnumber)) print(f"Changing working directory to: {output_path}") try: if not os.path.exists(output_path): os.makedirs(output_path) print("Working directory created") except OSError as ex: print("1: Failed to create folder for working directory") # CHANGING THE PATH TO OPENING THE LIBRARY AND THE MODEL result = dymola.cd(root_path) if not result: print("1: Failed to change working directory") # Opening OpenIPSL library dymola.openModel(library_path) if result and printInfo: print("Library opened") # Opening model dymola.openModel(model_path) if result and printInfo: print("Model opened") # CHANGING THE PATH FOR THE WORKING DIRECTORY # Note that the model is already opened result = dymola.cd(output_path) if not result: print("1: Failed to change working directory") dymola.ExecuteCommand("Advanced.TranslationInCommandLog = true") # Simulating the model if solver == 'dassl': dymola.ExecuteCommand("Advanced.Define.DAEsolver = true") print("DAE setting changed for dassl") if solver in ["Rkfix2", "Rkfix4", "Euler"]:
def TranslateModel(model_path, name, position): """ Function to handle the Compilation of Modelica models inputs model_path: path of the model name: name of the subsystems position: position number of the subsystems returns: None """ global gl_model_compiled if gl_model_compiled[position - 1] == False: import os import sys global dymola """ Dymola configurations""" if dymola is None: # Work-around for the environment variable sys.path.insert( 0, os.path.join( r'C:\Program Files\Dymola 2018 FD01\Modelica\Library\python_interface\dymola.egg' )) # Import Dymola Package from dymola.dymola_interface import DymolaInterface # Start the interface dymola = DymolaInterface() """ Compilation """ # Open dymola library for lib in Init.path_lib: check1 = dymola.openModel(os.path.join(lib, 'package.mo')) print("Opening successful " + str(check1)) # Force Dymola to use 64 bit compiler dymola.ExecuteCommand("Advanced.CompileWith64=2") dymola.cd(Init.path_res + '\\' + Init.name_wkdir + '\\' + name) # Translate the model check2 = dymola.translateModel(model_path) print("Translation successful " + str(check2)) if check2 is True: gl_model_compiled[position - 1] = True
#Creation of matrix with names, paths and variables machines = { 'names' : ["GENROU","GENSAL", "GENCLS", "GENROE", "GENSAE", "CSVGN1"], 'path' : ["OpenIPSL.Examples.Machines.PSSE.GENROU", "OpenIPSL.Examples.Machines.PSSE.GENSAL", "OpenIPSL.Examples.Machines.PSSE.GENCLS", "OpenIPSL.Examples.Machines.PSSE.GENROE", "OpenIPSL.Examples.Machines.PSSE.GENSAE", "OpenIPSL.Examples.Machines.PSSE.CSVGN1"], 'delta' : ['gENROU.delta', 'gENSAL.delta', 'gENCLS.delta', 'gENROE.delta', 'gENSAE.delta', 'cSVGN1.delta'], 'pelec' : ['gENROU.PELEC', 'gENSAL.PELEC', 'gENCLS.PELEC', 'gENROE.PELEC', 'gENSAE.PELEC', 'cSVGN1.PELEC'], 'speed' : ['gENROU.SPEED', 'gENSAL.SPEED', 'gENCLS.SPEED', 'gENROE.SPEED', 'gENSAE.SPEED', 'cSVGN1.SPEED']} # In[5]: #For loop that will iterate between machines, simulate, and create the .csv file for machineNumber, machineName in enumerate(machines['names']): try: print(f"{machineName} Simulation Start...") dymola.cd("/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Machines/" + machineName) resultPath = f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Machines/{machineName}/" + machineName result = dymola.simulateModel(machines['path'][machineNumber], stopTime=10.0, numberOfIntervals = 5000, resultFile = resultPath) if not result: print("Simulation failed or model was not found. Below is the translation log:\n") log = dymola.getLastErrorLog() print(log) else: print(f"{machineName} Simulation OK...") print(".csv Writing Start...") #Selecting Result File sim = SimRes(f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Machines/{machineName}/{machineName}.mat") #Selecting Variables
def dymola_simulation(model_info, path_dymola, solver, printInfo=True): ''' ''' # Retrieving model information root_path = model_info['root_path'] library_path = model_info['library_path'] model_path = model_info['model_path'] model_name = model_info['model_name'] output_path = model_info['output_path'] dymola = None try: if printInfo: print("Creating and starting Dymola instance") # Creating dymola instance dymola = DymolaInterface(dymolapath=path_dymola) if printInfo: print(f"Using Dymola port:" + str(dymola._portnumber)) print(f"Changing working directory to: {output_path}") try: if not os.path.exists(output_path): os.makedirs(output_path) print("Working directory created") except OSError as ex: print("1: Failed to create folder for working directory") # CHANGING THE PATH TO OPENING THE LIBRARY AND THE MODEL result = dymola.cd(root_path) if not result: print("1: Failed to change working directory") # Opening OpenIPSL library dymola.openModel(library_path) if result and printInfo: print("Library opened") # Opening model dymola.openModel(model_path) if result and printInfo: print("Model opened") # CHANGING THE PATH FOR THE WORKING DIRECTORY # Note that the model is already opened result = dymola.cd(output_path) if not result: print("1: Failed to change working directory") # Simulating the model if solver == 'dassl': dymola.Execute("Advanced.Define.DAEsolver = true") print("DAE setting changed for dassl") if solver in ["Rkfix2", "Rkfix4", "Euler"]: print("Running simulation...") result = dymola.simulateModel(model_name, method=solver, stopTime=120, numberOfIntervals=240000, tolerance=1e-06, resultFile=model_name + "_{}".format(solver)) else: # Settings for dassl print("Running simulation...") result = dymola.simulateModel(model_name, method=solver, stopTime=120, numberOfIntervals=5000, tolerance=1e-06, resultFile=model_name + "_{}".format(solver)) if not result: print("Simulation failed. Below is the error log:") log = dymola.getLastErrorLog() print(log) else: print("Simulation OK") # Close Dymola dymola.close() except DymolaException as ex: if printInfo: print(("Error: " + str(ex))) else: pass finally: if dymola is not None: dymola.close() dymola = None
class DymolaBaseEnv(gym.Env): """ A variation of the ModelicaGym FMU interface that uses the Dymola API. To install dymola API add dymola.exe to the system PATH variable. """ def __init__(self): """ :param model_path: path to the model FMU. Absolute path is advised. :param mode: FMU exporting mode "CS" or "ME" :param config: dictionary with model specifications: model_input_names - names of parameters to be used as action. model_output_names - names of parameters to be used as state descriptors. model_parameters - dictionary of initial parameters of the model time_step - time difference between simulation steps positive_reward - (optional) positive reward for default reward policy. Is returned when episode goes on. negative_reward - (optional) negative reward for default reward policy. Is returned when episode is ended :param log_level: level of logging to be used """ with open(self.conf_file) as f: config = json.load(f) logger.setLevel(config['log_level']) self.model_name = config['mo_name'] self.dymola = None self.libs = config['libs'] self.reset_dymola() # Parameters required by this implementation self.tau = config['time_step'] self.model_input_names = [] for i in range(len(config['action_names'])): if config['action_len'][i] <= 1: self.model_input_names += [config['action_names'][i]] else: self.model_input_names += [ f"{config['action_names'][i]}[{x}]" for x in range(1, 1 + config['action_len'][i]) ] self.model_output_names = config['state_names'] self.model_parameters = config['model_parameters'] self.default_action = config['default_action'] self.add_names = config['additional_debug_states'] self.method = config['method'] self.negative_reward = config['negative_reward'] self.positive_reward = config['positive_reward'] if not len(self.model_input_names) == len(self.default_action): raise Exception( "The number of action names and the default action values should be the same length." ) # initialize the model time and state self.start = 0 self.stop = self.tau self.done = False self.state = self.reset() # OpenAI Gym requirements self.action_space = self._get_action_space() self.observation_space = self._get_observation_space() self.debug_data = {name: [] for name in self.model_output_names} self.rbc_action_names = [] for i in range(len(config['rbc_action_names'])): if config['rbc_action_len'][i] <= 1: self.rbc_action_names += [config['rbc_action_names'][i]] else: foo = config['rbc_action_names'][i] bar = config['rbc_action_len'][i] self.rbc_action_names += [ f"{foo}[{x}]" for x in range(1, 1 + bar) ] self.rbc_action = [] self.data = None self.tracker = 0 self.exception_flag = False # OpenAI Gym API def render(self, **kwargs): """ OpenAI Gym API. Determines how current environment state should be rendered. :param kwargs: :return: implementation should return rendering result """ pass def reset(self): """ OpenAI Gym API. Determines restart procedure of the environment :return: environment state after restart """ logger.info( "Resetting the environment and deleting old results files.") if os.path.isdir('temp_dir'): # print("Removing old files...") for file in os.listdir('temp_dir'): try: os.remove(os.path.join(os.getcwd(), 'temp_dir', file)) except: pass self.action = self.default_action self.start = 0 self.stop = self.tau logger.info("The model is being reset") res = self.dymola.simulateExtendedModel( self.model_name, startTime=self.start, stopTime=self.stop, initialNames=self.model_input_names, initialValues=self.action, finalNames=self.model_output_names) self.state = res[1] self.cached_values = None self.cached_state = None self.debug_data = { name: [] for name in self.model_output_names + self.add_names } self.state = self.postprocess_state(self.state) self.done = not (res[0]) if self.done: logger.error( f"Model failed to reset. Dymola simulation from time {self.start} to {self.stop} failed with error message: {self.dymola.getLastError()}" ) return flatten(self.state) def reset_dymola(self): if self.dymola: # this doesn't really seem to be working. It hangs self.dymola.close() self.dymola = DymolaInterface() self.dymola.ExecuteCommand("Advanced.Define.DAEsolver = true") # load libraries loaded = [] #self.dymola.eraseClasses('Modelica') for lib in self.libs: # all paths relative to the cwd loaded += [self.dymola.openModel(lib, changeDirectory=False)] if not loaded[-1]: logger.error(f"Could not find library {lib}") if not False in loaded: logger.debug("Successfully loaded all libraries.") if not os.path.isdir('temp_dir'): os.mkdir('temp_dir') self.temp_dir = os.path.join(os.getcwd(), "temp_dir") self.dymola.cd('temp_dir') logger.debug("Dymola has been reset") return def step(self, action): """ OpenAI Gym API. Determines how one simulation step is performed for the environment. Simulation step is execution of the given action in a current state of the environment. :param action: action to be executed. :return: resulting state """ logger.debug("Experiment next step was called.") if self.done: logger.warning( """You are calling 'step()' even though this environment has already returned done = True. You should always call 'reset' once you receive 'done = True' -- any further steps are undefined behavior.""") return np.array(self.state), self.negative_reward, self.done, {} # check if action is a list. If not - create list of length 1 try: iter(action) except TypeError: action = [action] logger.warning( "Model input values (action) should be passed as a list") # Check if number of model inputs equals number of values passed if len(action) != len(list(self.model_input_names)): message = "List of values for model inputs should be of the length {}," \ "equal to the number of model inputs. Actual length {}".format( len(list(self.model_input_names)), len(action)) logger.error(message) raise ValueError(message) # Set input values of the model logger.debug("model input: {}, values: {}".format( self.model_input_names, action)) try: self.done, state = self.do_simulation() self.state = state self.start += self.tau self.stop += self.tau except: print("exception") self.reset() self.exception_flag = True return flatten(self.state), self._reward_policy(), self.done, {} # logging def get_log_file_name(self): log_date = datetime.datetime.utcnow() log_file_name = "{}-{}-{}_{}.txt".format(log_date.year, log_date.month, log_date.day, self.model_name) return log_file_name # internal logic def _get_action_space(self): """ Returns action space according to OpenAI Gym API requirements. :return: one of gym.spaces classes that describes action space according to environment specifications. """ low = -1 * np.ones(len(self.model_input_names)) high = 1 * np.ones(len(self.model_input_names)) return spaces.Box(low, high) def _get_observation_space(self): """ Returns state space according to OpenAI Gym API requirements. :return: one of gym.spaces classes that describes state space according to environment specifications. """ low = -1 * np.ones(len(self.model_output_names)) high = 1 * np.ones(len(self.model_output_names)) return spaces.Box(low, high) def _is_done(self, results): """ Determines logic when experiment is considered to be done. :return: boolean flag if current state of the environment indicates that experiment has ended. """ return not results[0] def do_simulation(self): """ Executes simulation by FMU in the time interval [start_time; stop_time] currently saved in the environment. :return: resulting state of the environment. """ #print("============================") logger.debug("Simulation started for time interval {}-{}".format( self.start, self.stop)) self.act = self.action + self.rbc_action #self.debug_points[-1*self.n_points:] found = self.dymola.importInitialResult('dsres.mat', atTime=self.start) print(found) x = self.dymola.simulateExtendedModel( self.model_name, startTime=self.start, stopTime=self.stop, initialNames=self.model_input_names + self.rbc_action_names, initialValues=self.act, finalNames=self.model_output_names) finished, state = x if finished == False: print('finished = False') print(self.dymola.getLastError()) state = self.reset() finished = True self.get_state_values() logger.debug("Simulation results: {}".format(state)) return not finished, state def _reward_policy(self): """ Determines reward based on the current environment state. By default, implements simple logic of penalizing for experiment end and rewarding each step. :return: reward associated with the current state """ if self.exception_flag: self.exception_flag = False if self.done: reward = self.negative_reward else: reward = self.positive_reward return reward def get_state_values(self): """ Extracts the values of model outputs at the end of modeling time interval from simulation result :return: Values of model outputs as tuple in order specified in `model_outputs` attribute """ self.data = DyMat.DyMatFile('temp_dir/dsres.mat') for name in self.debug_data: self.debug_data[name] += self.data[name].tolist() for name in self.add_names + self.model_input_names + self.rbc_action_names: if not name in self.debug_data: self.debug_data.update({name: []}) self.debug_data[name] += self.data[name].tolist() return def _set_init_parameter(self): """ Sets initial parameters of a model. :return: environment """ if self.model_parameters is not None: self.model.set(list(self.model_parameters), list(self.model_parameters.values())) return self
'/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/TurbineGovernors/' ) os.chdir( f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/TurbineGovernors/" ) for tgovernorNumber, tgovernorName in enumerate(tgovernors['names']): os.makedirs(f'{tgovernorName}') # In[5]: #For loop that will iterate between turbine governors, simulate, and create the .csv fileurb for tgovernorNumber, tgovernorName in enumerate(tgovernors['names']): try: print(f"{tgovernorName} Simulation Start...") dymola.cd( "/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/TurbineGovernors/" + tgovernorName) resultPath = f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/TurbineGovernors/{tgovernorName}/" + tgovernorName result = dymola.simulateModel(tgovernors['path'][tgovernorNumber], stopTime=10.0, numberOfIntervals=5000, resultFile=resultPath) if not result: print( "Simulation failed or model was not found. Below is the translation log:\n" ) log = dymola.getLastErrorLog() print(log) try: os.chdir( f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/TurbineGovernors/{tgovernorName}/"
def main(): """Create a system and multiple subsystems""" AHU = System.System() subsystems = AHU.GenerateSubSys() """Prepare the working Directory""" os.chdir(Init.path_res) os.mkdir(str(Init.name_wkdir)) os.chdir(str(Init.name_wkdir)) """Create one directory for each of the subsystems and one for the inputs""" for s in subsystems: os.mkdir(s._name) os.mkdir("Inputs") """Load the FMU model, set the experiment and initialize the inputs""" global dymola dymola = None # Work-around for the environment variable sys.path.insert(0, os.path.join(str(Init.path_dymola))) # Import Dymola Package from dymola.dymola_interface import DymolaInterface # Start the interface dymola = DymolaInterface() """ Simulation """ # Open dymola library for lib in Init.path_lib: check1 = dymola.openModel(os.path.join(lib, 'package.mo')) print('Opening successful ' + str(check1)) dymola.cd(Init.path_res + '\\' + Init.name_wkdir) # Translate the model to FMU if Init.create_FMU: dymola.ExecuteCommand('translateModelFMU("' + Init.path_fmu + '", true, "' + Init.name_fmu + '", "1", "cs", false, 0)') else: shutil.copyfile( Init.path_res + "\\" + Init.name_fmu + ".fmu", Init.path_res + '\\' + Init.name_wkdir + '\\' + Init.name_fmu + '.fmu') model = load_fmu(Init.path_res + '\\' + Init.name_wkdir + '\\' + Init.name_fmu + '.fmu') model.set('humidifierWSP1', 0) model.set('valveHRS', 0) model.set('valvePreHeater', 0) model.set('valveHeater', 0) model.set('valveCooler', 0) model.initialize() model.do_step(0, Init.sync_rate) """Variables storing (time) steps""" time_step = Init.sync_rate time_storage = 0 start = time.time() counter = 0 """Variables storing commands""" storage_commands = np.zeros([5, 1]) supplyTemps = [] """There are currently three different options: 1. NC-OPT algorithm 2. NC-OPT algorithm using parallel computing 3. BExMoC algorithm """ """The algorithms work with a discrete *time_step*. In each step, the current measurements are taken using the :func:`GetMeasurements' method. """ while time_step <= Init.sync_rate * Init.stop_time: # Variable for the final commands of all subsystems command_all = [] if Init.algorithm == 'NC_DMPC': if time_step - time_storage >= Init.optimization_interval or time_step == Init.sync_rate: """ Consider the subsystems in multiple iterations, either in parallel or in sequential order """ for k in range(4): command_all = [] if Init.parallelization: def f(s): commands = s.CalcDVvalues(time_step, time_storage, k, model) return commands p = Pool(4) commands = p.map(f, [ subsystems[0], subsystems[1], subsystems[2], subsystems[3], subsystems[4] ]) command_all = commands else: for s in subsystems: commands = s.CalcDVvalues(time_step, time_storage, k, model) print(k, s._name, commands) command_all.append(commands) elif Init.algorithm == 'BExMoC': #Consider each subsystem sequentially for s in subsystems: print(s._name) """The main calculations are carried out by invoking the :func:'CalcDVvalues' method. The BExMoC algorithm exchanges tables between the subsystems in a .mat format""" commands = (s.CalcDVvalues(time_step, time_storage, 0, model)) command_all.append(commands) #Save the look-up tables in .mat files (sio.savemat( (Init.path_res + '\\' + Init.name_wkdir + '\\' + s._name + '\\' + 'DV_lookUpTable' + str(counter) + '.mat'), {'DV_lookUpTable': s.lookUpTables[1]})) (sio.savemat( (Init.path_res + '\\' + Init.name_wkdir + '\\' + s._name + '\\' + 'Costs_lookUpTable' + str(counter) + '.mat'), {'Cost_lookUpTable': s.lookUpTables[0]})) (sio.savemat( (Init.path_res + '\\' + Init.name_wkdir + '\\' + s._name + '\\' + 'Output_Table' + str(counter) + '.mat'), {'Output_Table': s.lookUpTables[2]})) (sio.savemat( (Init.path_res + '\\' + Init.name_wkdir + '\\' + s._name + '\\' + 'command' + str(counter) + '.mat'), {'Output_Table': commands})) #For real time experiments, the excecution needs to be paused if Init.realtime: if time_step > 0: time.sleep(max(Init.sync_rate - time.time() + start, 0)) start = time.time() else: length = len(Init.name) for l, val in enumerate(command_all): if Init.names_DVs[length - l - 1] != None: model.set(Init.names_DVs[length - l - 1], val) print(val) model.do_step(time_step, Init.sync_rate) print('Proceding') if time_step - time_storage >= Init.optimization_interval: time_storage = time_step time_step += Init.sync_rate counter += 1 Objective_Function.CloseDymola()
#Create Exciters folder os.makedirs( '/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Exciters/') os.chdir( f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Exciters/") for exciterNumber, exciterName in enumerate(exciters['names']): os.makedirs(f'{exciterName}') # In[5]: #For loop that will iterate between exciters, simulate, and create the .csv file for exciterNumber, exciterName in enumerate(exciters['names']): try: print(f"{exciterName} Simulation Start...") dymola.cd( "/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Exciters/" + exciterName) resultPath = f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Exciters/{exciterName}/" + exciterName result = dymola.simulateModel(exciters['path'][exciterNumber], stopTime=10.0, numberOfIntervals=5000, resultFile=resultPath) if not result: print( "Simulation failed or model was not found. Below is the translation log:\n" ) log = dymola.getLastErrorLog() print(log) try: os.chdir( f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Exciters/{exciterName}/"
#Delete old results shutil.rmtree('' + FMachinesWorkingDir + '') #Create Exciters folder os.makedirs('' + FMachinesWorkingDir + '') os.chdir(f"" + FMachinesWorkingDir + "") for machineNumber, machineName in enumerate(machines['names']): os.makedirs(f'{machineName}') # In[28]: #For loop that will iterate between machines, simulate, and create the .csv file for machineNumber, machineName in enumerate(machines['names']): try: print(f"Fault {machineName} Simulation Start...") dymola.cd("" + FMachinesWorkingDir + machineName) resultPath = "/" + FMachinesWorkingDir + f"{machineName}/" + machineName #Changing the solver if it is CSVGN1 if machineName == 'CSVGN1': result = dymola.simulateModel(machines['path'][machineNumber], stopTime=10.0, method="dassl", tolerance=1e-4, numberOfIntervals=500, resultFile=resultPath) else: result = dymola.simulateModel(machines['path'][machineNumber], stopTime=10.0, method="Rkfix2", tolerance=1e-06, numberOfIntervals=5000,
shutil.rmtree('/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/PowerSystemStabilizers/') #Create Power System Stabilizers folder os.makedirs('/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/PowerSystemStabilizers/') os.chdir(f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/PowerSystemStabilizers/") for pssNumber, pssName in enumerate(psss['names']): os.makedirs(f'{pssName}') # In[15]: #For loop that will iterate between power system stabilizers, simulate, and create the .csv fileurb for pssNumber, pssName in enumerate(psss['names']): try: print(f"{pssName} Simulation Start...") dymola.cd("/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/PowerSystemStabilizers/" + pssName) resultPath = f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/PowerSystemStabilizers/{pssName}/" + pssName result = dymola.simulateModel(psss['path'][pssNumber], stopTime=10.0, numberOfIntervals = 5000, resultFile = resultPath) if not result: print("Simulation failed or model was not found. Below is the translation log:\n") log = dymola.getLastErrorLog() print(log) try: os.chdir(f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/PowerSystemStabilizers/{pssName}/") os.remove("dsin.txt") except: pass else:
# In[4]: #Setting Dymola Interface dymola = DymolaInterface("/opt/dymola-2020-x86_64/bin64/dymola.sh") #Setting OpenIPSL library dymola.openModel( "/home/manuelnvro/dev/Gitted/PythonTesting/OpenIPSL-master/OpenIPSL/package.mo" ) print("Dymola Simulation Start...") # In[5]: try: #Set WorkingDir dymola.cd("/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola") resultPath = "/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/EXAC1" #Dymola Simulation result = dymola.simulateModel("OpenIPSL.Examples.Controls.PSSE.ES.EXAC1", numberOfIntervals=5000, resultFile=resultPath) if not result: print("Simulation failed. Below is the translation log.") log = dymola.getLastErrorLog() print(log) exit(1) print("Simulation OK") #Close Dymola dymola.close() #Selecting result file sim = SimRes(
class DymolaLauncher(object): """ Dymola Launcher """ def __init__(self, **kwargs): """ This class is aimed to launch Dymola jobs via the python interface @ In, kwargs, dict, the dictionary of options """ from dymola.dymola_interface import DymolaInterface # intialize dymola cwd = os.getcwd() if sys.platform.startswith("win"): print("trying to find dymola executable") found = None for item in sys.path: if item.endswith("dymola.egg"): found = item if found is not None: print("dymola found in: ", found) dymola_exe = os.path.join( os.path.dirname( os.path.dirname(os.path.dirname( os.path.dirname(found)))), "bin64", "dymola.exe") print("dymola exe: ", dymola_exe) self.dymola = DymolaInterface(dymolapath=dymola_exe) else: print("dymola not found in", sys.path) self.dymola = DymolaInterface() else: self.dymola = DymolaInterface() self.workDir = kwargs.get("workingDir") if not os.path.isabs(self.workDir): self.workDir = os.path.join(cwd, self.workDir) print("swd", self.workDir, "cwd", cwd, "MODELICAPATH", os.environ.get("MODELICAPATH", "")) self.silent = kwargs.get("silent") self.dymola.cd(self.workDir) self.dymola.experimentSetupOutput(events=False) def run(self, input): """ Run the input file @ In, input, str, the input file to run @ Out, None """ self.returnOut = self.dymola.RunScript(input, silent=self.silent) def getResultOutput(self): """ Return the result @ In, None @ Out, outcome, tuple, outcome (result, returnCode, log) """ if not self.returnOut: outcome = (None, -1, self.dymola.getLastErrorLog()) else: outcome = (self.returnOut, 0, self.dymola.getLastErrorLog()) print("result", outcome) return outcome def close(self): """ Finalize dymola @ In, None @ Out, None """ self.dymola.close()