def __init__(self, library, wh_lib): self.library = library self.wh_lib = wh_lib self.wh_lib_path = self.wh_lib + os.sep + self.wh_lib + os.sep + "package.mo" sys.path.append('bin/CITests') from _config import ch_file, wh_file, exit_file self.ch_file = ch_file self.wh_file = wh_file self.exit_file = exit_file self.CRED = '\033[91m' # Colors self.CEND = '\033[0m' self.green = '\033[0;32m' from dymola.dymola_interface import DymolaInterface # Load modelica python interface from dymola.dymola_exception import DymolaException print(f'1: Starting Dymola instance') if platform.system() == "Windows": dymola = DymolaInterface() else: dymola = DymolaInterface(dymolapath="/usr/local/bin/dymola") self.dymola = dymola self.dymola_exception = DymolaException() self.dymola.ExecuteCommand( "Advanced.TranslationInCommandLog:=true;" ) # ## Writes all information in the log file, not only the
def __init__(self, package, library, dymolaversion, changed_models): self.package = package self.library = library self.dymolaversion = dymolaversion self.changed_models = changed_models sys.path.append('bin/CITests') from _config import exit_file, html_wh_file, ch_file self.exit_file = exit_file self.html_wh_file = html_wh_file self.ch_file = ch_file self.CRED = '\033[91m' # Colors self.CEND = '\033[0m' self.green = "\033[0;32m" from dymola.dymola_interface import DymolaInterface # Load modelica python interface from dymola.dymola_exception import DymolaException print(f'1: Starting Dymola instance') if platform.system() == "Windows": dymola = DymolaInterface() else: dymola = DymolaInterface(dymolapath="/usr/local/bin/dymola") self.dymola = dymola self.dymola_exception = DymolaException() self.dymola.ExecuteCommand( "Advanced.TranslationInCommandLog:=true;") # Writes all information in the log file, not only the
def __init__(self, package, n_pro, show_gui, simulate_examples, ch_models, mo_library, wh_library, filter_wh): self.package = package self.mo_library = mo_library self.lib_path = self.mo_library + os.sep + "package.mo" self.root_package = self.mo_library + os.sep + self.package self.n_pro = n_pro self.show_gui = show_gui self.simulate_ex = simulate_examples self.ch_models = ch_models self.wh_library = wh_library self.filter_wh = filter_wh sys.path.append('bin/CITests') from _config import ch_file, wh_file self.ch_file = ch_file self.wh_file = wh_file self.err_log = f'{self.mo_library}{os.sep}{self.mo_library}.{self.package}-errorlog.txt' self.CRED = '\033[91m' # Colors self.CEND = '\033[0m' self.green = "\033[0;32m" from dymola.dymola_interface import DymolaInterface # Load modelica python interface from dymola.dymola_exception import DymolaException print(f'1: Starting Dymola instance') if platform.system() == "Windows": dymola = DymolaInterface() else: dymola = DymolaInterface(dymolapath="/usr/local/bin/dymola") self.dymola = dymola self.dymola_exception = DymolaException() self.dymola.ExecuteCommand( "Advanced.TranslationInCommandLog:=true;" ) # Writes all information in the log file, not only the
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 kennfeld_simulieren(mp, Root_simulationsergebnisse, model_kennfeld_path, model_kennfeld_name): dymola = None try: #erzeuge Instanz von Dymola dymola = DymolaInterface() print(model_kennfeld_path, model_kennfeld_name) #öffne das Model dymola.openModel(path=model_kennfeld_path) dymola.translateModel(problem=model_kennfeld_name) print('simulieren') result = dymola.simulateExtendedModel( problem=model_kennfeld_name, stopTime=200000, method='radau IIa', resultFile=Root_simulationsergebnisse + '\simulationsergebnis_mp' + str(mp)) print(result[0]) if not result: print("Simulation failed. Below is the translation log.") log = dymola.getLastError() print(log) except DymolaException as ex: print("Error: " + str(ex)) if dymola is not None: dymola.close() dymola = None return
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 setUpClass(cls): cls.project_dir, _ = os.path.split(__file__) temp_dir = os.path.join(cls.project_dir, 'Temp') # clean up if os.path.isdir(temp_dir): shutil.rmtree(temp_dir) # extract the distribution file with zipfile.ZipFile("Modelica-Arduino.zip", "r") as zip_ref: zip_ref.extractall("Temp") package_file = os.path.join(temp_dir, 'Arduino', 'package.mo') print("Starting Dymola") cls.dymola = DymolaInterface(showwindow=False) cmd = 'openModel("{}")'.format(package_file) print("Loading Arduino library") cls.dymola.ExecuteCommand(cmd) print("Setting Compiler") cls.dymola.ExecuteCommand( 'SetDymolaCompiler("vs", {"CCompiler=MSVC","MSVCDir=C:/Program Files (x86)/Microsoft Visual Studio 14.0/Vc"});' )
def _Advanced(): from dymola.dymola_interface import DymolaInterface from dymola.dymola_exception import DymolaException dymola = DymolaInterface() dymola.Execute( r"N:\Forschung\EBC0387_Vaillant_Low_GWP_HP_study_GES\Students\cve-shi\02_Hiwi\05_GIT\Dymola\GitLabCI\bin\CITests\UnitTests\CheckPackages\CheckModelTests.mos" )
def __init__(self, package, library, dymolaversion, path): self.package = package self.library = library self.dymolaversion = dymolaversion self.path = path sys.path.append('../bin/CITests') from _config import ch_file, resource_dir self.changed_file = f'..{os.sep}{ch_file}' self.resource_file_path = f'{resource_dir}{os.sep}{self.package.replace(self.library + ".", "")}' self.package_path = f'{self.package}' self.CRED = '\033[91m' # Color self.CEND = '\033[0m' self.green = "\033[0;32m" if self.package is None: print( f'{self.CRED}Error:{self.CEND} Package is missing! (e.g. Airflow)' ) exit(1) if self.library is None: print( f'{self.CRED}Error:{self.CEND} Library is missing! (e.g. AixLib)' ) exit(1) from dymola.dymola_interface import DymolaInterface from dymola.dymola_exception import DymolaException print(f'1: Starting Dymola instance') if platform.system() == "Windows": dymola = DymolaInterface() else: dymola = DymolaInterface(dymolapath="/usr/local/bin/dymola") self.dymola = dymola self.dymola_exception = DymolaException() self.dymola.ExecuteCommand("Advanced.TranslationInCommandLog:=true;") librarycheck = self.dymola.openModel(self.path) if librarycheck == True: print(f'Found {self.library} Library. Start regression test.') elif librarycheck == False: print( f'Library Path is wrong. Please Check Path of {self.library} Library Path' ) exit(1) self.dymola.ExecuteCommand("Advanced.TranslationInCommandLog:=true;")
def simulate_optimal(ladephasen, entladephasen, simulationsdauer, dir_laden_daten, dir_modell_sim, name_modell_sim, Root_simulationsergebnisse): ladephasen = clear_phasen(ladephasen) entladephasen = clear_phasen(entladephasen) input_laden = merge(ladephasen, dir_laden_daten) input_entladen = merge(entladephasen, dir_laden_daten) try: #erzeuge Instanz von Dymola dymola = DymolaInterface() dymola.openModel(path=dir_modell_sim) dymola.translateModel(problem=name_modell_sim) dymola.ExecuteCommand("laden.table=" + input_laden) dymola.ExecuteCommand("entladen.table=" + input_entladen) result = dymola.simulateExtendedModel(problem=name_modell_sim, stopTime=simulationsdauer * 3600, method='radau IIa', finalNames=['Stromkosten.y'], resultFile=os.path.join( Root_simulationsergebnisse, 'simulation_optimal')) print(result[0]) Stromkosten = result[1] print('optimale Stromkosten', Stromkosten[0]) if not result: print("Simulation failed. Below is the translation log.") log = dymola.getLastError() print(log) dymola.plot(["elektrische_leistungsaufnahme.y"]) dymola.ExportPlotAsImage( os.path.join(Root_simulationsergebnisse, "Leistungsaufnahme_optimal.png")) dymola.plot(["__ctt__strompreis.y[1]"]) dymola.ExportPlotAsImage( os.path.join(Root_simulationsergebnisse, "Strompreis.png")) dymola.plot(["cost_calculation1.out_kkm1_drehzahl_min_unterschritten"]) dymola.ExportPlotAsImage( os.path.join(Root_simulationsergebnisse, "Drehzahl_unterschritten.png")) dymola.plot(["cost_calculation1.out_Investitionskosten_kkm1"]) dymola.ExportPlotAsImage( os.path.join(Root_simulationsergebnisse, "Invest_KKM.png")) dymola.plot(["cost_calculation1.out_Investitionskosten_Speicher"]) dymola.ExportPlotAsImage( os.path.join(Root_simulationsergebnisse, "Invest_Speicher.png")) except DymolaException as ex: print("Error: " + str(ex)) if dymola is not None: dymola.close() dymola = None return input_laden, input_entladen, ladephasen, entladephasen
def dym_check_lic(): from dymola.dymola_interface import DymolaInterface from dymola.dymola_exception import DymolaException if platform.system() == "Windows": dymola = DymolaInterface() else: dymola = DymolaInterface(dymolapath="/usr/local/bin/dymola") dymola.ExecuteCommand("Advanced.TranslationInCommandLog:=true;") dym_sta_lic_available = dymola.ExecuteCommand('RequestOption("Standard");') if not dym_sta_lic_available: dymola.ExecuteCommand( 'DymolaCommands.System.savelog("Log_NO_DYM_STANDARD_LIC_AVAILABLE.txt");' ) print("No Dymola License is available") dymola.close() else: print("Dymola License is available")
def _CreateIBPSALog(self): from dymola.dymola_interface import DymolaInterface from dymola.dymola_exception import DymolaException import buildingspy.development.regressiontest as u """ Check the IBPSA Model Automatical """ cmd = "git clone https://github.com/ibpsa/modelica-ibpsa.git" returned_value = os.system(cmd) # returns the exit code in unix print('returned value:', returned_value) cmd = "cd modelica-ibpsa-master" os.system(cmd) Library = IBPSA/package.mo ut = u.Tester(tool = self.tool) ### Set Number of Threads ut.setNumberOfThreads(self.n_pro) ### Set GUI Show ut.showGUI(self.show_gui) ### Set in Batch Mode ut.batchMode(self.batch) ### Sets the Dymola path to activate the GUI dymola = DymolaInterface(dymolapath="/usr/local/bin/dymola") ### Writes all information in the log file, not only the last entries dymola.ExecuteCommand("Advanced.TranslationInCommandLog:=true;") dym_sta_lic_available = dymola.ExecuteCommand('RequestOption("Standard");') if not dym_sta_lic_available: dymola.ExecuteCommand('DymolaCommands.System.savelog("Log_NO_DYM_STANDARD_LIC_AVAILABLE.txt");') print("No Dymola License is available") dymola.close() exit(1) else: print("Dymola License is available") PackageCheck = dymola.openModel(Library) if PackageCheck == True: print("Found AixLib Library and start Checkmodel Tests \n Check Package " + self.Package+" \n") elif PackageCheck == None: print("Library Path is wrong. Please Check Path of AixLib Library Path") exit(1) result=dymola.checkModel(self.Package) dymola.savelog(self.Package+"-log.txt") Log = dymola.getLastError() if result == True: print('\n Check of Package '+self.Package+' was Successful! \n') dymola.close() #exit(0) if result == False: print('\n ModelCheck Failed in Package ' + self.Package+ ' Show Savelog \n') print(Log) dymola.clearlog() dymola.close()
def results_to_csv(res_path): """ This function loads the mat file and save it to csv. It loads the dymola result mat file and saves the indoor air temp of the two modelled zones and the total heating power in W. """ res_all = pd.DataFrame() signals = [ 'Time', 'multizone.PHeater[1]', 'multizone.PHeater[2]', 'multizone.TAir[1]', 'multizone.TAir[2]' ] dymola = DymolaInterface() print('Reading signals: ', signals) dym_res = dymola.readTrajectory( fileName=res_path, signals=signals, rows=dymola.readTrajectorySize(fileName=res_path)) results = pd.DataFrame().from_records(dym_res).T results = results.rename( columns=dict(zip(results.columns.values, signals))) results.index = results['Time'] results["AixLib_Heating_Power_W"] = results["multizone.PHeater[1]"] +\ results["multizone.PHeater[1]"] # drop Time and single zones columns results = results.drop( ['Time', 'multizone.PHeater[1]', 'multizone.PHeater[2]'], axis=1) results = results.rename(index=str, columns={ "multizone.TAir[1]": "AixLib_T_dayzone", "multizone.TAir[2]": "AixLib_T_nightzone" }) # results = results.drop(index_to_drop) # results = results.groupby(level=0).first() # results.to_csv(path=res_path, delimiter=';') dymola.close() res_csv = os.path.join(os.path.dirname(os.path.abspath(__file__)), "AixLib_SingleBuilding.csv") results.to_csv(res_csv) return results
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 __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 Initialize_Simulation(Path, Show=False): """ Initializes the simulation via dymola. Inputs: Path : String, relative path to model Show : Boolean, Optional. Shows Dymola Window if True. Default is False Returns: Model_Instance : Instance of the model in the dymola interface. """ Model_Instance = DymolaInterface(use64bit=True, showwindow=Show) Model_Instance.openModel(path=Path) return Model_Instance
def _Test(): # Import dymola package from dymola.dymola_interface import DymolaInterface from dymola.dymola_exception import DymolaException dymola = None #dymola.dymola_interface.DymolaInterface(dymolapath="", port=-1, showwindow=True, debug=False, allowremote=False, nolibraryscripts=False) try: dymola = DymolaInterface(showwindow=True) dymola.simulateModel( "Modelica.Mechanics.Rotational.Examples.CoupledClutches") print("Simulate") except DymolaException as ex: print("Error")
def __EnsureDymolaIsOpen(this): if (not Dymola2.__dymolaIsOpen): import sys sys.path.append( r'C:\Program Files\Dymola 2018 FD01\Modelica\Library\python_interface\dymola.egg' ) from dymola.dymola_interface import DymolaInterface from PySimLib import Platform Dymola2.__interface = DymolaInterface() print('Dymola-Interface opened') Dymola2.__dymolaIsOpen = True #Platform.Execute([GetConfigValue("Dymola2", "PathExe")], False) Dymola2.__interface.ExecuteCommand("OutputCPUtime:=true;") else: print('Dymola is still open')
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
def make_dymola(cls): import sys import os if cls.dymola == None: # Work-around for the environment variable sys.path.insert(0, os.path.join(cls.dym_path)) # Import Dymola Package print(cls.dym_path) global dymola from dymola.dymola_interface import DymolaInterface # Start the interface cls.dymola = DymolaInterface() for i, path in enumerate(cls.lib_paths): print(path) check = cls.dymola.openModel(os.path.join(path, 'package.mo')) print('Opening successful ' + str(check))
def simulate(): dir_aixlib = r"D:\Sciebo\Programmierung\GIT\_Standard\AixLib\AixLib" dir_result = r"D:\Sciebo\Programmierung\Tests\Dymola" dymola = DymolaInterface() try: dymola.openModel(path=os.path.join(dir_aixlib, 'package.mo')) # dymola.openModel(r"D:\Sciebo\Programmierung\Tests\Dymola\Test_BUDO.mo") dymola.translateModel( 'AixLib.Fluid.BoilerCHP.Examples.Test_BUDO.CompleteModel') output = dymola.simulateExtendedModel( problem='AixLib.Fluid.BoilerCHP.Examples.Test_BUDO.CompleteModel', startTime=0.0, stopTime=86400, outputInterval=500, method="Dassl", tolerance=0.0001, resultFile=os.path.join(dir_result, 'demo_results'), finalNames=['boiler_system.temperature_sensor_2.T'], ) print(output[1]) error = dymola.getLastError() print(error) # dymola.plot( # ["boiler_system.temperature_sensor_2.T", "combiTimeTable.y[3]"]) # dymola.ExportPlotAsImage(os.path.join(dir_result, "plot.png")) # list_var = dymola.list( # r"D:\Sciebo\Programmierung\Tests\Dymola\Test_BUDO.txt", variables='*"H02.1"*') # print(list_var) # list_var = dymola.variables( # r"D:\Sciebo\Programmierung\Tests\Dymola\Test_BUDO.txt") # print(list_var) # list_var = dymola.getExperiment() # print(list_var) # list_var = dymola.listfunctions(filter="*") # print(list_var) dymola.exit() except: print("Unexpected error:", sys.exc_info()) dymola.exit()
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 simulate_compare(simulationsdauer, dir_modell_sim, name_modell_sim, Root_simulationsergebnisse): try: #erzeuge Instanz von Dymola dymola = DymolaInterface() dymola.openModel(path=dir_modell_sim) dymola.translateModel(problem=name_modell_sim) result = dymola.simulateExtendedModel(problem=name_modell_sim, stopTime=simulationsdauer * 3600, method='radau IIa', finalNames=['Stromkosten.y'], resultFile=os.path.join( Root_simulationsergebnisse, 'simulation_optimal')) print(result[0]) Stromkosten = result[1] #ergebnis[step-1,1]=Stromkosten[0]☺ print('Vergleichs-Stromkosten', Stromkosten[0]) if not result: print("Simulation failed. Below is the translation log.") log = dymola.getLastError() print(log) dymola.plot(["elektrische_leistungsaufnahme.y"]) dymola.ExportPlotAsImage( os.path.join(Root_simulationsergebnisse, "vergleichs_ergebnis.png")) except DymolaException as ex: print("Error: " + str(ex)) if dymola is not None: dymola.close() dymola = None return Stromkosten
def _python_Interface(): from dymola.dymola_interface import DymolaInterface from dymola.dymola_exception import DymolaException dymola = DymolaInterface(showwindow=True) dymola.openModel("D:/Gitlab/GitLabCI/AixLib/package.mo") result = dymola.checkModel( "AixLib.Fluid.Actuators.Valves.ExpansionValves.SimpleExpansionValves.IsenthalpicExpansionValve" ) print(result) Log = dymola.getLastError() print(Log) #Errorlog = dymola.getLastErrorLog() #print(Errorlog) dymola.savelog("Fluid-log.txt") dymola.close() if result == True: print('\n Check was Successful! \n') exit(0) if result == False: print('\n Error: Look in Savelog \n') exit(1)
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 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
import pandas as pd import numpy as np import os # In[198]: #This is intended to be used in the manuelnvro Dell using Dymola 2020 # In[3]: #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 Machines Simulation Start...\n") # In[4]: #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']}
def simulate_flex(model_name, model_path, sim_duration, flex_var, param_dict): dymola = DymolaInterface() #Model muss noch geöffnet sein openModel = dymola.openModel(path=model_path) print(openModel) translateModel = dymola.translateModel(problem=model_name) print(translateModel) if flex_var == 1: #erste Ebene dymola.ExecuteCommand("konf_Bivalenz=true") dymola.ExecuteCommand("konf_HK=true") dymola.ExecuteCommand("konf_BHKW_stromgefuehrt=false") #zweite Ebene dymola.ExecuteCommand(str("konf_BHKW=" + param_dict["konf_BHKW"])) dymola.ExecuteCommand(str("konf_WRG=" + param_dict["konf_WRG"])) dymola.ExecuteCommand(str("konf_Puffer=" + param_dict["konf_Puffer"])) dymola.ExecuteCommand(str("Anzahl_HK=" + param_dict["Anzahl_HK"])) #die if-Bedingung ist nur zur Sicherheit if param_dict["konf_WRG"] == "true": dymola.ExecuteCommand(str("Anzahl_WRG=" + param_dict["Anzahl_WRG"])) else: dymola.ExecuteCommand("Anzahl_WRG=0") elif flex_var == 2: #erste Ebene dymola.ExecuteCommand("konf_BHKW=true") dymola.ExecuteCommand("konf_Bivalenz=false") dymola.ExecuteCommand("konf_BHKW_Puffer=true") dymola.ExecuteCommand("konf_BHKW_stromgefuehrt=true") #zweite Ebene dymola.ExecuteCommand(str("konf_HK=" + param_dict["konf_HK"])) dymola.ExecuteCommand(str("konf_WRG=" + param_dict["konf_WRG"])) #die if-Bedingung ist nur zur Sicherheit if param_dict["konf_HK"] == "true": dymola.ExecuteCommand(str("Anzahl_HK=" + param_dict["Anzahl_HK"])) else: dymola.ExecuteCommand("Anzahl_HK=0") #die if-Bedingung ist nur zur Sicherheit if param_dict["konf_WRG"] == "true": dymola.ExecuteCommand(str("Anzahl_WRG=" + param_dict["Anzahl_WRG"])) else: dymola.ExecuteCommand("Anzahl_WRG=0") else: print("Auswahl der Flexibilisierungsmaßnahme fehlerhaft") result = dymola.simulateExtendedModel(problem=model_name, stopTime=sim_duration, finalNames=[ "konf_Bivalenz", "konf_HK", "konf_BHKW_stromgefuehrt", "konf_BHKW", "konf_WRG", "konf_Puffer", "Anzahl_WRG", "Anzahl_HK" ]) if not result[0]: print("Simulation failed. Below is the translation log.") log = dymola.getLastError() print(log) print('ERGEBNIS_Inhalt:', "konf_Bivalenz", "konf_HK", "konf_BHKW_stromgefuehrt", "konf_BHKW", "konf_WRG", "konf_Puffer", "Anzahl_WRG", "Anzahl_HK") #saveModel=dymola.saveTotalModel('C:/Users/theisinger_l/waerme_save.mo', "waerme") #Achtung Dymola speichert mit saveTotalModel anscheinend nicht parameterwerte ab.. #print(saveModel) dymola.close() return result
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
import platform from dymola.dymola_interface import DymolaInterface from dymola.dymola_exception import DymolaException osString = platform.system() isWindows = osString.startswith("Win") dymola = None try: # Instantiate the Dymola interface and start Dymola dymola = DymolaInterface() # Call a function in Dymola and check its return value result = dymola.simulateModel("Modelica.Mechanics.Rotational.Examples.CoupledClutches") if not result: print("Simulation failed. Below is the translation log.") log = dymola.getLastErrorLog() print(log) exit(1) dymola.plot(["J1.w", "J2.w", "J3.w", "J4.w"]) if (isWindows): plotPath = "C:/temp/plot.png" else: plotPath = "/tmp/plot.png"; dymola.ExportPlotAsImage(plotPath) print("OK") except DymolaException as ex: print(("Error: " + str(ex))) finally: