Package: pydelica
PyDelica: Serverless OpenModelica with PythonAboutPyDelica is an API providing a quick and easy to use interface to compile, customise and run OpenModelica models with Python. Unlike OMPython it does not require the launch of a server session to use OMShell but rather dynamically adjusts files produced after model compilation in order to update options and parameters. The lack of server requirement means models can be run in tandem without calling multiple OMC sessions which can be very taxing on CPU. Furthermore PyDelica is able to detect errors during model runs by reading thestderrandstdoutfrom OpenModelica and throw appropriate exceptions to terminate the program execution.InstallationTo use PyDelica you will require an installation of OpenModelica on your system, the API has been confirmed to work on both Windows and Linux, but if OM is installable on macOS it should also be possible to still use it.To install run:pipinstallpydelicaGetting StartedFor the purposes of demonstration the included test modeltests/models/SineCurrent.mowill be used.PyDelica SessionAll uses of PyDelica require an instance of theSessionclass:frompydelicaimportSessionwithSession()assession:...It is strongly recommended that this class be used via the context manager to ensure cleanup of temporary directories.LoggingTheSessionclass has one optional argument which is used to set the log level output within OpenModelica itself. The options are based on the-lvflag within OM. By default the level is set toNormalwhich means no log level output.As an example if you wanted to run with statistics logging-lv=LOG_STATSyou would setup with the following:frompydelicaimportSessionfrompydelica.loggerimportOMLogLevelwithSession(log_level=OMLogLevel.STATS)assession:...See the source for more optionshere.Building/Compiling ModelsBefore you can run a model you must first compile it. This is done using thebuild_modelmember function which takes the path to the Modelica source file.model_path=os.path.join('tests','models','SineCurrent.mo')session.build_model(model_path)If the required model is not top level, that is to say it exists within a module or , we can optionally specify the address within Modelica. This is also required if the required model is not the default. For example say modelAexisted within moduleM:model_path='FictionalModelFile.mo'session.build_model(model_path,'M.A')Thebuild_modelfunction also allows you to specify additional flags/options to hand to the OMC compiler, these are given
in the form of a dictionary where the value can beNoneif the flag does not take any input. You can also directly set the profiling level for profiling the Modelica code. When set, the profile dictionary is also stored in the session after the simulation and is accessible via thecode_profileandcode_infoattributes:session.build_model(model_path,'M.A',profiling="all",omc_build_flags={"-g":"MetaModelica"})session.simulate()print(session.code_profile)print(session.code_info)Examining Parameters and OptionsWe can examine all parameters for a given model using theget_parametersmethod which will return a Python dictionary:session.get_parameters('SineCurrentModel')if the parameter is unique to a single model then the model name argument can be dropped. Returning the value for a single parameter is as simple as:session.get_parameter(<parameter-name>)For simulation options the analogous methods areget_simulation_optionsandget_simulation_optionrespectively for general case, for more specific see below.Setting Parameters and OptionsSet a parameter to a different value using theset_parameterfunction:session.set_parameter(<parameter-name>,<new-value>)Further ConfigurationThe output file type can be specified:frompydelica.optionsimportOutputFormatsession.set_output_format(OutputFormat.CSV)# Other options are MAT and PLTSet the solver:frompydelica.optionsimportSolversession.set_solver(Solver.DASSL)# Other options are EULER and RUNGE_KUTTASet the time range:# Each argument is optionalsession.set_time_range(start_time=0,stop_time=10,model_name='SineCurrentModel')Set tolerance:# Model name is optionalsession.set_tolerance(tolerance=1E-9,model_name='SineCurrentModel')Set variable filter for outputs:# Model name is optionalsession.set_variable_filter(filter_str='output*',model_name='SineCurrentModel')Failing Simulation on Lower Assertion LevelBy default PyDelica will look for the expressionassert | erroras an indication of a Modelica assertion
failure and then terminate when this is violated. You can override this behaviour using thefail_on_assert_levelmethod of theSessionclass:frompydelicaimportSessionwithSession()aspd_session:pd_session.fail_on_assert_level('warning')Possible values ranked by order (highest at the top):ValueDescription'never'Do not throw an exception on Modelica assertion violation'error'Default. Throw an exception on an assertion of levelAssertionLevel.error'warning'Throw an exception on assertion of levelAssertionLevel.warning'info'Throw an exception on any `assert'debug'Throw an exception on any `assertRunning the SimulationTo run the simulation use thesimulatemethod. If a model name is specified then that model is run,
else this is the first model in the model list. At the simulation step parameter values are written to the
XML file read by the binary before the model binary is executed.# Model name is optional, verbosity is also optional and overwrites that of the sessionsession.simulate(model_name='SineCurrentModel',verbosity=OMLogLevel.DEBUG)Retrieving ResultsTo view the results use theget_solutionsmethod which will return a python dictionary containing
the solutions for all models after a model run:solutions=session.get_solutions()The variables for each model are stored as a Pandas dataframe.Using Alternative LibrariesNOTE:Currently only works in WSL on Windows machines.You can use an alternative library version via theuse_librarymethod:session.use_library("Modelica","3.2.3")you can also optionally specify the location of this library:session.use_library("Modelica","3.2.3",library_directory="/home/user/my_om_libraries")TroubleshootingSimulation fails with no error thrownTry setting the assertion level to a lower level, for some reason OM ranks missing input file errors
as typedebug, seehere.stdout | info | ... loading "data" from "Default/myInput.mat"
assert | debug | Not possible to open file "Default/myInput.mat": No such file or directory
assert | info | simulation terminated by an assertion at initializationPyDelica cannot find OMCPyDelica relies on either locating OMC on UNIX using thewhichcommand, or in the case of Windows using theOPENMODELICAHOMEenvironment variable. Ensure at least one of these is available after installating OpenModelica.