def simulator(self): try: dymola = None dymola = DymolaInterface("C:/Program Files/Dymola 2019 FD01/bin64/Dymola.exe") openResult = dymola.openModel(self.packageName) print(" openModel : ", openResult ) if not openResult: print("openModel is failed. Below is the translation log.") log = dymola.getLastErrorLog() print(log) exit(1) dymola.experimentSetupOutput(events=False) result = dymola.simulateExtendedModel(self.modelName,0.0, self.simTime, 0, self.deltaTime, "Radau", 0.00001, self.deltaTime, self.resultName, initialNames=self.handleModelParamName, initialValues=self.handleModelParamVal) print(" simulateExtendedModel : ", result[0]) if not result[0]: print("Simulation is failed. Below is the translation log.") log = dymola.getLastErrorLog() print(log) exit(1) except DymolaException as ex: print(("Error: " + str(ex))) finally: if dymola is not None: dymola.close() dymola = None return 0
def simulation(paths, models, times, A, t, htc, modelon, lcl, dir_save): modelon = modelon lcl = lcl A = A t = t htc = htc dir_save = dir_save for pat, model, time in zip(paths, models, times): dymola = None try: # Instantiate the Dymola interface and start Dymola dymola = DymolaInterface() # Loading libs dymola.openModel(path=modelon) dymola.openModel(path=lcl) # Load model dymola.openModel(path=pat) dymola.translateModel(model) # Call a function in Dymola and check its return value result = dymola.simulateExtendedModel( problem=model, startTime=0, stopTime=time, outputInterval=0.5, method="Esdirk45a", initialNames=["A", "T", "htc"], initialValues=[A, t, htc], resultFile=dir_save + "\\" + model) # result = dymola.simulateModel("C_Two_M_and_I", startTime=0, stopTime=t_stop, resultFile=dir_path + "_result") if not result: print("Simulation failed. Below is the translation log.") log = dymola.getLastErrorLog() print(log) # dymola.plot(["MotorStator.T", "Inverter_Al.T"], legends=['T_motor', 'T_inverter']) # dymola.ExportPlotAsImage(r'C:\Users\sanjio.durasevic\Desktop\C2\12_11_2018_Motor_Inverter_script\plots\slika.png') except DymolaException as ex: print("Error: " + str(ex)) finally: if dymola is not None: dymola.close() dymola = None
def createDymosimExe(modelPath, stopTime): dymola = None try: dymola = DymolaInterface() result = dymola.simulateExtendedModel(modelPath, 0.0, stopTime, 0, 0.0, "Dassl", 0.0001, 0.0, None, None, None, ["Result"], True) print(result) if not result[0]: print("Simulation failed. Below is the translation log.") log = dymola.getLastErrorLog() print(log) except DymolaException as ex: print(("Error: " + str(ex))) finally: if dymola is not None: dymola.close() dymola = None
def translate(self): try: dymola = None dymola = DymolaInterface("C:/Program Files/Dymola 2019 FD01/bin64/Dymola.exe") openResult = dymola.openModel(self.packageName) print(" openModel : ", openResult ) if not openResult: print("Model open failed. Below is the translation log.") log = dymola.getLastErrorLog() print(log) exit(1) transResult = dymola.translateModelExport(self.modelName) print(" translateModel : ", transResult) except DymolaException as ex: print(("Error: " + str(ex))) finally: if dymola is not None: dymola.close() dymola = None return 0
# 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 variables = ['Time', machines['delta'][machineNumber], machines['pelec'][machineNumber], machines['speed'][machineNumber], 'GEN1.V', 'LOAD.V', 'GEN2.V', 'FAULT.V' ] df_variables = pd.DataFrame([], columns = variables) for var in variables: df_variables.drop(var, axis = 1, inplace = True) df_variables[var] = np.array(sim[var].values()) print(f"{machineName} Variables OK...") #Changing current directory os.chdir(f"/home/manuelnvro/dev/Gitted/PythonTesting/WorkingDir/Dymola/Machines/{machineName}/")
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
def simulate(simSettings, showWindow=False, closeWindow=True, simID='', seed=0, singleTranslate=True): ''' simSettings => dictionary of setting parameters (see below for details) showWindow => =True to launch Dymola GUI closeWindow => =False to prevent auto-closing of the Dymola GUI when done simID => simulation ID to differentiate output files (e.g., simID_dsres0.mat vs. dsres0.mat) seed => starting seed value for output file naming (e.g., seed+0, ..., seed+len(experiments)) singleTranslate => =True to only translate the model once - !!! If variables needed to be changed require retranslation then add them to problem name. i.e., simSettings['problem']=['Example.Test(var1=1,var2=5)'] or try to set 'annotation(Evaluate=false)' in the model simSettings details: - All settings, besides `=None`, must be enclosed in brackets [] - !!! 'initialNames' and 'initialValues' are set different than others. Specify each variable indepenently. The script will generate the tests and collapse all 'non-standard' keys. - 'problem', 'resultFile', and 'autoLoad' only support 1 or None entries - Only specify 'numberOfIntervals' or 'outputInterval', not both - 'fixedstepsize' is only for fixed step size solvers - showWindow=True and closeWindow=False only a specified number of simulations are retained in memory according, not all simulations. - The experiments generated are a list of dictionaries which are saved as experiments.pickle in the working directory of the Modelica simulation (cwdMOD). To open the pickle in python: with open(os.path.join('PATHTOPICKLE,'experiments.pickle'), 'rb') as handle: experiments = pickle.load(handle) - !!! Settings not specified assume Dymola default settings. Any simulation settings (tolerance, solver, etc.) located in the model are ignored. Default Settings: 'problem' = '' => Modelica file (.mo) to be run (e.g., ['TRANSFORM.Fluid.Examples.RankineCycl'] ) 'startTime' = 0 => Start time of simulation 'stopTime' = 1 => Stop time of simulation 'numberOfIntervals' = 500 => Number of intervals to be saved to result file 'outputInterval' = 0 => Time (seconds) between intervals to be saved to result file 'method' = 'dassl' => Solver 'tolerance' = 0.0001 => Solver tolerance 'fixedstepsize' = 0 => Step size for solver (certain solvers only, e.g., Euler) 'resultFile' = 'dsres.mat' => Name of the result file 'initialNames' = '' => Names of variables in model 'initialValues' = '' => Value of variables in model (len(initialNames) = len(initialValues)) 'finalNames' = '' => Variable for Dymola to print to screen when simulation is finished 'autoLoad' = true => Automatically load (true) the result file into the Dymola plot window Possible Methods: 'methods' = Lsodar, dassl, Euler, Rkfix2, Rkfix3, Rkfix4, Esdirk23a, Esdirk34a, Esdirk45a, Dopri45, Dopri853, Sdirk34hw, Cerk23, Cerk34, Cerk34, Cvode For the current supported solvers and their use see Dymola ''' # Check User Input checkInput(simSettings) try: if int(seed) >= 0: seed = int(seed) else: raise NameError("seedNum must be a positive integer") except: raise NameError("seedNum must be a positive integer") # Modify simID for naminc conventions if simID != '': simID = simID + '_' # Generate all experiment permutations experimentsRaw = genExperimentsRaw(simSettings) # Filter experiments to generate key/value pairs for 'initialNames' and 'initialValues' experiments = genExperiments(experimentsRaw) # Instantiate the Dymola interface and start Dymola dymola = None result_tran = False try: # Open Dymola dymola = DymolaInterface(showwindow=showWindow) # Get working directory cwdMod = dymola.ExecuteCommand( 'Modelica.Utilities.System.getWorkDirectory();') # Translate the model if singleTranslate: result_tran = dymola.translateModel(experiments[0]['problem']) if not result_tran: raise Exception( "Translation failed. Aborting parametric simulation. Investigate model in IDE for details." ) # Run all experiments saveResult = [] j = seed print('Total experiments = {} for simID = "{}"'.format( len(experiments), simID)) print('Experiment numbering started at seed = {}'.format(seed)) for i, value in enumerate(experiments): j = seed + i print('Experiment {} (= {}/{})'.format(j, i + 1, len(experiments))) print(value) # ModelTranslate = "Dymola.Path.To.Your.Model(Dymola.Path.to.Variable=1000)" if not singleTranslate: result_tran = False result_tran = dymola.translateModel(value['problem']) if not result_tran: print( "Translation failed. Aborting parametric simulation. Investigate model in IDE for details." ) break # Simulate the model result = dymola.simulateExtendedModel(**value)[0] # Save the result (success/fail) saveResult.append(result) # Rename the log files and return new log file for debugging ref. dslogNew = renameFiles(simID, j, value, cwdMod, result) # Print last line of error if not result: print( "Simulation failed. Below is the translation log. For more details see: {}" .format(dslogNew)) log = dymola.getLastErrorLog() print('### Log Start ###\n' + log + '### Log End ###') except DymolaException as ex: print(("Error: " + str(ex))) except Exception as inst: print('{}'.format(inst.message)) finally: if dymola is not None: if showWindow == True and closeWindow == False: pass else: dymola.close() if result_tran: # Save experiment dictionary as pickle in cwdMod with open( os.path.join( cwdMod, '{}experiments_{}to{}.pickle'.format(simID, seed, j)), 'wb') as handle: pickle.dump(experiments, handle, protocol=pickle.HIGHEST_PROTOCOL) # Save summary off success/fail (true/false) of simulations with open( os.path.join(cwdMod, '{}summary_{}to{}.txt'.format(simID, seed, j)), 'w') as fil: fil.write('Summary of success/fail (true/false) of experiments\n') for i, val in enumerate(saveResult): fil.write('\t'.join( ['Experiment', '{}'.format(i), '{}'.format(val)]) + '\n')
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()