Scripting API¶
The following are short summaries of OpenModelica scripting commands. These commands are useful for loading and saving classes, reading and storing data, plotting of results, and various other tasks.
The arguments passed to a scripting function should follow syntactic and typing rules for Modelica and for the scripting function in question. In the following tables we briefly indicate the types or character of the formal parameters to the functions by the following notation:
String typed argument, e.g. "hello", "myfile.mo".
- TypeName - class, package or function name, e.g. MyClass,
Modelica.Math.
VariableName - variable name, e.g.
v1,v2,vars1[2].x, etc.Integer or Real typed argument, e.g. 35, 3.14, xintvariable.
options - optional parameters with named formal parameter passing.
OpenModelica Scripting Commands¶
The following are brief descriptions of the scripting commands available in the OpenModelica environment. See also https://build.openmodelica.org/Documentation/OpenModelica.Scripting.html. All commands are shown in alphabetical order:
interactiveDumpAbsynToJL¶
Dumps the AST into a Julia representation.
impure function interactiveDumpAbsynToJL
output String res;
end interactiveDumpAbsynToJL;
relocateFunctions¶
Update symbols in the running program to ones defined in the given shared object.
Highly experimental, requires OMC be compiled with special flags to use.
This will hot-swap the functions at run-time, enabling a smart build system to do some incremental compilation (as long as the function interfaces are the same).
impure function relocateFunctions
input String fileName;
input String names[:, 2];
output Boolean success;
end relocateFunctions;
GC_expand_hp¶
Forces the GC to expand the heap to accomodate more data.
impure function GC_expand_hp
input Integer size;
output Boolean success;
end GC_expand_hp;
GC_gcollect_and_unmap¶
Forces the GC to collect and unmap memory.
Forces GC to collect and unmap memory (we use it before we start and wait for memory-intensive tasks in child processes).
GC_get_prof_stats¶
Returns a record with the GC statistics.
impure function GC_get_prof_stats
output GC_PROFSTATS gcStats;
end GC_get_prof_stats;
GC_set_max_heap_size¶
Forces the GC to limit the maximum heap size.
impure function GC_set_max_heap_size
input Real size "In bytes; a Real so that sizes past 2^31 fit";
output Boolean success;
end GC_set_max_heap_size;
addClassAnnotation¶
Adds an annotation to a class.
Used to set annotations, like Diagrams and Icons in classes. The function is given the name of the class and the annotation to set.
Usage: addClassAnnotation(Modelica, annotate = Documentation(info = "<html></html>"))
impure function addClassAnnotation
input TypeName class_;
input ExpressionOrModification annotate;
output Boolean bool;
end addClassAnnotation;
addComponent¶
Adds a component to the given class.
impure function addComponent
input TypeName componentName;
input TypeName typeName;
input TypeName classPath;
input Expression binding = $Code(());
input ExpressionOrModification modification = $Code();
input Expression comment = $Code(());
input Expression annotate = $Code(());
output Boolean success;
end addComponent;
addConnection¶
Adds a connection to the given class.
impure function addConnection
input VariableName connector1;
input VariableName connector2;
input TypeName className;
input Expression comment = $Code(());
input Expression annotate = $Code(());
output Boolean success;
end addConnection;
addEquation¶
Adds an equation to a class.
The equation is added to the end of the last equation or initial equation section (depending on
isInitial
) in the class, or to a new section if no suitable section exists. The class must be able to contain equations, i.e. be a normal long class or class extends declaration.
impure function addEquation
input TypeName className "The name of the class to add the equation to";
input String eq "The equation given as a string";
input Boolean isInitial = false "Whether the equation should be added as an initial or normal equation";
output Boolean success "true if the equation could be added, otherwise false";
end addEquation;
addInitialState¶
Adds an initial state to a class.
impure function addInitialState
input TypeName cl;
input String state;
input ExpressionOrModification annotate;
output Boolean bool;
end addInitialState;
addTransition¶
Adds a transition to a class.
impure function addTransition
input TypeName cl;
input String from;
input String to;
input String condition;
input Boolean immediate = true;
input Boolean reset = true;
input Boolean synchronize = false;
input Integer priority = 1;
input ExpressionOrModification annotate;
output Boolean bool;
end addTransition;
alarm¶
Schedules an alarm signal for the process.
Like alarm(2).
Note that OpenModelica also sends SIGALRM to the process group when the alarm is triggered (in order to kill running simulations).
The first signal asks the running command to stop, so that omc survives to report what it completed; a second one a tenth of the time later (at least 5 and at most 60 seconds) terminates omc if the command has no cancellation point to stop at. Re-arming or clearing the alarm withdraws the request.
impure function alarm
input Integer seconds;
output Integer previousSeconds;
end alarm;
appendEnvironmentVar¶
Appends a variable to the environment variables list.
impure function appendEnvironmentVar
input String var;
input String value;
output String result "returns \"error\" if the variable could not be appended";
end appendEnvironmentVar;
basename¶
Returns the base name (file part) of a file path.
Similar to basename(3), but with the safety of Modelica strings.
function basename
input String path;
output String basename;
end basename;
buildAcausalDAE¶
Generates and builds (but does not run) the combined DAE simulation executable for a flowsheet model whose top-level components are acausal DAE blocks. This is the acausal-DAE counterpart of buildModel().
Note that unlike simulateAcausalDAE() this function only builds the combined simulation executable, it does not run it. The acausal-DAE counterpart of buildModel().
Returns the filenames for the generated simulation executable and the initialization file.
The arguments of simulate, buildModel and the other simulation calls.
Only className is necessary. An argument that is not given gets its value from the experiment annotation of the class, or of a class that it extends, or else from the default below. The declared values nan(), -1 and "<default>" only mark an argument that is not given.
Argument |
Value if not given |
|---|---|
|
|
|
|
|
( |
|
Not used. If it is given, numberOfIntervals is (stopTime - startTime) / stepSize, rounded down. |
|
|
|
"dassl". With |
|
The name of the class. The result file is |
|
Not used. |
|
"mat". The other formats are "csv", "plt", "arrow" and "empty", which writes no result file. |
|
".*". Only the variables whose full name matches this regular expression go into the result file. |
|
"". Extra flags for the C compiler. |
|
The |
The flags in simflags apply when the simulation executable runs, and they replace the values above: for example, -s=euler replaces method.
impure function buildAcausalDAE
input TypeName className "The model";
input Real startTime = nan() "Start time";
input Real stopTime = nan() "Stop time";
input Integer numberOfIntervals = -1 "Number of intervals";
input Real stepSize = nan() "Interval of the result file";
input Real tolerance = nan() "Integration tolerance";
input String method = "<default>" "Integration method";
input String fileNamePrefix = "<default>" "File name prefix";
input String options = "<default>" "Not used";
input String outputFormat = "<default>" "Result file format";
input String variableFilter = "<default>" "Variables to store";
input String cflags = "<default>" "Flags for the C compiler";
input String simflags = "<default>" "Flags for the simulation";
output String[2] buildModelResults;
end buildAcausalDAE;
buildEncryptedPackage¶
Builds an encrypted package for a class.
impure function buildEncryptedPackage
input TypeName className "the class that should encrypted";
input Boolean encrypt = true;
output Boolean success;
end buildEncryptedPackage;
buildLabel¶
Calls buildModel with the --generateLabeledSimCode flag enabled.
impure function buildLabel
input TypeName className "the class that should be built";
input Real startTime = 0.0 "the start time of the simulation. <default> = 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Integer numberOfIntervals = 500 "number of intervals in the result file. <default> = 500";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default> = 1e-6";
input String method = "dassl" "integration method used for simulation. <default> = dassl";
input String fileNamePrefix = "" "fileNamePrefix. <default> = \"\"";
input String options = "" "options. <default> = \"\"";
input String outputFormat = "mat" "Format for the result file. <default> = \"mat\"";
input String variableFilter = ".*" "Only variables fully matching the regexp are stored in the result file. <default> = \".*\"";
input String cflags = "" "cflags. <default> = \"\"";
input String simflags = "" "simflags. <default> = \"\"";
output String[2] buildModelResults;
end buildLabel;
buildModel¶
Translates a Modelica model into C code and builds a simulation executable.
Note that unlike simulate() this function only builds a simulation executable, it does not run it.
Returns the filenames for the generated simulation executable and the initialization file.
buildModel(className, [startTime], [stopTime], [numberOfIntervals], [stepSize], [tolerance], [method], [fileNamePrefix], [options], [outputFormat], [variableFilter], [cflags], [simflags])
Example command:
buildModel(A);
The arguments of simulate, buildModel and the other simulation calls.
Only className is necessary. An argument that is not given gets its value from the experiment annotation of the class, or of a class that it extends, or else from the default below. The declared values nan(), -1 and "<default>" only mark an argument that is not given.
Argument |
Value if not given |
|---|---|
|
|
|
|
|
( |
|
Not used. If it is given, numberOfIntervals is (stopTime - startTime) / stepSize, rounded down. |
|
|
|
"dassl". With |
|
The name of the class. The result file is |
|
Not used. |
|
"mat". The other formats are "csv", "plt", "arrow" and "empty", which writes no result file. |
|
".*". Only the variables whose full name matches this regular expression go into the result file. |
|
"". Extra flags for the C compiler. |
|
The |
The flags in simflags apply when the simulation executable runs, and they replace the values above: for example, -s=euler replaces method.
impure function buildModel
input TypeName className "The model";
input Real startTime = nan() "Start time";
input Real stopTime = nan() "Stop time";
input Integer numberOfIntervals = -1 "Number of intervals";
input Real stepSize = nan() "Interval of the result file";
input Real tolerance = nan() "Integration tolerance";
input String method = "<default>" "Integration method";
input String fileNamePrefix = "<default>" "File name prefix";
input String options = "<default>" "Not used";
input String outputFormat = "<default>" "Result file format";
input String variableFilter = "<default>" "Variables to store";
input String cflags = "<default>" "Flags for the C compiler";
input String simflags = "<default>" "Flags for the simulation";
output String[2] buildModelResults;
end buildModel;
buildModelFMU¶
Translates a Modelica model into a Functional Mockup Unit.
The only required argument is the className, while all others have some default values.
Example command:
buildModelFMU(className, version="2.0");
impure function buildModelFMU
input TypeName className "the class that should translated";
input String version = "2.0" "FMU version, 2.0 or 3.0 (1.0 is deprecated).";
input String fmuType = "me" "FMU type, me (model exchange), cs (co-simulation), me_cs (both model exchange and co-simulation)";
input String fileNamePrefix = "<default>" "fileNamePrefix. <default> = \"className\"";
input String platforms[:] = {"static"} "The list of platforms to generate code for.
\"dynamic\"=current platform, dynamically link the runtime.
\"static\"=current platform, statically link everything.
\"<cpu>-<vendor>-<os>\", host tripple, e.g. \"x86_64-linux-gnu\" or \"x86_64-w64-mingw32\".
\"<cpu>-<vendor>-<os> docker run ghcr.io/openmodelica/crossbuild:v1.28.0\" host triple with OpenModelica supplied Docker image, e.g. \"x86_64-linux-gnu docker run ghcr.io/openmodelica/crossbuild:v1.28.0\".
\"<cpu>-<vendor>-<os> docker run <image>\" host triple with Docker image, e.g. \"x86_64-linux-gnu docker run --pull=never multiarch/crossbuild\"";
input Boolean includeResources = false "Depreacted and no effect";
input String method = "<default>" "integration method embedded in a Co-Simulation FMU. <default> = dassl";
output String generatedFileName "Returns the full path of the generated FMU.";
end buildModelFMU;
cd¶
Changes the working directory.
Changes the working directory to the given filesystem path (which may be either relative or absolute). Returns the new working directory on success or a message on failure.
If the given path is the empty string, the function simply returns the current working directory.
impure function cd
input String newWorkingDirectory = "";
output String workingDirectory;
end cd;
checkAllModelsRecursive¶
Checks all models recursively and returns number of variables and equations.
impure function checkAllModelsRecursive
input TypeName className;
input Boolean checkProtected = false "Checks also protected classes if true";
input Boolean reportTimes = true "Reports time elapsed for every checked model if true";
output String result;
end checkAllModelsRecursive;
checkCodeGraph¶
Checks if the given taskgraph has the same structure as the graph described in the codefile.
impure function checkCodeGraph
input String graphfile;
input String codefile;
output String[:] result;
end checkCodeGraph;
checkInterfaceOfPackages¶
Checks the interfaces of MetaModelica packages.
Verifies the __OpenModelica_Interface=str annotation of all loaded packages with respect to the given main class.
For each row in the dependencyMatrix, the first element is the name of a dependency type. The rest of the elements are the other accepted dependency types for this one (frontend can call frontend and util, for example). Empty entries are ignored (necessary in order to have a rectangular matrix).
impure function checkInterfaceOfPackages
input TypeName cl;
input String dependencyMatrix[:, :];
output Boolean success;
end checkInterfaceOfPackages;
checkModel¶
Checks a model and returns the number of variables and equations.
impure function checkModel
input TypeName className;
output String result;
end checkModel;
checkSettings¶
Display some diagnostics.
impure function checkSettings
output CheckSettingsResult result;
end checkSettings;
checkTaskGraph¶
Checks if the given taskgraph has the same structure as the reference taskgraph and if all attributes are set correctly.
impure function checkTaskGraph
input String filename;
input String reffilename;
output String[:] result;
end checkTaskGraph;
classAnnotationExists¶
Checks if an annotation exists in a class.
Returns true if className has a class annotation called annotationName.
impure function classAnnotationExists
input TypeName className;
input TypeName annotationName;
output Boolean exists;
end classAnnotationExists;
clear¶
Clears loaded classes and user defined variables.
impure function clear
output Boolean success;
end clear;
clearCommandLineOptions¶
Resets all command line options to their default values.
impure function clearCommandLineOptions
output Boolean success;
end clearCommandLineOptions;
clearDebugFlags¶
Resets all debug flags to their default values.
impure function clearDebugFlags
output Boolean success;
end clearDebugFlags;
clearMessages¶
Clears the error buffer.
impure function clearMessages
output Boolean success;
end clearMessages;
clearProgram¶
Clears loaded classes.
impure function clearProgram
output Boolean success;
end clearProgram;
clearVariables¶
Clears all user defined variables.
impure function clearVariables
output Boolean success;
end clearVariables;
closeSimulationResultFile¶
Closes the current simulation results file.
Only needed by Windows. Windows cannot handle reading and writing to the same file from different processes. To allow OMEdit to make successful simulation again on the same file we must close the file after reading the Simulation Result Variables.
impure function closeSimulationResultFile
output Boolean success;
end closeSimulationResultFile;
codeToString¶
Converts a $Code expression to a string.
function codeToString
input ExpressionOrModification className;
output String string;
end codeToString;
compareFiles¶
Checks if two files are equal or not.
Compares file1 and file2 and returns true if their content is equal, otherwise false.
impure function compareFiles
input String file1;
input String file2;
output Boolean isEqual;
end compareFiles;
compareFilesAndMove¶
Overwrites a file with another if they differ.
Compares newFile and oldFile. If they differ, overwrite oldFile with newFile
Basically: test -f ../oldFile && cmp newFile oldFile || mv newFile oldFile
impure function compareFilesAndMove
input String newFile;
input String oldFile;
output Boolean success;
end compareFilesAndMove;
convertPackageToLibrary¶
Runs the conversion script for a library on a selected package.
impure function convertPackageToLibrary
input TypeName packageToConvert;
input TypeName library;
input String libraryVersion;
output Boolean success;
end convertPackageToLibrary;
convertUnits¶
Gets conversion factors for two units.
Returns the scale factor and offsets used when converting two units.
Returns false if the types are not compatible and should not be converted.
impure function convertUnits
input String s1;
input String s2;
output Boolean unitsCompatible;
output Real scaleFactor;
output Real offset;
end convertUnits;
copy¶
Copies a file.
Copies the source file to the destination file. Returns true if the file was successfully copied, otherwise false.
impure function copy
input String source;
input String destination;
output Boolean success;
end copy;
copyClass¶
Copies a class within the same level.
impure function copyClass
input TypeName className "the class that should be copied";
input String newClassName "the name for new class";
input TypeName withIn = $Code(__OpenModelica_TopLevel) "the within path for new class";
output Boolean result;
end copyClass;
countMessages¶
Returns the number of buffered messages.
Returns the total number of messages in the error buffer, as well as the number of errors and warnings.
impure function countMessages
output Integer numMessages;
output Integer numErrors;
output Integer numWarnings;
end countMessages;
createModel¶
Creates a new empty model.
impure function createModel
input TypeName className;
output Boolean success;
end createModel;
deleteClass¶
Unloads a class.
impure function deleteClass
input TypeName className;
output Boolean success;
end deleteClass;
deleteComponent¶
Deletes a component from the given class.
impure function deleteComponent
input TypeName componentName;
input TypeName classPath;
output Boolean success;
end deleteComponent;
deleteConnection¶
Deletes a connection in the given class.
impure function deleteConnection
input VariableName connector1;
input VariableName connector2;
input TypeName className;
output Boolean success;
end deleteConnection;
deleteEquation¶
Deletes an equation in a class.
Alias for updateEquation() with
newEq =
deleteFile¶
Deletes a file with the given name.
impure function deleteFile
input String fileName;
output Boolean success;
end deleteFile;
deleteInitialState¶
Deletes an initial state in a class.
impure function deleteInitialState
input TypeName cl;
input String state;
output Boolean bool;
end deleteInitialState;
deleteTransition¶
Deletes a transition from a class.
impure function deleteTransition
input TypeName cl;
input String from;
input String to;
input String condition;
input Boolean immediate;
input Boolean reset;
input Boolean synchronize;
input Integer priority;
output Boolean bool;
end deleteTransition;
deltaSimulationResults¶
Calculates the sum of absolute errors.
For each data point in the reference file, the sum of all absolute error sums of all given variables is calculated.
impure function deltaSimulationResults
input String filename;
input String reffilename;
input String method "method to compute then error. choose 1norm, 2norm, maxerr";
input String[:] vars = fill("", 0);
output Real result;
end deltaSimulationResults;
diffModelicaFileListings¶
Creates diffs of two strings corresponding to Modelica files
Creates diffs of two strings (before and after) corresponding to Modelica files. The diff is specialized to handle the list API moving comments around in the file and introducing or deleting whitespace.
The output can be chosen to be a colored diff (for terminals), XML, or the final text (deletions removed).
impure function diffModelicaFileListings
input String before;
input String after;
input DiffFormat diffFormat = DiffFormat.color;
input Boolean failOnSemanticsChange = false "Defaults to returning after instead of hard fail";
output String result;
end diffModelicaFileListings;
diffSimulationResults¶
Compares simulation results.
Takes two result files and compares them. By default, all selected variables that are not equal in the two files are output to diffPrefix.varName.csv; an empty diffPrefix writes no files.
The output is the names of the variables for which files were generated.
impure function diffSimulationResults
input String actualFile;
input String expectedFile;
input String diffPrefix;
input Real relTol = 1e-3 "y tolerance";
input Real relTolDiffMinMax = 1e-4 "y tolerance based on the difference between the maximum and minimum of the signal";
input Real rangeDelta = 0.002 "x tolerance";
input String[:] vars = fill("", 0);
input Boolean keepEqualResults = false;
output Boolean success;
output String[:] failVars;
end diffSimulationResults;
diffSimulationResultsHtml¶
Compares simulation results and generates an HTML report.
Takes two result files and compares them. By default, all selected variables that are not equal in the two files are output to diffPrefix.varName.csv; an empty diffPrefix writes no files.
The output is the names of the variables for which files were generated.
impure function diffSimulationResultsHtml
input String var;
input String actualFile;
input String expectedFile;
input Real relTol = 1e-3 "y tolerance";
input Real relTolDiffMinMax = 1e-4 "y tolerance based on the difference between the maximum and minimum of the signal";
input Real rangeDelta = 0.002 "x tolerance";
output String html;
end diffSimulationResultsHtml;
directoryExists¶
Returns whether the given directory exists or not.
impure function directoryExists
input String dirName;
output Boolean exists;
end directoryExists;
dirname¶
Returns the directory name of a file path.
Similar to dirname(3), but with the safety of Modelica strings.
function dirname
input String path;
output String dirname;
end dirname;
disableNewInstantiation¶
Disables the new (default) instantiation.
impure function disableNewInstantiation
output Boolean success;
end disableNewInstantiation;
dumpXMLDAE¶
Outputs the DAE system corresponding to a specific model.
Valid translationLevel strings are: flat, optimiser (runs the backend until sorting/matching), backEnd, or stateSpace.
impure function dumpXMLDAE
input TypeName className;
input String translationLevel = "flat" "flat, optimiser, backEnd, or stateSpace";
input Boolean addOriginalAdjacencyMatrix = false;
input Boolean addSolvingInfo = false;
input Boolean addMathMLCode = false;
input Boolean dumpResiduals = false;
input String fileNamePrefix = "<default>" "this is the className in string form by default";
input String rewriteRulesFile = "" "the file from where the rewiteRules are read, default is empty which means no rewrite rules";
output Boolean success "if the function succeeded true/false";
output String xmlfileName "the Xml file";
end dumpXMLDAE;
echo¶
Turns interactive output on or off.
echo(false) turns off all output when executing interactive commands or a script, echo(true) turns it on again.
impure function echo
input Boolean setEcho;
output Boolean newEcho;
end echo;
enableNewInstantiation¶
Enables the new (default) instantiation.
impure function enableNewInstantiation
output Boolean success;
end enableNewInstantiation;
escapeXML¶
Replaces characters in a string with XML escape characters.
function escapeXML
input String inStr;
output String outStr;
end escapeXML;
evaluateProbe¶
Evaluates a property of a node of the probe tree of a file, see getProbeTree, and returns the result as JSON: a list of items, each a text, a node (the id of a node of the tree), a diagnostic with a severity (error, warning or info), a span and a message, or an arrow with a color, a span, the span it points to and a message.
The properties are:
text,hover: the source of the node and what an editor shows when hovering it.errors,topClasses,contextModel,omcVersionof the file: the names that couldn't be looked up and the messages ofcheckModelof the models in it, and its classes.definition,uses,useArrows,role: what a name refers to and how it's used there, and the uses in the file of a class, component or declared name, as nodes or as arrows from the declaration.dependsOn,checkModel,flatModelica,modelInstanceof a class: the classes it uses, as ingetDependencyGraph, and the results ofcheckModel, ofinstantiateModelas Base Modelica and ofgetModelInstance.simVariables,simEquations,jacobianEquations,cCode,translationMessages,flatDeclarations,connectionEquations: what a class, component, equation or connect became in the translation of the context model: its simulation variables, the simulation equations with the symbolic operations done on them, the generated C functions of the equations, the declarations in the flat model and the equations of the flat model a connect generates.bltof a class andbltBlockof an equation or statement: the blocks of the initial and regular equations of the translation in the order they're solved, with the systems of equations and their iteration variables, and the block the simulation equations of an equation are in, each with links to the equations of the file the equations of the block come from.stateSelectionof a class or component: the states of the translation, the variables index reduction didn't choose as states (dummy states) with the variable they're equal to and how, and thestateSelectattributes.
The translation of the context model is kept in a directory in the temporary directory, named by the hash of the name and contents of the file, so it's done once for each version of the file.
impure function evaluateProbe
input String fileName "A file whose classes are loaded.";
input String nodeId "The id of a node of getProbeTree.";
input String property "One of the properties of the node.";
input String contextModel = "" "The model translated for the simulation properties, the model the node is in if empty.";
input Boolean prettyPrint = false;
output String result;
end evaluateProbe;
existClass¶
Returns whether the given class exists or not.
impure function existClass
input TypeName cl;
output Boolean exists;
end existClass;
existModel¶
Returns whether the given model exists or not.
existPackage¶
Returns whether the given package exists or not.
exit¶
Forces omc to quit with the given exit status.
impure function exit
input Integer status;
end exit;
exportToFigaro¶
Exports a model to a Figaro database.
impure function exportToFigaro
input TypeName path;
input String directory = cd();
input String database;
input String mode;
input String options;
input String processor;
output Boolean success;
end exportToFigaro;
extendsFrom¶
Returns true if the given class extends from the given base class.
impure function extendsFrom
input TypeName className;
input TypeName baseClassName;
output Boolean res;
end extendsFrom;
filterSimulationResults¶
Creates a simulation results file with selected variables.
Takes one simulation result and filters out the selected variables only, producing the output file.
If numberOfIntervals<>0, re-sample to that number of intervals, ignoring event points (might be changed in the future).
if removeDescription=true, the description matrix will contain 0-length strings, making the file smaller.
if hintReadAllVars=true, the whole mat-file will be read at once (this is faster but uses more memory if you only use few variables from the file). May cause a crash if there is not enough virtual memory.
impure function filterSimulationResults
input String inFile;
input String outFile;
input String[:] vars;
input Integer numberOfIntervals = 0 "0=Do not resample";
input Boolean removeDescription = false;
input Boolean hintReadAllVars = true;
output Boolean success;
end filterSimulationResults;
generateCode¶
Generates code for a function.
The input is a function name for which C-code is generated and compiled into a dll/so.
impure function generateCode
input TypeName className;
output Boolean success;
end generateCode;
generateEntryPoint¶
Generates an entry point for a MetaModelica program.
Generates a main() function that calls the given MetaModelica entry point (assumed to have input list and no outputs).
impure function generateEntryPoint
input String fileName;
input TypeName entryPoint;
input String url = "https://trac.openmodelica.org/OpenModelica/newticket";
end generateEntryPoint;
generateHeader¶
Generates header file for external MetaModelica functions.
impure function generateHeader
input String fileName;
output Boolean success;
end generateHeader;
generateScriptingAPI¶
Generates the scripting API.
Returns OpenModelica.Scripting API entry points for the classes that we can automatically generate entry points for.
The entry points are MetaModelica code calling CevalScript directly, and Qt/C++ code that calls the MetaModelica code.
impure function generateScriptingAPI
input TypeName cl;
input String name;
output Boolean success;
output String moFile;
output String qtFile;
output String qtHeader;
end generateScriptingAPI;
generateSeparateCode¶
Generates code for a MetaModelica package.
Under construction.
impure function generateSeparateCode
input TypeName className;
input Boolean cleanCache = false "If true, the cache is reset between each generated package. This conserves memory at the cost of speed.";
output Boolean success;
end generateSeparateCode;
generateSeparateCodeDependencies¶
Generates dependencies for a MetaModelica package.
Under construction.
impure function generateSeparateCodeDependencies
input String stampSuffix = ".c" "Suffix to add to dependencies (often .c.stamp)";
output String[:] dependencies;
end generateSeparateCodeDependencies;
generateSeparateCodeDependenciesMakefile¶
Generates dependencies Makefile for a MetaModelica package.
Under construction.
impure function generateSeparateCodeDependenciesMakefile
input String filename "The file to write the makefile to";
input String directory = "" "The relative path of the generated files";
input String suffix = ".c" "Often .stamp since we do not update all the files";
output Boolean success;
end generateSeparateCodeDependenciesMakefile;
generateVerificationScenarios¶
Generate scenarios for a verification model.
impure function generateVerificationScenarios
input TypeName path;
output Boolean success;
end generateVerificationScenarios;
getAlgorithmCount¶
Counts the number of algorithm sections in a class.
impure function getAlgorithmCount
input TypeName class_;
output Integer count;
end getAlgorithmCount;
getAlgorithmItemsCount¶
Counts the number of algorithm statements in a class.
impure function getAlgorithmItemsCount
input TypeName class_;
output Integer count;
end getAlgorithmItemsCount;
getAllSubtypeOf¶
Returns the list of all classes that extend from className given a parentClass where the lookup for className should start
impure function getAllSubtypeOf
input TypeName className;
input TypeName parentClass = $Code(AllLoadedClasses);
input Boolean qualified = false "Not implemented";
input Boolean includePartial = false;
input Boolean sort = false;
output TypeName classNames[:];
end getAllSubtypeOf;
getAnnotationCount¶
Counts the number of annotation sections in a class.
impure function getAnnotationCount
input TypeName class_;
output Integer count;
end getAnnotationCount;
getAnnotationModifierValue¶
Returns the value for a modifier in the given annotation.
Example:
model M
annotation(experiment(StartTime = 1.0, StopTime = 2.0));
end M;
getAnnotationModifierValue(M, "experiment", "StopTime") => 2.0
impure function getAnnotationModifierValue
input TypeName className;
input String annotationName;
input String modifierName;
output String modifierValue;
end getAnnotationModifierValue;
getAnnotationNamedModifiers¶
Returns the names of the modifiers in the given annotation.
Example:
model M
annotation(experiment(StartTime = 1.0, StopTime = 2.0));
end M;
getAnnotationNamedModifiers(M, "experiment") => {"StartTime", "StopTime"}
impure function getAnnotationNamedModifiers
input TypeName className;
input String annotationName;
output String[:] modifierNames;
end getAnnotationNamedModifiers;
getAnnotationVersion¶
Returns the current annotation version.
impure function getAnnotationVersion
output String annotationVersion;
end getAnnotationVersion;
getAvailableIndexReductionMethods¶
Returns the currently available index reduction methods.
function getAvailableIndexReductionMethods
output String[:] allChoices;
output String[:] allComments;
end getAvailableIndexReductionMethods;
getAvailableLibraries¶
Returns a list of all available libraries.
Looks for all libraries that are visible from the getModelicaPath().
impure function getAvailableLibraries
output String[:] libraries;
end getAvailableLibraries;
getAvailableLibraryVersions¶
Returns the installed versions of a library.
impure function getAvailableLibraryVersions
input TypeName libraryName;
output String[:] librariesAndVersions;
end getAvailableLibraryVersions;
getAvailableMatchingAlgorithms¶
Returns the available matching algorithms.
function getAvailableMatchingAlgorithms
output String[:] allChoices;
output String[:] allComments;
end getAvailableMatchingAlgorithms;
getAvailablePackageConversionsFrom¶
Returns the versions that provide conversion from the requested version of the library.
impure function getAvailablePackageConversionsFrom
input TypeName pkg;
input String version;
output String[:] convertsTo;
end getAvailablePackageConversionsFrom;
getAvailablePackageConversionsTo¶
Returns the versions that provide conversion to the requested version of the library.
impure function getAvailablePackageConversionsTo
input TypeName pkg;
input String version;
output String[:] convertsTo;
end getAvailablePackageConversionsTo;
getAvailablePackageVersions¶
Returns the versions that provide the requested version of the library.
impure function getAvailablePackageVersions
input TypeName pkg;
input String version;
output String[:] withoutConversion;
end getAvailablePackageVersions;
getAvailableTearingMethods¶
Returns the available tearing methods.
function getAvailableTearingMethods
output String[:] allChoices;
output String[:] allComments;
end getAvailableTearingMethods;
getBooleanClassAnnotation¶
Checks if an annotation exists and returns its value
Returns the value of the class annotation annotationName of class className. If there is no such annotation, or if it is not true or false, this function fails.
impure function getBooleanClassAnnotation
input TypeName className;
input TypeName annotationName;
output Boolean value;
end getBooleanClassAnnotation;
getBuiltinType¶
Returns the builtin type e.g Real, Integer, Boolean & String of the class.
impure function getBuiltinType
input TypeName cl;
output String name;
end getBuiltinType;
getCFlags¶
Returns the C compiler flags (CFLAGS) used for simulation code.
See setCFlags() for details.
impure function getCFlags
output String outString;
end getCFlags;
getCXXCompiler¶
Returns the C++ compiler (CXX) used for simulation code.
impure function getCXXCompiler
output String compiler;
end getCXXCompiler;
getClassComment¶
Returns a class's comment.
impure function getClassComment
input TypeName cl;
output String comment;
end getClassComment;
getClassDiagram¶
Returns a UML class diagram of className, as PlantUML text, as Mermaid text, which GitHub and GitLab show as a diagram in a mermaid code block, or as a draw.io (diagrams.net) file that can be edited and rearranged.
The diagram has the class, the classes it extends, directly or not, and the classes it uses up to depth levels: the types of its components, and the classes replaceable classes default to, are constrained by or are redeclared as. With depth = 0 it only has the class and its base classes. Class extends (redeclare model extends) and redeclared classes declared in a class in the diagram are also in it, together with the classes they replace. The names are looked up like in getDefUseChains, without instantiating anything, so it also works for packages and partial classes.
Every class is shown with its full name, how it's declared as stereotype (e.g. «replaceable package» or «redeclare function extends») and partial classes as abstract, with the components and short class definitions declared in it and the replaceable classes declared in it that aren't in the diagram. extends and class extends are generalizations, labelled with their modifiers, components of a class in the diagram are compositions, labelled with their names and dimensions, and short class definitions, constraining classes and redeclares in modifiers are dependencies, labelled with what declares them, and a redeclared class that doesn't extend the class it replaces depends on it, labelled redeclares. Classes declared in a class are nested in it; Mermaid has no nesting, so there they are linked to it, labelled nested.
In the draw.io file every class links to modelica:// and its name, and every line in the box of a class links to the line in the file of the element it shows, e.g. modelica://P.M?lineNumber=12, and for a component also to its name, e.g. modelica://P.M?lineNumber=12&element=c.
The classes in exclude and in the packages in exclude are left out, except className itself. With showModifiers = false the modifiers and bindings aren't shown.
impure function getClassDiagram
input TypeName className;
input String fileName = "" "The file to write the diagram to, if not empty.";
input String format = "plantuml" "plantuml, mermaid or drawio.";
input Integer depth = 1 "How many levels of used classes to include.";
input String exclude[:] = {"Modelica.Icons"} "Classes and packages to leave out.";
input Boolean showModifiers = true;
output String diagram "The diagram, or the file name if it was written to a file.";
end getClassDiagram;
getClassInformation¶
Returns information about a class.
The dimensions are returned as an array of strings. The string is the textual representation of the dimension (they are not evaluated to Integers).
impure function getClassInformation
input TypeName cl;
output String restriction, comment;
output Boolean partialPrefix, finalPrefix, encapsulatedPrefix;
output String fileName;
output Boolean fileReadOnly;
output Integer lineNumberStart, columnNumberStart, lineNumberEnd, columnNumberEnd;
output String dimensions[:];
output Boolean isProtectedClass;
output Boolean isDocumentationClass;
output String version;
output String preferredView;
output Boolean state;
output String access;
output String versionDate;
output String versionBuild;
output String dateModified;
output String revisionId;
end getClassInformation;
getClassNames¶
Returns the list of class names defined in the class.
impure function getClassNames
input TypeName class_ = $Code(AllLoadedClasses);
input Boolean recursive = false;
input Boolean qualified = false;
input Boolean sort = false;
input Boolean builtin = false "List also builtin classes if true";
input Boolean showProtected = false "List also protected classes if true";
input Boolean includeConstants = false "List also constants in the class if true";
output TypeName classNames[:];
end getClassNames;
getClassRestriction¶
Returns the restriction of the given class.
impure function getClassRestriction
input TypeName cl;
output String restriction;
end getClassRestriction;
getCommandLineOptions¶
Returns all command line options who have non-default values as a list of strings.
Example output: {"-d=failtrace", "--showErrorMessages=true"}.
impure function getCommandLineOptions
output String[:] flags;
end getCommandLineOptions;
getCompiler¶
Returns the C compiler (CC) used for simulation code.
impure function getCompiler
output String compiler;
end getCompiler;
getComponentAnnotations¶
Returns the annotations of the components in the given class.
impure function getComponentAnnotations
input TypeName className;
output Expression result;
end getComponentAnnotations;
getComponentComment¶
Returns the comment on a component.
impure function getComponentComment
input TypeName className;
input TypeName componentName;
output String comment;
end getComponentComment;
getComponentCondition¶
Returns the condition of the given component in the given class as a string.
impure function getComponentCondition
input TypeName className;
input TypeName componentName;
output String result;
end getComponentCondition;
getComponentCount¶
Returns the number of components in a class.
impure function getComponentCount
input TypeName classPath;
output Integer count;
end getComponentCount;
getComponentModifierNames¶
Returns the list of class component modifiers.
impure function getComponentModifierNames
input TypeName class_;
input String componentName;
output String[:] modifiers;
end getComponentModifierNames;
getComponentModifierValue¶
Returns the binding equation of a component.
Returns the modifier value (only the binding excluding submodifiers) of a component.
Example:
model A
B b1(a1(p1=5,p2=4));
end A;
getComponentModifierValue(A,b1.a1.p1) => 5
getComponentModifierValue(A,b1.a1.p2) => 4
See also getComponentModifierValues().
impure function getComponentModifierValue
input TypeName class_;
input TypeName modifier;
output String value;
end getComponentModifierValue;
getComponentModifierValues¶
Returns the modifier for a component.
Returns the modifier (including the submodfiers) for a component.
Example:
model A
B b1(a1(p1=5,p2=4));
end A;
getComponentModifierValues(A,b1.a1) => (p1 = 5, p2 = 4)
See also getComponentModifierValue().
impure function getComponentModifierValues
input TypeName class_;
input TypeName modifier;
output String value;
end getComponentModifierValues;
getComponents¶
Returns information about the component in a given class.
For each component the following information is returned in an array:
type
name
description string
public/protected
final prefix
flow prefix
stream prefix
replaceable prefix
variability (constant/parameter/discrete/unspecified)
inner/outer prefix
input/output prefix
array dimensions
impure function getComponents
input TypeName className;
input Boolean useQuotes = false;
end getComponents;
getComponentsTest¶
Returns an array of records with information about the components of the given class.
impure function getComponentsTest
input TypeName name;
output Component[:] components;
record Component
String className "the type of the component";
String name "the name of the component";
String comment "the comment of the component";
Boolean isProtected "true if component is protected";
Boolean isFinal "true if component is final";
Boolean isFlow "true if component is flow";
Boolean isStream "true if component is stream";
Boolean isReplaceable "true if component is replaceable";
String variability "'constant', 'parameter', 'discrete', ''";
String innerOuter "'inner', 'outer', ''";
String inputOutput "'input', 'output', ''";
String dimensions[:] "array with the dimensions of the component";
end Component;
end getComponentsTest;
getConfigFlagValidOptions¶
Returns the list of valid options for a string config flag, and the description strings for these options if available.
function getConfigFlagValidOptions
input String flag;
output String validOptions[:];
output String mainDescription;
output String descriptions[:];
end getConfigFlagValidOptions;
getConnectionCount¶
Counts the number of connect equation in a class.
impure function getConnectionCount
input TypeName className;
output Integer count;
end getConnectionCount;
getConnectionList¶
Returns an list of all connect equations including those within loops
Example:
{{"connector1.lhs","connector1.rhs"}, {"connector2.lhs","connector2.rhs"}}
impure function getConnectionList
input TypeName className;
output String[:, :] result;
end getConnectionList;
getConnectorCount¶
Returns the number of public connectors in the given class.
impure function getConnectorCount
input TypeName className;
output Integer count;
end getConnectorCount;
getConversionsFromVersions¶
Returns the versions this library can convert from with and without conversions.
impure function getConversionsFromVersions
input TypeName pack;
output String[:] withoutConversion;
output String[:] withConversion;
end getConversionsFromVersions;
getCrefInfo¶
Deprecated; use getClassInformation instead.
impure function getCrefInfo
input TypeName cl;
output Expression[:] result;
end getCrefInfo;
getDefUseChains¶
Returns the def-use chains of the names in className as JSON: for every name used in it or declared in it, where it's declared and everywhere in scope it's used. If className is a component, e.g. P.Base.x, only the chain of that component is returned.
The names are looked up with the new frontend like the instantiation would, through imports, base classes and redeclares, but without instantiating anything, so it also works for packages, partial classes and classes that can't be instantiated. A name looked up through a replaceable class is also looked up in the classes it's redeclared as, and those uses are marked as candidate.
The JSON has the definitions, each with its name, kind (class, component or iterator), its source span and the position of its name, and its uses. A use has the position of the name, the text as written, the part of a qualified name that refers to the definition, the class it's used in and its role (type, extends, modifier, binding, dimension, condition, constrainedby, equation, algorithm, argument, import, annotation, classExtends, redeclare, end). If the name isn't found in the source, exact is false and the position is the span of what it's used in. The names that couldn't be looked up are listed under unresolved.
impure function getDefUseChains
input TypeName className "A class, or a component declared in a class.";
input String fileName = "" "The file to write the JSON to, if not empty.";
input TypeName scope = $Code(AllLoadedClasses) "The class to look for the uses in.";
input Boolean prettyPrint = false;
output String chains "The JSON, or the file name if it was written to a file.";
end getDefUseChains;
getDefaultComponentName¶
Returns the default component name for a class.
Returns the default component name for a class as defined by the defaultComponentName annotation.
impure function getDefaultComponentName
input TypeName cl;
output String name;
end getDefaultComponentName;
getDefaultComponentPrefixes¶
Returns the default component prefixes for a class.
Returns the default component prefixes for a class as defined by the defaultComponentPrefixes annotation.
impure function getDefaultComponentPrefixes
input TypeName cl;
output String prefixes;
end getDefaultComponentPrefixes;
getDefaultOpenCLDevice¶
Returns the id for the default OpenCL device to be used.
impure function getDefaultOpenCLDevice
output Integer defdevid;
end getDefaultOpenCLDevice;
getDefinitionAt¶
Returns the definition of the name at a position in a file as JSON, e.g. for go to definition in an editor. The names in the innermost class the position is in are looked up like in getDefUseChains, and the positions of the names are found in the file on disk.
The JSON has the file, line and column, the definition (as in getDefUseChains, without its uses) or null if there's no name at the position or it can't be looked up, the use of the name at the position or null if it's the declared name of the definition, and the candidates in the classes a replaceable class is redeclared as. The uses of the definition are returned by getDefUseChains with its name.
impure function getDefinitionAt
input String fileName "A file of a loaded class.";
input Integer line;
input Integer column "Starting at 1, counting bytes.";
input Boolean prettyPrint = false;
output String definition;
end getDefinitionAt;
getDependencyGraph¶
Returns the classes in scope and the classes they use as JSON, to find out which classes a change of a library affects. The names are looked up like in getDefUseChains.
The JSON has an object classes with a member for each class, named by its full name, with its kind, restriction, source span, hash and uses. The hash is computed from the source of the class without the classes declared in it, comments and whitespace, so it only changes when the class itself changes. uses are the full names of the classes it uses, sorted, including the classes that declare the components, constants and enumeration literals it uses and the candidates of names looked up through replaceable classes. A class is affected by a change if it or a class it uses, directly or not, has another hash or other uses.
impure function getDependencyGraph
input TypeName scope = $Code(AllLoadedClasses) "The classes to include.";
input String fileName = "" "The file to write the JSON to, if not empty.";
input Boolean prettyPrint = false;
output String graph "The JSON, or the file name if it was written to a file.";
end getDependencyGraph;
getDerivedClassModifierNames¶
Returns a derived class's modifier names.
Example command:
type Resistance = Real(final quantity="Resistance",final unit="Ohm");
getDerivedClassModifierNames(Resistance) => {"quantity","unit"}
impure function getDerivedClassModifierNames
input TypeName className;
output String[:] modifierNames;
end getDerivedClassModifierNames;
getDerivedClassModifierValue¶
Returns a derived class's modifier value.
Example command:
type Resistance = Real(final quantity="Resistance",final unit="Ohm");
getDerivedClassModifierValue(Resistance, unit); => " = "Ohm""
getDerivedClassModifierValue(Resistance, quantity); => " = "Resistance""
impure function getDerivedClassModifierValue
input TypeName className;
input TypeName modifierName;
output String modifierValue;
end getDerivedClassModifierValue;
getDerivedUnits¶
Returns the list of derived units for the specified base unit.
impure function getDerivedUnits
input String baseUnit;
output String[:] derivedUnits;
end getDerivedUnits;
getDiagramAnnotation¶
Returns the Diagram annotation for a given class.
impure function getDiagramAnnotation
input TypeName className;
output Expression result;
end getDiagramAnnotation;
getDocumentationAnnotation¶
Returns the Documentation annotation defined in the class.
impure function getDocumentationAnnotation
input TypeName cl;
output String out[3] "{info,revision,infoHeader}";
end getDocumentationAnnotation;
getElementAnnotation¶
Returns the annotation on a component or class element as a string.
impure function getElementAnnotation
input TypeName elementName;
output String annotationString;
end getElementAnnotation;
getElementAnnotations¶
Returns the annotations of the components and short class definitions in the given class.
impure function getElementAnnotations
input TypeName className;
output Expression result;
end getElementAnnotations;
getElementModifierNames¶
Returns the list of element (component or short class) modifiers in a class.
impure function getElementModifierNames
input TypeName className;
input String elementName;
output String[:] modifiers;
end getElementModifierNames;
getElementModifierValue¶
Returns the binding equation for an element.
Returns the modifier value (only the binding excluding submodifiers) of an element (component or short class).
Example:
model A
B b1(a1(p1=5,p2=4));
model X = Y(a1(p1=5,p2=4));
end A;
getElementModifierValue(A,b1.a1.p1) => 5
getElementModifierValue(A,b1.a1.p2) => 4
getElementModifierValue(A,X.a1.p1) => 5
getElementModifierValue(A,X.a1.p2) => 4
See also getElementModifierValues().
impure function getElementModifierValue
input TypeName className;
input TypeName modifier;
output String value;
end getElementModifierValue;
getElementModifierValues¶
Returns the modifier for an element.
Returns the modifier value (including the submodifiers) of an element (component or short class).
Example:
model A
B b1(a1(p1=5,p2=4));
model X = Y(a1(p1=5,p2=4));
end A;
getElementModifierValues(A,b1.a1) => (p1 = 5, p2 = 4)
getElementModifierValues(A,X.a1) => (p1 = 5, p2 = 4)
See also getElementModifierValue().
impure function getElementModifierValues
input TypeName className;
input TypeName modifier;
output String value;
end getElementModifierValues;
getElements¶
Returns information about the elements in a given class.
For each component/short class definition the following information is returned in an array:
kind of element (co = component, cl = class)
class restriction
type
name
description string
public/protected
final prefix
flow prefix
stream prefix
replaceable prefix
variability (constant/parameter/discrete/unspecified)
inner/outer prefix
input/output prefix
constraining class
array dimensions
impure function getElements
input TypeName className;
input Boolean useQuotes = false;
end getElements;
getElementsInfo¶
Returns information about the elements in a given class.
impure function getElementsInfo
input TypeName className;
output Expression result;
end getElementsInfo;
getEnumerationLiterals¶
Returns the literals for a given enumeration type.
impure function getEnumerationLiterals
input TypeName className;
output String[:] result;
end getEnumerationLiterals;
getEnvironmentVar¶
Returns the value of the given environment variable.
impure function getEnvironmentVar
input String var;
output String value "returns empty string on failure";
end getEnvironmentVar;
getEquationCount¶
Counts the number of equation sections in a class.
impure function getEquationCount
input TypeName class_;
output Integer count;
end getEquationCount;
getEquationItemsCount¶
Counts the number of equations in a class.
impure function getEquationItemsCount
input TypeName class_;
output Integer count;
end getEquationItemsCount;
getErrorString¶
Returns current error messages.
Returns a user-friendly string containing the errors stored in the buffer. With warningsAsErrors=true, it reports warnings as if they were errors.
impure function getErrorString
input Boolean warningsAsErrors = false;
output String errorString;
end getErrorString;
getExtendsModifierNames¶
Returns the names of the modifiers on an extends clause.
impure function getExtendsModifierNames
input TypeName className;
input TypeName extendsName;
input Boolean useQuotes = false;
output String modifiers;
end getExtendsModifierNames;
getExtendsModifierValue¶
Returns the modifier value for a modifier on an extends clause.
impure function getExtendsModifierValue
input TypeName className;
input TypeName extendsName;
input TypeName modifierName;
output Expression result;
end getExtendsModifierValue;
getExternalFunctionSpecification¶
Returns information about a function's external specification.
Returns information about the given function's external specification: language, output variable, external function name, arguments, annotations on the external declaration, and annotations on the function.
impure function getExternalFunctionSpecification
input TypeName functionName;
output Expression result;
end getExternalFunctionSpecification;
getExternalFunctions¶
Describes the external "C" functions of a library.
Returns, as JSON, every external "C" function in className, external object constructors and destructors included: its path, C name, the C types of its call in the specification's mapping, its Include annotations and the include directories omc resolves for it. A function the wasm-jit target cannot call carries the reason instead of its C types.
The package manager builds the WebAssembly modules that the wasm-jit target loads for these functions from this description.
impure function getExternalFunctions
input TypeName className;
output String json;
end getExternalFunctions;
getHomeDirectoryPath¶
Returns the path to the current user's HOME directory.
impure function getHomeDirectoryPath
output String homeDirectoryPath;
end getHomeDirectoryPath;
getIconAnnotation¶
Returns the Icon annotation for a given class.
impure function getIconAnnotation
input TypeName className;
output Expression result;
end getIconAnnotation;
getImportCount¶
Counts the number of import-clauses in a class.
impure function getImportCount
input TypeName class_;
output Integer count;
end getImportCount;
getImportedNames¶
Returns the definition names of all import-clauses in a class.
impure function getImportedNames
input TypeName class_;
output String[:] out_public;
output String[:] out_protected;
end getImportedNames;
getIndexReductionMethod¶
Returns the currently used index reduction method.
impure function getIndexReductionMethod
output String selected;
end getIndexReductionMethod;
getInheritanceCount¶
Returns the numbers of extends clauses in the given class.
impure function getInheritanceCount
input TypeName className;
output Integer count;
end getInheritanceCount;
getInheritedClasses¶
Returns the list of inherited classes in a class.
impure function getInheritedClasses
input TypeName name;
output TypeName inheritedClasses[:];
end getInheritedClasses;
getInitialAlgorithmCount¶
Counts the number of initial algorithm sections in a class.
impure function getInitialAlgorithmCount
input TypeName class_;
output Integer count;
end getInitialAlgorithmCount;
getInitialAlgorithmItemsCount¶
Counts the number of initial algorithm statements in a class.
impure function getInitialAlgorithmItemsCount
input TypeName class_;
output Integer count;
end getInitialAlgorithmItemsCount;
getInitialEquationCount¶
Counts the number of initial equation sections in a class.
impure function getInitialEquationCount
input TypeName class_;
output Integer count;
end getInitialEquationCount;
getInitialEquationItemsCount¶
Counts the number of initial equations in a class.
impure function getInitialEquationItemsCount
input TypeName class_;
output Integer count;
end getInitialEquationItemsCount;
getInitialStates¶
Returns a list of initial states in a class.
Each initial state item contains 2 values i.e, state name and annotation.
impure function getInitialStates
input TypeName cl;
output String[:, :] initialStates;
end getInitialStates;
getInstallationDirectoryPath¶
Returns the installation directory path.
Returns the directory OpenModelica is installed in. omc finds it from the location of its own files and sets the environment variable OPENMODELICAHOME to it.
impure function getInstallationDirectoryPath
output String installationDirectoryPath;
end getInstallationDirectoryPath;
getInstanceDiagram¶
Returns a UML instance diagram of the model className as it is instantiated, in the formats of getClassDiagram: PlantUML, Mermaid or draw.io.
Where getClassDiagram shows each class once, with the modifiers it declares, this shows the instances: the model, and each of its components that is an instance of a class, as a box of its own, e.g. a1 : P.A, up to depth levels of components. Each box has the parameters and constants of its instance, including the inherited ones, with the value they have in that instance, as written and evaluated, e.g. parameter Real k = 2*p (= 6). The components that aren't drawn as boxes, connectors and the components below depth, are lines in the box of the instance they are in; variables aren't shown. Protected elements are left out, unless showProtected = true, which shows them marked with -. An array of components is one box, e.g. r[10] : Resistor, or with expandArrays = true a box for each of its elements, e.g. r[1] : Resistor, with the values of that element, if it has at most 100 elements and their number is known.
A component is a composition of the instance it's in, labelled with its name and dimensions. With showConnections = true the connect equations are associations between the boxes of the components they connect, labelled with the connectors.
In the draw.io file every box and line links to the line the component is declared on in its class, with its name, e.g. modelica://P.M?lineNumber=12&element=c, and the box of the model to modelica:// and its name.
The instances of the classes in exclude and in the packages in exclude are left out.
impure function getInstanceDiagram
input TypeName className;
input String fileName = "" "The file to write the diagram to, if not empty.";
input String format = "plantuml" "plantuml, mermaid or drawio.";
input Integer depth = 1 "How many levels of components to draw as boxes of their own.";
input String exclude[:] = fill("", 0) "Classes and packages whose instances are left out.";
input Boolean showConnections = true;
input Boolean showProtected = false "Also show the protected elements.";
input Boolean expandArrays = false "A box for each element of an array of components.";
output String diagram "The diagram, or the file name if it was written to a file.";
end getInstanceDiagram;
getInstantiatedParametersAndValues¶
Returns the top-level parameter names and values from the DAE.
impure function getInstantiatedParametersAndValues
input TypeName cls;
output String[:] values;
end getInstantiatedParametersAndValues;
getLanguageStandard¶
Returns the current Modelica Language Standard in use.
impure function getLanguageStandard
output String outVersion;
end getLanguageStandard;
getLinker¶
Returns the linker (LINK) used for simulation code.
impure function getLinker
output String linker;
end getLinker;
getLinkerFlags¶
Returns the linker flags (LDFLAGS) used for simulation code.
impure function getLinkerFlags
output String linkerFlags;
end getLinkerFlags;
getLoadedLibraries¶
Returns the loaded libraries.
Returns a list of names of libraries and their path on the system, for example:
{{"Modelica","/usr/lib/omlibrary/Modelica 3.2.1"},{"ModelicaServices","/usr/lib/omlibrary/ModelicaServices 3.2.1"}}
impure function getLoadedLibraries
output String[:, 2] libraries;
end getLoadedLibraries;
getMMfileTotalDependencies¶
Returns imports for a MetaModelica package.
impure function getMMfileTotalDependencies
input String in_package_name;
input String public_imports_dir;
output String[:] total_pub_imports;
end getMMfileTotalDependencies;
getMatchingAlgorithm¶
Returns the currently used matching algorithm.
impure function getMatchingAlgorithm
output String selected;
end getMatchingAlgorithm;
getMemorySize¶
Returns the amount of system memory.
Retrieves the physical memory size available on the system in megabytes.
impure function getMemorySize
output Real memory(unit = "MiB");
end getMemorySize;
getModelFigures¶
Returns the figures defined in the class' figures sub-annotation of Documentation.
impure function getModelFigures
input TypeName name;
output Figure[:] figures;
end getModelFigures;
getModelInstance¶
Dumps a model instance as a JSON string.
impure function getModelInstance
input TypeName className;
input TypeName context = $Code(__NoContext);
input String modifier = "";
input Boolean prettyPrint = false;
output String result;
end getModelInstance;
getModelInstanceAnnotation¶
Dumps the annotation of a model using the same JSON format as getModelInstance.
Returns the whole annotation if the filter is empty, otherwise only the parts matching the filter.
impure function getModelInstanceAnnotation
input TypeName className;
input String[:] filter = fill("", 0);
input Boolean prettyPrint = false;
output String result;
end getModelInstanceAnnotation;
getModelInstanceAnnotationReference¶
Like getModelInstanceAnnotation, but returns an integer handle to an in-memory structure instead of a JSON string (see getModelInstanceReference).
impure function getModelInstanceAnnotationReference
input TypeName className;
input String[:] filter = fill("", 0);
output Integer handle;
end getModelInstanceAnnotationReference;
getModelInstanceReference¶
Like getModelInstance, but returns an integer handle to an in-memory model instance structure instead of a JSON string (see issue #15219). The handle is intended to be read directly by an in-process client such as OMEdit and must be released with releaseModelInstanceReference. Returns 0 on failure.
impure function getModelInstanceReference
input TypeName className;
input TypeName context = $Code(__NoContext);
input String modifier = "";
output Integer handle;
end getModelInstanceReference;
getModelicaPath¶
Returns the Modelica library path.
The OPENMODELICALIBRARY (MODELICAPATH in the language specification) is a list of paths to search when trying to load a library. It is a string separated by colon (:) on all OSes except Windows, which uses semicolon (;).
The default is the value of the environment variable OPENMODELICALIBRARY when omc starts, or ~/.openmodelica/libraries/ if it is not set. The environment variable MODELICAPATH is not used. To change the path while omc runs, use setModelicaPath().
The package manager installs libraries into ~/.openmodelica/libraries/. It can only be used if this directory is in the OPENMODELICALIBRARY as the same text, with or without the last '/'.
'~' is the directory that getHomeDirectoryPath() returns. On Windows it is %APPDATA%.
impure function getModelicaPath
output String modelicaPath;
end getModelicaPath;
getNamedAnnotation¶
Returns the value of the annotation with the given name in the given class.
impure function getNamedAnnotation
input TypeName className;
input TypeName annotationName;
output Expression result;
end getNamedAnnotation;
getNoSimplify¶
Returns true if noSimplify flag is set.
impure function getNoSimplify
output Boolean noSimplify;
end getNoSimplify;
getNthAlgorithm¶
Returns the n:th algorithm section in a class.
impure function getNthAlgorithm
input TypeName class_;
input Integer index;
output String result;
end getNthAlgorithm;
getNthAlgorithmItem¶
Returns the n:th algorithm statement in a class.
impure function getNthAlgorithmItem
input TypeName class_;
input Integer index;
output String result;
end getNthAlgorithmItem;
getNthAnnotationString¶
Returns the n:th annotation section as string.
impure function getNthAnnotationString
input TypeName class_;
input Integer index;
output String result;
end getNthAnnotationString;
getNthComponent¶
Returns the type, name, and description string of the n:th component in the given class.
impure function getNthComponent
input TypeName className;
input Integer n;
output Expression result;
end getNthComponent;
getNthComponentAnnotation¶
Returns the annotation for the n:th component in the given class.
impure function getNthComponentAnnotation
input TypeName className;
input Integer n;
output Expression result;
end getNthComponentAnnotation;
getNthComponentCondition¶
Returns the condition for the n:th component in the given class as a string.
impure function getNthComponentCondition
input TypeName className;
input Integer n;
output String result;
end getNthComponentCondition;
getNthComponentModification¶
Returns the modification for the n:th component in the given class.
impure function getNthComponentModification
input TypeName className;
input Integer n;
output ExpressionOrModification result[:];
end getNthComponentModification;
getNthConnection¶
Returns the n:th connection.
Example command:
getNthConnection(A) => {"from", "to", "comment"}
impure function getNthConnection
input TypeName className;
input Integer index;
output String[:] result;
end getNthConnection;
getNthConnectionAnnotation¶
Returns the annotation of the n:th connect clause in the class.
impure function getNthConnectionAnnotation
input TypeName className;
input Integer index;
output Expression result;
end getNthConnectionAnnotation;
getNthConnector¶
Returns the name and type of the n:th public connector in the given class.
impure function getNthConnector
input TypeName className;
input Integer n;
output Expression result;
end getNthConnector;
getNthConnectorIconAnnotation¶
Returns the Icon annotation from the type of the n:th public connector in the given class.
impure function getNthConnectorIconAnnotation
input TypeName className;
input Integer n;
output Expression result;
end getNthConnectorIconAnnotation;
getNthEquation¶
Returns the n:th equation section in a class.
impure function getNthEquation
input TypeName class_;
input Integer index;
output String result;
end getNthEquation;
getNthEquationItem¶
Returns the n:th equation in a class.
impure function getNthEquationItem
input TypeName class_;
input Integer index;
output String result;
end getNthEquationItem;
getNthImport¶
Returns the n:th import-clause.
impure function getNthImport
input TypeName class_;
input Integer index;
output String out[3] "{\"Path\",\"Id\",\"Kind\"}";
end getNthImport;
getNthInheritedClass¶
Returns the name of the n:th inherited class in the given class.
impure function getNthInheritedClass
input TypeName className;
input Integer n;
output TypeName baseClass;
end getNthInheritedClass;
getNthInheritedClassDiagramMapAnnotation¶
Returns the IconMap annotation for the n:th inherited class in the given class.
impure function getNthInheritedClassDiagramMapAnnotation
input TypeName className;
input Integer n;
output Expression result;
end getNthInheritedClassDiagramMapAnnotation;
getNthInheritedClassIconMapAnnotation¶
Returns the IconMap annotation for the n:th inherited class in the given class.
impure function getNthInheritedClassIconMapAnnotation
input TypeName className;
input Integer n;
output Expression result;
end getNthInheritedClassIconMapAnnotation;
getNthInitialAlgorithm¶
Returns the n:th initial algorithm section in a class.
impure function getNthInitialAlgorithm
input TypeName class_;
input Integer index;
output String result;
end getNthInitialAlgorithm;
getNthInitialAlgorithmItem¶
Returns the n:th initial algorithm statement in a class.
impure function getNthInitialAlgorithmItem
input TypeName class_;
input Integer index;
output String result;
end getNthInitialAlgorithmItem;
getNthInitialEquation¶
Returns the n:th initial equation section in a class.
impure function getNthInitialEquation
input TypeName class_;
input Integer index;
output String result;
end getNthInitialEquation;
getNthInitialEquationItem¶
Returns the n:th initial equation in a class.
impure function getNthInitialEquationItem
input TypeName class_;
input Integer index;
output String result;
end getNthInitialEquationItem;
getOrderConnections¶
Returns true if orderConnections flag is set.
impure function getOrderConnections
output Boolean orderConnections;
end getOrderConnections;
getPackages¶
Returns the list of packages defined in the class.
impure function getPackages
input TypeName class_ = $Code(AllLoadedClasses);
output TypeName classNames[:];
end getPackages;
getParameterNames¶
Returns the names of all parameters in a given class.
impure function getParameterNames
input TypeName class_;
output String[:] parameters;
end getParameterNames;
getParameterValue¶
Returns the value of a parameter of the class.
impure function getParameterValue
input TypeName class_;
input String parameterName;
output String parameterValue;
end getParameterValue;
getProbeTree¶
Returns the probe tree of a file as JSON, for property probing tools like CodeProber: the nodes of the file with their source spans and the names of the properties that evaluateProbe can evaluate on them.
The tree is built from the file as it's parsed: the file (StoredDefinition), its classes (ClassDefinition), their elements (ComponentDeclaration, ComponentClause for several components declared together, ExtendsClause, ImportClause), equations (Equation) and statements (Statement), nested like in the source, and the names in them (Ident), declared or used, found like in getDefUseChains. A node has an id, the indices of the children from the root, e.g. 0.1.3, which stays the same as long as the file doesn't change, its kind, a label, its span, its properties and its children. If the file can't be parsed, root is null and errors has the syntax errors.
impure function getProbeTree
input String fileName "A file whose classes are loaded.";
input Boolean prettyPrint = false;
output String tree;
end getProbeTree;
getReplaceableChoices¶
Returns all replaceable choices for a class with choicesAllMatching.
impure function getReplaceableChoices
input TypeName baseClass;
input TypeName parentClass;
input Boolean includePartial = false;
input Boolean sort = false;
output String choices[:, :];
end getReplaceableChoices;
getSettings¶
Returns some settings.
impure function getSettings
output String settings;
end getSettings;
getShortDefinitionBaseClassInformation¶
Returns information about a short class definition.
Returns information about a short class definition: the base class, flow prefix, stream prefix, variability, input/output prefix, and array dimensions.
impure function getShortDefinitionBaseClassInformation
input TypeName className;
output Expression result;
end getShortDefinitionBaseClassInformation;
getShowAnnotations¶
Returns the value of the --showAnnotations flag.
impure function getShowAnnotations
output Boolean show;
end getShowAnnotations;
getSimulationOptions¶
Returns the startTime, stopTime, tolerance, and interval based on the experiment annotation.
impure function getSimulationOptions
input TypeName name;
input Real defaultStartTime = 0.0;
input Real defaultStopTime = 1.0;
input Real defaultTolerance = 1e-6;
input Integer defaultNumberOfIntervals = 500 "May be overridden by defining defaultInterval instead";
input Real defaultInterval = 0.0 "If = 0.0, then numberOfIntervals is used to calculate the step size";
output Real startTime;
output Real stopTime;
output Real tolerance;
output Integer numberOfIntervals;
output Real interval;
end getSimulationOptions;
getSourceFile¶
Returns the filename of the class.
impure function getSourceFile
input TypeName class_;
output String filename "empty on failure";
end getSourceFile;
getTearingMethod¶
Returns the currently used tearing method.
impure function getTearingMethod
output String selected;
end getTearingMethod;
getTempDirectoryPath¶
Returns the current user temporary directory location.
impure function getTempDirectoryPath
output String tempDirectoryPath;
end getTempDirectoryPath;
getTimeStamp¶
Returns the timestamp for a class.
The given class corresponds to a file (or a buffer), with a given last time this file was modified at the time of loading this file. The timestamp along with its String representation is returned.
impure function getTimeStamp
input TypeName cl;
output Real timeStamp;
output String timeStampAsString;
end getTimeStamp;
getTotalModel¶
Saves a model and dependencies to a single string.
Save the className model in a single string, together with all the other classes that it depends upon, directly and indirectly. This file can be later reloaded with the loadString() API function, which loads className and all the other needed classes into memory.
This is useful to allow third parties to run a certain model (e.g. for debugging) without worrying about all the library dependencies.
The classes it depends upon are found by looking up the names used in className, in every class declared in it and in what they use, in the scopes of the new frontend, without instantiating them. className is saved whole, so for a package all its classes are saved, while of the other classes only the ones used and of their packages only the constants used are saved. A class that fails to instantiate is saved with what it refers to, so the saved model fails the same way. The className_total model extending className is not added for packages and functions.
Please note that the resulting file is not a valid Modelica .mo file according to the specification and cannot be loaded in OMEdit - it can only be loaded with loadFile() or passing the file to the compiler on the command line.
impure function getTotalModel
input TypeName className;
input Boolean stripAnnotations = false;
input Boolean stripComments = false;
input Boolean obfuscate = false;
output String result;
end getTotalModel;
getTransitions¶
Returns list of transitions for the given class.
Each transition item contains: from, to, condition, immediate, reset, synchronize, priority.
impure function getTransitions
input TypeName cl;
output String[:, :] transitions;
end getTransitions;
getUsedClassNames¶
Returns the list of class names used in the total program defined by the class.
impure function getUsedClassNames
input TypeName className;
output TypeName classNames[:];
end getUsedClassNames;
getUses¶
Returns the libraries used by a package.
Returns the libraries used by the package based on the uses-annotation, using the format: {{"Library1","Version"},{"Library2","Version"}}.
impure function getUses
input TypeName pack;
output String[:, :] uses;
end getUses;
getVectorizationLimit¶
Returns the vectorization limit used by the old frontend.
impure function getVectorizationLimit
output Integer vectorizationLimit;
end getVectorizationLimit;
getVersion¶
Returns the version of the compiler or a Modelica library.
Returns the version of the compiler if called without an argument, or the version of a loaded Modelica library if the name of the library is given as argument.
impure function getVersion
input TypeName cl = $Code(OpenModelica);
output String version;
end getVersion;
help¶
Display the OpenModelica help text.
function help
input String topic = "topics";
output String helpText;
end help;
iconv¶
Converts a string from one character encoding to another.
See man (3) iconv for more information.
function iconv
input String string;
input String from;
input String to = "UTF-8";
output String result;
end iconv;
importFMU¶
Imports a Functional Mockup Unit.
Example command:
importFMU("A.fmu");
impure function importFMU
input String filename "the fmu file name";
input String workdir = "<default>" "The output directory for imported FMU files. <default> will put the files to current working directory.";
input Integer loglevel = 3 "loglevel_nothing=0;loglevel_fatal=1;loglevel_error=2;loglevel_warning=3;loglevel_info=4;loglevel_verbose=5;loglevel_debug=6";
input Boolean fullPath = false "When true the full output path is returned otherwise only the file name.";
input Boolean debugLogging = false "When true the FMU's debug output is printed.";
input Boolean generateInputConnectors = true "When true creates the input connector pins.";
input Boolean generateOutputConnectors = true "When true creates the output connector pins.";
input TypeName modelName = $Code(Default) "Name of the generated model. If default then the name is auto generated using FMU information.";
output String generatedFileName "Returns the full path of the generated file.";
end importFMU;
importFMUModelDescription¶
Imports modelDescription.xml
Example command:
importFMUModelDescription("A.xml");
impure function importFMUModelDescription
input String filename "the fmu file name";
input String workdir = "<default>" "The output directory for imported FMU files. <default> will put the files to current working directory.";
input Integer loglevel = 3 "loglevel_nothing=0;loglevel_fatal=1;loglevel_error=2;loglevel_warning=3;loglevel_info=4;loglevel_verbose=5;loglevel_debug=6";
input Boolean fullPath = false "When true the full output path is returned otherwise only the file name.";
input Boolean debugLogging = false "When true the FMU's debug output is printed.";
input Boolean generateInputConnectors = true "When true creates the input connector pins.";
input Boolean generateOutputConnectors = true "When true creates the output connector pins.";
output String generatedFileName "Returns the full path of the generated file.";
end importFMUModelDescription;
inferBindings¶
Update bindings for a verification model.
impure function inferBindings
input TypeName path;
output Boolean success;
end inferBindings;
installPackage¶
Installs a package.
Installs the package with the best matching version (or only the specified version if exactMatch is given). The package is installed into ~/.openmodelica/libraries/, which must be in the OPENMODELICALIBRARY. To update the index, call updatePackageIndex().
impure function installPackage
input TypeName pkg;
input String version = "";
input Boolean exactMatch = false;
output Boolean result;
end installPackage;
installWasmToolchain¶
Installs the sysroot wasm external "C" code is compiled against.
Downloads the WebAssembly sysroot (wasi-libc headers, libc.so and the compiler-rt builtins) that the package index's prebuilt wasm modules are built with, unless it is installed already, and returns its path. The wasm-jit target compiles Include sources against it with the system clang. With cxx, libc++'s headers and libc++.so are added, for C++ code compiled with -fwasm-exceptions. Returns the empty string if the index has none or the download fails.
impure function installWasmToolchain
input Boolean cxx = false "Also libc++, for C++ code";
output String sysroot;
end installWasmToolchain;
instantiateModel¶
Instantiates a model and returns the flattened model.
impure function instantiateModel
input TypeName className;
output String result;
end instantiateModel;
isBlock¶
Checks if a given class is a block.
impure function isBlock
input TypeName cl;
output Boolean b;
end isBlock;
isClass¶
Checks if a given class is a class.
impure function isClass
input TypeName cl;
output Boolean b;
end isClass;
isConnector¶
Checks if a given class is a connector or expandable connector.
impure function isConnector
input TypeName cl;
output Boolean b;
end isConnector;
isConstant¶
Checks if a component in a class is a constant.
impure function isConstant
input TypeName componentName;
input TypeName className;
output Boolean result;
end isConstant;
isEnumeration¶
Checks if a given class is an enumeration.
impure function isEnumeration
input TypeName cl;
output Boolean b;
end isEnumeration;
isExperiment¶
Checks if a class is an experiment.
An experiment is defined as a non-partial model or block having annotation experiment(StopTime=...)
impure function isExperiment
input TypeName name;
output Boolean res;
end isExperiment;
isExtendsModifierFinal¶
Returns whether a modifier on an extends clause is final or not.
impure function isExtendsModifierFinal
input TypeName className;
input TypeName extendsName;
input TypeName modifierName;
output Boolean isFinal;
end isExtendsModifierFinal;
isFunction¶
Checks if a given class is a function.
impure function isFunction
input TypeName cl;
output Boolean b;
end isFunction;
isModel¶
Checks if a given class is a model.
impure function isModel
input TypeName cl;
output Boolean b;
end isModel;
isOperator¶
Checks if a given class is an operator.
impure function isOperator
input TypeName cl;
output Boolean b;
end isOperator;
isOperatorFunction¶
Checks if a given class is an operator function.
impure function isOperatorFunction
input TypeName cl;
output Boolean b;
end isOperatorFunction;
isOperatorRecord¶
Checks if a given class is an operator record.
impure function isOperatorRecord
input TypeName cl;
output Boolean b;
end isOperatorRecord;
isOptimization¶
Checks if a given class is an optimization.
impure function isOptimization
input TypeName cl;
output Boolean b;
end isOptimization;
isPackage¶
Checks if a given class is a package.
impure function isPackage
input TypeName cl;
output Boolean b;
end isPackage;
isParameter¶
Checks whether a component in a class is a parameter.
impure function isParameter
input TypeName componentName;
input TypeName className;
output Boolean result;
end isParameter;
isPartial¶
Checks if a given class is partial.
impure function isPartial
input TypeName cl;
output Boolean b;
end isPartial;
isPrimitive¶
Checks if a type is primitive.
impure function isPrimitive
input TypeName className;
output Boolean result;
end isPrimitive;
isProtected¶
Checks if a component in a class is protected.
impure function isProtected
input TypeName componentName;
input TypeName className;
output Boolean result;
end isProtected;
isProtectedClass¶
Returns true if the given class c1 has class c2 as one of its protected class.
impure function isProtectedClass
input TypeName cl;
input String c2;
output Boolean b;
end isProtectedClass;
isRecord¶
Checks if a given class is a record.
impure function isRecord
input TypeName cl;
output Boolean b;
end isRecord;
isRedeclare¶
Checks if a given element is a redeclare element.
impure function isRedeclare
input TypeName element;
output Boolean b;
end isRedeclare;
isReplaceable¶
Checks if a given element is replaceable.
impure function isReplaceable
input TypeName element;
output Boolean b;
end isReplaceable;
isShortDefinition¶
Returns true if the given class is defined as a short class.
impure function isShortDefinition
input TypeName class_;
output Boolean isShortCls;
end isShortDefinition;
isType¶
Checks if a given class is a type.
impure function isType
input TypeName cl;
output Boolean b;
end isType;
linearize¶
Creates a model with symbolic linearization matrices.
Creates a model with symbolic linearization matrices.
At stopTime the linearization matrices are evaluated and a modelica model is created.
Usage:¶
linearize(A, stopTime=0.0);
Creates the file in the selected linearization output language (modelica by default) that contains the linearized matrices at stopTime.
The output language can be changed with the command line option --linearizationDumpLanguage e.g., setCommandLineOptions("--linearizationDumpLanguage=modelica")
The arguments of simulate, buildModel and the other simulation calls.
Only className is necessary. An argument that is not given gets its value from the experiment annotation of the class, or of a class that it extends, or else from the default below. The declared values nan(), -1 and "<default>" only mark an argument that is not given.
Argument |
Value if not given |
|---|---|
|
|
|
|
|
( |
|
Not used. If it is given, numberOfIntervals is (stopTime - startTime) / stepSize, rounded down. |
|
|
|
"dassl". With |
|
The name of the class. The result file is |
|
Not used. |
|
"mat". The other formats are "csv", "plt", "arrow" and "empty", which writes no result file. |
|
".*". Only the variables whose full name matches this regular expression go into the result file. |
|
"". Extra flags for the C compiler. |
|
The |
The flags in simflags apply when the simulation executable runs, and they replace the values above: for example, -s=euler replaces method.
impure function linearize
input TypeName className "The model";
input Real startTime = nan() "Start time";
input Real stopTime = nan() "Stop time";
input Integer numberOfIntervals = -1 "Number of intervals";
input Real stepSize = nan() "Interval of the result file";
input Real tolerance = nan() "Integration tolerance";
input String method = "<default>" "Integration method";
input String fileNamePrefix = "<default>" "File name prefix";
input String options = "<default>" "Not used";
input String outputFormat = "<default>" "Result file format";
input String variableFilter = "<default>" "Variables to store";
input String cflags = "<default>" "Flags for the C compiler";
input String simflags = "<default>" "Flags for the simulation";
output String linearizationResult;
end linearize;
list¶
Lists the contents of the given class, or all loaded classes.
Pretty-prints a class definition.
Syntax¶
list(Modelica.Math.sin)list(Modelica.Math.sin,interfaceOnly=true)
Description¶
list() pretty-prints the whole of the loaded AST while list(className) lists a class and its children. It keeps all annotations and comments intact but strips out any comments and normalizes white-space.
list(className,interfaceOnly=true) works on functions and pretty-prints only the interface parts (annotations and protected sections removed). String-comments on public variables are kept.
If the specified class does not exist (or is not a function when interfaceOnly is given), an empty string is returned.
impure function list
input TypeName class_ = $Code(AllLoadedClasses);
input Boolean interfaceOnly = false;
input Boolean shortOnly = false "only short class definitions";
input ExportKind exportKind = ExportKind.Absyn;
output String contents;
end list;
listFile¶
Lists the contents of the file given by the class.
Lists the contents of the file given by the class. See also list().
impure function listFile
input TypeName class_;
input Boolean nestedClasses = true;
output String contents;
end listFile;
listVariables¶
Lists the names of the active variables in the scripting environment.
impure function listVariables
output TypeName variables[:];
end listVariables;
loadClassContentString¶
Loads class elements from a string and inserts them into the given loaded class.
Loads class content from a string and inserts it into the given loaded class with an optional position offset for graphical annotations. The existing class must be a long class definition, either normal or class extends. The content is merged according to the following rules:
public/protected sections: Merged with the last public/protected section if the protection is the same.
equation sections: Merged with the last equation section if it's the same type of equation section (normal/initial).
external declaration: The new declaration overwrites the old.
annotations: The new annotation is merged with the old.
Any section not merged is added after the last section of the same type, or where they would normally be placed if no such section exists (i.e. public/protected first, then equations, etc).
Example:
loadClassContentString(" Real y; algorithm y = x; ", P.M);
If an offset is given it will be applied to the graphical annotations on the loaded content before it's merged into the class, for example Placement annotations on components.
impure function loadClassContentString
input String data;
input TypeName className;
input Integer offsetX = 0;
input Integer offsetY = 0;
output Boolean success;
end loadClassContentString;
loadEncryptedPackage¶
Loads an encrypted package.
impure function loadEncryptedPackage
input String fileName;
input String workdir = "<default>" "The output directory for imported encrypted files. <default> will put the files to current working directory.";
input Boolean skipUnzip = false "Skips the unzip of .mol if true. In that case we expect the files are already extracted e.g., because of parseEncryptedPackage() call.";
input Boolean uses = true;
input Boolean notify = true "Give a notification of the libraries and versions that were loaded";
input Boolean requireExactVersion = false "If the version is required to be exact, if there is a uses Modelica(version=\"3.2\"), Modelica 3.2.1 will not match it.";
output Boolean success;
end loadEncryptedPackage;
loadFile¶
Loads a Modelica file (*.mo).
Loads the given file using the given encoding.
Note that if the file basename is package.mo and the parent directory is the top-level class, or if the file is a directory, the library structure is loaded as if loadModel(ClassName) was called. Uses-annotations are respected if uses=true. The main difference from loadModel is that loadFile appends this directory to OPENMODELICALIBRARY (MODELICAPATH in the language specification) (for this call only).
impure function loadFile
input String fileName;
input String encoding = "UTF-8";
input Boolean uses = true;
input Boolean notify = true "Give a notification of the libraries and versions that were loaded";
input Boolean requireExactVersion = false "If the version is required to be exact, if there is a uses Modelica(version=\"3.2\"), Modelica 3.2.1 will not match it.";
input Boolean allowWithin = true "Whether to allow the file to have a within-clause other than 'within;'.";
output Boolean success;
end loadFile;
loadFileInteractive¶
Loads a Modelica file and returns a list of all loaded top-level classes.
impure function loadFileInteractive
input String filename;
input String encoding = "UTF-8";
input Boolean uses = true;
input Boolean notify = true "Give a notification of the libraries and versions that were loaded";
input Boolean requireExactVersion = false "If the version is required to be exact, if there is a uses Modelica(version=\"3.2\"), Modelica 3.2.1 will not match it.";
output TypeName names[:];
end loadFileInteractive;
loadFileInteractiveQualified¶
Loads a Modelica file and returns a list of the top-level classes that were loaded.
impure function loadFileInteractiveQualified
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end loadFileInteractiveQualified;
loadFiles¶
Loads Modelica files (*.mo).
impure function loadFiles
input String[:] fileNames;
input String encoding = "UTF-8";
input Integer numThreads = OpenModelica.Scripting.numProcessors();
input Boolean uses = true;
input Boolean notify = true "Give a notification of the libraries and versions that were loaded";
input Boolean requireExactVersion = false "If the version is required to be exact, if there is a uses Modelica(version=\"3.2\"), Modelica 3.2.1 will not match it.";
input Boolean allowWithin = true "Whether to allow the files to have a within-clause other than 'within;'.";
output Boolean success;
end loadFiles;
loadModel¶
Loads a Modelica library.
Loads a Modelica library.
Syntax¶
loadModel(Modelica)loadModel(Modelica,{"3.2"})
Description¶
loadModel() begins by parsing the getModelicaPath() and looking for candidate packages to load in the given paths (separated by : or ; depending on OS).
The candidate is selected by choosing the one with the highest priority, chosen by looking through the priorityVersion argument to the function. If the version searched for is "default", the following special priority is used: no version name > highest main release > highest pre-release > lexical sort of others (see table below for examples). If none of the searched versions exist, false is returned and an error is added to the buffer.
A top-level package may either be defined in a file ("Modelica 3.2.mo") or directory ("Modelica 3.2/package.mo")
The encoding of any Modelica file in the package is assumed to be UTF-8. Legacy code may contain files in a different encoding. In order to handle this, add a file package.encoding at the top-level of the package, containing a single line with the name of the encoding in it. If your package contains files with mixed encodings and your system iconv supports UTF-8//IGNORE, you can ignore the bad characters in some of the files. You are recommended to convert your files to UTF-8 without byte-order mark.
Priority |
Example |
|---|---|
No version name |
Modelica |
Main release |
Modelica 3.3 |
Pre-release |
Modelica 3.3 Beta 1 |
Non-ordered |
Modelica Trunk |
Bugs¶
If loadModel(Modelica.XXX) is called, loadModel(Modelica) is executed instead, loading the complete library.
impure function loadModel
input TypeName className;
input String[:] priorityVersion = {"default"};
input Boolean notify = false "Give a notification of the libraries and versions that were loaded";
input String languageStandard = "" "Override the set language standard. Parse with the given setting, but do not change it permanently.";
input Boolean requireExactVersion = false "If the version is required to be exact, if there is a uses Modelica(version=\"3.2\"), Modelica 3.2.1 will not match it.";
output Boolean success;
end loadModel;
loadModelica3D¶
Loads Modelica3D.
Usage¶
Modelica3D requires some changes to the standard ModelicaServices in order to work correctly. These changes will make your MultiBody models unable to simulate because they need an object declared as:
inner ModelicaServices.Modelica3D.Controller m3d_control
Example session:
loadModelica3D();getErrorString();
loadString("model DoublePendulum
extends Modelica.Mechanics.MultiBody.Examples.Elementary.DoublePendulum;
inner ModelicaServices.Modelica3D.Controller m3d_control;
end DoublePendulum;");getErrorString();
system("python " + getInstallationDirectoryPath() + "/lib/omlibrary-modelica3d/osg-gtk/dbus-server.py &");getErrorString();
simulate(DoublePendulum);getErrorString();
This API call will load the modified ModelicaServices 3.2.1 so Modelica3D runs. You can also simply call loadModel(ModelicaServices,{"3.2.1 modelica3d"});
You will also need to start an m3d backend to render the results. We hid them in $OPENMODELICAHOME/lib/omlibrary-modelica3d/osg-gtk/dbus-server.py (or blender2.59).
For more information and example models, visit the Modelica3D wiki.
impure function loadModelica3D
input String version = "3.2.1";
output Boolean status;
end loadModelica3D;
loadOMSimulator¶
Loads the OMSimulator DLL from the default path.
impure function loadOMSimulator
output Integer status;
end loadOMSimulator;
loadString¶
Loads Modelica definitions from a string.
Parses the data and merges the resulting AST with the loaded AST. If a filename is given, it is used to provide error messages as if the string was read from a file with the same name.
When merge is true the classes cNew in the file will be merged with the already loaded classes cOld in the following way:
get all the inner class definitions from cOld that were loaded from a different file than itself
append all elements from step 1 to class cNew public list
NOTE: Encoding is deprecated as *ALL* strings are now UTF-8 encoded.
impure function loadString
input String data;
input String filename = "<interactive>";
input String encoding = "UTF-8" "Deprecated as *ALL* strings are now UTF-8 encoded";
input Boolean merge = false "if merge is true the parsed AST is merged with the existing AST,
default to false which means that is replaced, not merged";
input Boolean uses = true;
input Boolean notify = true "Give a notification of the libraries and versions that were loaded";
input Boolean requireExactVersion = false "If the version is required to be exact,
if there is a uses Modelica(version=\"3.2\"),
Modelica 3.2.1 will not match it.";
output Boolean success;
end loadString;
mkdir¶
Creates a directory.
Creates a directory for the given filesystem path (which may be either relative or absolute). Returns true if the directory was created or already exists, otherwise false.
impure function mkdir
input String newDirectory;
output Boolean success;
end mkdir;
modelEquationsUC¶
Extracts the equations needed for data reconciliation of a model with uncertainties.
impure function modelEquationsUC
input TypeName className "the class to extract the equations from";
input String outputFile = "" "the file to write the extracted equations to";
input Boolean dumpSteps = false "print the steps of the extraction";
output String result;
end modelEquationsUC;
modifierToJSON¶
Parses a modifier given as a string and dumps it as JSON.
impure function modifierToJSON
input String modifier;
input Boolean prettyPrint = false;
output String json;
end modifierToJSON;
moo¶
Generates an optimization executable for a model and runs it with the MOO dynamic optimizer.
Builds a dynamic optimization problem from a Modelica/Optimica model like optimize() and solves it with MOO (the executable is run with -moo).
Example command:
moo(A);
The arguments of simulate, buildModel and the other simulation calls.
Only className is necessary. An argument that is not given gets its value from the experiment annotation of the class, or of a class that it extends, or else from the default below. The declared values nan(), -1 and "<default>" only mark an argument that is not given.
Argument |
Value if not given |
|---|---|
|
|
|
|
|
( |
|
Not used. If it is given, numberOfIntervals is (stopTime - startTime) / stepSize, rounded down. |
|
|
|
"dassl". With |
|
The name of the class. The result file is |
|
Not used. |
|
"mat". The other formats are "csv", "plt", "arrow" and "empty", which writes no result file. |
|
".*". Only the variables whose full name matches this regular expression go into the result file. |
|
"". Extra flags for the C compiler. |
|
The |
The flags in simflags apply when the simulation executable runs, and they replace the values above: for example, -s=euler replaces method.
impure function moo
input TypeName className "The model";
input Real startTime = nan() "Start time";
input Real stopTime = nan() "Stop time";
input Integer numberOfIntervals = -1 "Number of intervals";
input Real stepSize = nan() "Interval of the result file";
input Real tolerance = nan() "Integration tolerance";
input String method = "<default>" "Integration method";
input String fileNamePrefix = "<default>" "File name prefix";
input String options = "<default>" "Not used";
input String outputFormat = "<default>" "Result file format";
input String variableFilter = "<default>" "Variables to store";
input String cflags = "<default>" "Flags for the C compiler";
input String simflags = "<default>" "Flags for the simulation";
output String optimizationResults;
end moo;
moveClass¶
Moves a class up or down in a package.
Moves a class up or down depending on the given offset, where a positive offset moves the class down and a negative offset up. The offset is truncated if the resulting index is outside the class list.
It retains the visibility of the class by adding public/protected sections when needed, and merges sections of the same type if the class is moved from a section it was alone in.
Returns true if the move was successful, otherwise false.
impure function moveClass
input TypeName className "the class that should be moved";
input Integer offset "Offset in the class list.";
output Boolean result;
end moveClass;
moveClassToBottom¶
Moves a class to the bottom of its enclosing class.
Returns true if the move was successful, otherwise false.
impure function moveClassToBottom
input TypeName className;
output Boolean result;
end moveClassToBottom;
moveClassToTop¶
Moves a class to the top of its enclosing class.
Returns true if the move was successful, otherwise false.
impure function moveClassToTop
input TypeName className;
output Boolean result;
end moveClassToTop;
newModel¶
Creates a new empty model in the given package.
impure function newModel
input TypeName className;
input TypeName withinPath;
output Boolean success;
end newModel;
ngspicetoModelica¶
Converts ngspice netlist to Modelica code.
The Modelica file is created in the same directory as netlist file.
impure function ngspicetoModelica
input String netlistfileName;
output Boolean success = false;
end ngspicetoModelica;
numProcessors¶
Returns the number of available processors or threads.
Returns the number of processors (if compiled against hwloc) or hardware threads (if using sysconf) available to OpenModelica.
impure function numProcessors
output Integer result;
end numProcessors;
oms_RunFile¶
Simulates a single FMU or SSP model.
impure function oms_RunFile
input String filename;
output Integer status;
end oms_RunFile;
oms_addBus¶
OMSimulator: Adds a bus to a given component.
impure function oms_addBus
input String cref;
output Integer status;
end oms_addBus;
oms_addConnection¶
Adds a new connection between connectors A and B.
impure function oms_addConnection
input String crefA;
input String crefB;
output Integer status;
end oms_addConnection;
oms_addConnector¶
Adds a connector to a given component.
impure function oms_addConnector
input String cref;
input oms_causality causality;
input oms_signal_type type_;
output Integer status;
end oms_addConnector;
oms_addConnectorToBus¶
Adds a connector to a bus.
impure function oms_addConnectorToBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_addConnectorToBus;
oms_addConnectorToTLMBus¶
Adds a connector to a TLM bus.
impure function oms_addConnectorToTLMBus
input String busCref;
input String connectorCref;
input String type_;
output Integer status;
end oms_addConnectorToTLMBus;
oms_addDynamicValueIndicator¶
Adds a dynamic value indicator.
impure function oms_addDynamicValueIndicator
input String signal;
input String lower;
input String upper;
input Real stepSize;
output Integer status;
end oms_addDynamicValueIndicator;
oms_addEventIndicator¶
Adds an event indicator.
impure function oms_addEventIndicator
input String signal;
output Integer status;
end oms_addEventIndicator;
oms_addExternalModel¶
Adds an external model to a TLM system.
impure function oms_addExternalModel
input String cref;
input String path;
input String startscript;
output Integer status;
end oms_addExternalModel;
oms_addSignalsToResults¶
Adds all variables that match the given regex to the result file.
impure function oms_addSignalsToResults
input String cref;
input String regex;
output Integer status;
end oms_addSignalsToResults;
oms_addStaticValueIndicator¶
Adds a static value indicator.
impure function oms_addStaticValueIndicator
input String signal;
input Real lower;
input Real upper;
input Real stepSize;
output Integer status;
end oms_addStaticValueIndicator;
oms_addSubModel¶
Adds a component to a system.
impure function oms_addSubModel
input String cref;
input String fmuPath;
output Integer status;
end oms_addSubModel;
oms_addSystem¶
Adds a (sub-)system to a model or system.
impure function oms_addSystem
input String cref;
input oms_system type_;
output Integer status;
end oms_addSystem;
oms_addTLMBus¶
Adds a TLM bus.
impure function oms_addTLMBus
input String cref;
input oms_tlm_domain domain;
input Integer dimensions;
input oms_tlm_interpolation interpolation;
output Integer status;
end oms_addTLMBus;
oms_addTLMConnection¶
Connects two TLM connectors.
impure function oms_addTLMConnection
input String crefA;
input String crefB;
input Real delay;
input Real alpha;
input Real linearimpedance;
input Real angularimpedance;
output Integer status;
end oms_addTLMConnection;
oms_addTimeIndicator¶
Adds a time indicator.
impure function oms_addTimeIndicator
input String signal;
output Integer status;
end oms_addTimeIndicator;
oms_compareSimulationResults¶
Compares a given signal in two result files.
impure function oms_compareSimulationResults
input String filenameA;
input String filenameB;
input String var;
input Real relTol;
input Real absTol;
output Integer status;
end oms_compareSimulationResults;
oms_copySystem¶
Copies a system.
impure function oms_copySystem
input String source;
input String target;
output Integer status;
end oms_copySystem;
oms_delete¶
Deletes a connector, component, system, or model object.
impure function oms_delete
input String cref;
output Integer status;
end oms_delete;
oms_deleteConnection¶
Deletes the connection between two connectors.
impure function oms_deleteConnection
input String crefA;
input String crefB;
output Integer status;
end oms_deleteConnection;
oms_deleteConnectorFromBus¶
Deletes a connector from a given bus.
impure function oms_deleteConnectorFromBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_deleteConnectorFromBus;
oms_deleteConnectorFromTLMBus¶
Deletes a connector from a given TLM bus.
impure function oms_deleteConnectorFromTLMBus
input String busCref;
input String connectorCref;
output Integer status;
end oms_deleteConnectorFromTLMBus;
oms_export¶
Exports a composite model to a SPP file.
impure function oms_export
input String cref;
input String filename;
output Integer status;
end oms_export;
oms_exportDependencyGraphs¶
Exports the dependency graphs of a given model to dot files.
impure function oms_exportDependencyGraphs
input String cref;
input String initialization;
input String event;
input String simulation;
output Integer status;
end oms_exportDependencyGraphs;
oms_exportSnapshot¶
Lists the SSD representation of a given model, system, or component.
impure function oms_exportSnapshot
input String cref;
output String contents;
output Integer status;
end oms_exportSnapshot;
oms_extractFMIKind¶
Extracts the FMI kind of a given FMU from the file system.
impure function oms_extractFMIKind
input String filename;
output Integer kind;
output Integer status;
end oms_extractFMIKind;
oms_faultInjection¶
Defines a new fault injection block.
impure function oms_faultInjection
input String signal;
input oms_fault_type faultType;
input Real faultValue;
output Integer status;
end oms_faultInjection;
oms_getBoolean¶
Get boolean value of a given signal.
impure function oms_getBoolean
input String cref;
output Boolean value;
output Integer status;
end oms_getBoolean;
oms_getFixedStepSize¶
Gets the fixed step size.
impure function oms_getFixedStepSize
input String cref;
output Real stepSize;
output Integer status;
end oms_getFixedStepSize;
oms_getInteger¶
Get integer value of a given signal.
impure function oms_getInteger
input String cref;
input Integer value;
output Integer status;
end oms_getInteger;
oms_getModelState¶
Gets the model state of the given model cref.
impure function oms_getModelState
input String cref;
output Integer modelState;
output Integer status;
end oms_getModelState;
oms_getReal¶
Get real value.
impure function oms_getReal
input String cref;
output Real value;
output Integer status;
end oms_getReal;
oms_getSolver¶
Gets the selected solver method of the given system.
impure function oms_getSolver
input String cref;
output Integer solver;
output Integer status;
end oms_getSolver;
oms_getStartTime¶
Gets the start time from the model.
impure function oms_getStartTime
input String cref;
output Real startTime;
output Integer status;
end oms_getStartTime;
oms_getStopTime¶
Gets the stop time from the model.
impure function oms_getStopTime
input String cref;
output Real stopTime;
output Integer status;
end oms_getStopTime;
oms_getSubModelPath¶
Returns the path of a given component.
impure function oms_getSubModelPath
input String cref;
output String path;
output Integer status;
end oms_getSubModelPath;
oms_getSystemType¶
Gets the type of a given system.
impure function oms_getSystemType
input String cref;
output Integer type_;
output Integer status;
end oms_getSystemType;
oms_getTolerance¶
Gets the tolerance of a given system or component.
impure function oms_getTolerance
input String cref;
output Real absoluteTolerance;
output Real relativeTolerance;
output Integer status;
end oms_getTolerance;
oms_getVariableStepSize¶
Gets the step size parameters.
impure function oms_getVariableStepSize
input String cref;
output Real initialStepSize;
output Real minimumStepSize;
output Real maximumStepSize;
output Integer status;
end oms_getVariableStepSize;
oms_getVersion¶
Returns the version of the OMSimulator.
impure function oms_getVersion
output String version;
end oms_getVersion;
oms_importFile¶
Imports a composite model from a SSP file.
impure function oms_importFile
input String filename;
output String cref;
output Integer status;
end oms_importFile;
oms_importSnapshot¶
Loads a snapshot to restore a previous model state.
impure function oms_importSnapshot
input String cref;
input String snapshot;
output Integer status;
end oms_importSnapshot;
oms_initialize¶
Initializes a composite model.
impure function oms_initialize
input String cref;
output Integer status;
end oms_initialize;
oms_instantiate¶
Instantiates a given composite model.
impure function oms_instantiate
input String cref;
output Integer status;
end oms_instantiate;
oms_list¶
Lists the SSD representation of a given model, system, or component.
impure function oms_list
input String cref;
output String contents;
output Integer status;
end oms_list;
oms_listUnconnectedConnectors¶
Lists all unconnected connectors of a given system.
impure function oms_listUnconnectedConnectors
input String cref;
output String contents;
output Integer status;
end oms_listUnconnectedConnectors;
oms_loadSnapshot¶
Loads a snapshot to restore a previous model state.
impure function oms_loadSnapshot
input String cref;
input String snapshot;
output String newCref;
output Integer status;
end oms_loadSnapshot;
oms_newModel¶
Creates a new composite model.
impure function oms_newModel
input String cref;
output Integer status;
end oms_newModel;
oms_removeSignalsFromResults¶
Removes all variables that match the given regex from the result file.
impure function oms_removeSignalsFromResults
input String cref;
input String regex;
output Integer status;
end oms_removeSignalsFromResults;
oms_rename¶
Renames a model, system, or component.
impure function oms_rename
input String cref;
input String newCref;
output Integer status;
end oms_rename;
oms_reset¶
Reset the composite model after a simulation run.
impure function oms_reset
input String cref;
output Integer status;
end oms_reset;
oms_setBoolean¶
Sets the value of a given boolean signal.
impure function oms_setBoolean
input String cref;
input Boolean value;
output Integer status;
end oms_setBoolean;
oms_setCommandLineOption¶
Sets special flags.
impure function oms_setCommandLineOption
input String cmd;
output Integer status;
end oms_setCommandLineOption;
oms_setFixedStepSize¶
Sets the fixed step size.
impure function oms_setFixedStepSize
input String cref;
input Real stepSize;
output Integer status;
end oms_setFixedStepSize;
oms_setInteger¶
Sets the value of a given integer signal.
impure function oms_setInteger
input String cref;
input Integer value;
output Integer status;
end oms_setInteger;
oms_setLogFile¶
Redirects logging output to file or std streams.
impure function oms_setLogFile
input String filename;
output Integer status;
end oms_setLogFile;
oms_setLoggingInterval¶
Sets the logging interval of the simulation.
impure function oms_setLoggingInterval
input String cref;
input Real loggingInterval;
output Integer status;
end oms_setLoggingInterval;
oms_setLoggingLevel¶
Enables/disables debug logging.
impure function oms_setLoggingLevel
input Integer logLevel;
output Integer status;
end oms_setLoggingLevel;
oms_setReal¶
Sets the value of a given real signal.
impure function oms_setReal
input String cref;
input Real value;
output Integer status;
end oms_setReal;
oms_setRealInputDerivative¶
Sets the first order derivative of a real input signal.
impure function oms_setRealInputDerivative
input String cref;
input Real value;
output Integer status;
end oms_setRealInputDerivative;
oms_setResultFile¶
Sets the result file of the simulation.
impure function oms_setResultFile
input String cref;
input String filename;
input Integer bufferSize;
output Integer status;
end oms_setResultFile;
oms_setSignalFilter¶
Sets a signal filter.
impure function oms_setSignalFilter
input String cref;
input String regex;
output Integer status;
end oms_setSignalFilter;
oms_setSolver¶
Sets the solver method for the given system.
impure function oms_setSolver
input String cref;
input oms_solver solver;
output Integer status;
end oms_setSolver;
oms_setStartTime¶
Sets the start time of the simulation.
impure function oms_setStartTime
input String cref;
input Real startTime;
output Integer status;
end oms_setStartTime;
oms_setStopTime¶
Sets the stop time of the simulation.
impure function oms_setStopTime
input String cref;
input Real stopTime;
output Integer status;
end oms_setStopTime;
oms_setTLMPositionAndOrientation¶
Sets initial position and orientation for a TLM 3D interface.
impure function oms_setTLMPositionAndOrientation
input String cref;
input Real x1;
input Real x2;
input Real x3;
input Real A11;
input Real A12;
input Real A13;
input Real A21;
input Real A22;
input Real A23;
input Real A31;
input Real A32;
input Real A33;
output Integer status;
end oms_setTLMPositionAndOrientation;
oms_setTLMSocketData¶
Sets data for TLM socket communication.
impure function oms_setTLMSocketData
input String cref;
input String address;
input Integer managerPort;
input Integer monitorPort;
output Integer status;
end oms_setTLMSocketData;
oms_setTempDirectory¶
Sets new temp directory.
impure function oms_setTempDirectory
input String newTempDir;
output Integer status;
end oms_setTempDirectory;
oms_setTolerance¶
Sets the tolerance for a given model or system.
impure function oms_setTolerance
input String cref;
input Real absoluteTolerance;
input Real relativeTolerance;
output Integer status;
end oms_setTolerance;
oms_setVariableStepSize¶
Sets the step size parameters for methods with stepsize control.
impure function oms_setVariableStepSize
input String cref;
input Real initialStepSize;
input Real minimumStepSize;
input Real maximumStepSize;
output Integer status;
end oms_setVariableStepSize;
oms_setWorkingDirectory¶
Sets a new working directory.
impure function oms_setWorkingDirectory
input String newWorkingDir;
output Integer status;
end oms_setWorkingDirectory;
oms_simulate¶
Simulates a composite model.
impure function oms_simulate
input String cref;
output Integer status;
end oms_simulate;
oms_stepUntil¶
Simulates a composite model until a given time value.
impure function oms_stepUntil
input String cref;
input Real stopTime;
output Integer status;
end oms_stepUntil;
oms_terminate¶
Terminates a given composite model.
impure function oms_terminate
input String cref;
output Integer status;
end oms_terminate;
optimize¶
Generates an optimization executable for a Modelica/Optimica model and runs it.
Optimizes a Modelica/Optimica model by generating C code, building it and running the optimization executable.
Example command:
optimize(A);
The arguments of simulate, buildModel and the other simulation calls.
Only className is necessary. An argument that is not given gets its value from the experiment annotation of the class, or of a class that it extends, or else from the default below. The declared values nan(), -1 and "<default>" only mark an argument that is not given.
Argument |
Value if not given |
|---|---|
|
|
|
|
|
( |
|
Not used. If it is given, numberOfIntervals is (stopTime - startTime) / stepSize, rounded down. |
|
|
|
"dassl". With |
|
The name of the class. The result file is |
|
Not used. |
|
"mat". The other formats are "csv", "plt", "arrow" and "empty", which writes no result file. |
|
".*". Only the variables whose full name matches this regular expression go into the result file. |
|
"". Extra flags for the C compiler. |
|
The |
The flags in simflags apply when the simulation executable runs, and they replace the values above: for example, -s=euler replaces method.
impure function optimize
input TypeName className "The model";
input Real startTime = nan() "Start time";
input Real stopTime = nan() "Stop time";
input Integer numberOfIntervals = -1 "Number of intervals";
input Real stepSize = nan() "Interval of the result file";
input Real tolerance = nan() "Integration tolerance";
input String method = "<default>" "Integration method";
input String fileNamePrefix = "<default>" "File name prefix";
input String options = "<default>" "Not used";
input String outputFormat = "<default>" "Result file format";
input String variableFilter = "<default>" "Variables to store";
input String cflags = "<default>" "Flags for the C compiler";
input String simflags = "<default>" "Flags for the simulation";
output String optimizationResults;
end optimize;
parseEncryptedPackage¶
Parses an encrypted package and returns the names of the parsed classes.
impure function parseEncryptedPackage
input String fileName;
input String workdir = "<default>" "The output directory for imported encrypted files. <default> will put the files to current working directory.";
output TypeName names[:];
end parseEncryptedPackage;
parseFile¶
Parses a Modelica file and returns the parsed classes.
impure function parseFile
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end parseFile;
parseString¶
Parses a string containing Modelica definitions and returns the parsed classes.
impure function parseString
input String data;
input String filename = "<interactive>";
output TypeName names[:];
end parseString;
plot¶
Displays a plot with selected variables using OMPlot.
Returns true on success.
Example command sequences:
simulate(A); plot({x,y,z});simulate(A); plot(x, externalWindow=true);simulate(A,fileNamePrefix="B"); simulate(C); plot(z,fileName="B.mat",legendPosition=none);simulate(A); plot({b,x}, stack=true);
impure function plot
input VariableNames vars "The variables you want to plot";
input Boolean externalWindow = false "Opens the plot in a new plot window";
input String fileName = "<default>" "The filename containing the variables. <default> will read the last simulation result";
input String title = "" "This text will be used as the diagram title.";
input String grid = "simple" "Sets the grid for the plot i.e., simple, detailed, none or xonly.";
input Boolean logX = false "Determines whether or not the horizontal axis is logarithmically scaled.";
input Boolean logY = false "Determines whether or not the vertical axis is logarithmically scaled.";
input String xLabel = "time" "This text will be used as the horizontal label in the diagram.";
input String yLabel = "" "This text will be used as the left vertical label in the diagram.";
input Real xRange[2] = {0.0, 0.0} "Determines the horizontal interval that is visible in the diagram. {0,0} will select a suitable range.";
input Real yRange[2] = {0.0, 0.0} "Determines the left vertical interval that is visible in the diagram. {0,0} will select a suitable range.";
input Real curveWidth = 1.0 "Sets the width of the curve.";
input Integer curveStyle = 1 "Sets the style of the curve. SolidLine=1, DashLine=2, DotLine=3, DashDotLine=4, DashDotDotLine=5, Sticks=6, Steps=7.";
input String legendPosition = "top" "Sets the POSITION of the legend i.e., left, right, top, bottom, none.";
input String footer = "" "This text will be used as the diagram footer.";
input Boolean autoScale = true "Use auto scale while plotting.";
input Boolean forceOMPlot = false "if true launches OMPlot and doesn't call callback function even if it is defined.";
input String yAxis = "L" "Sets the variable to be plotted on the left (L) or right (R) y-axis.";
input String yLabelRight = "" "This text will be used as the right vertical label in the diagram.";
input Real yRangeRight[2] = {0.0, 0.0} "Determines the right vertical interval that is visible in the diagram. {0,0} will select a suitable range.";
input Boolean stack = false "Draws each curve in a lane of its own, one below the other.";
output Boolean success "Returns true on success";
end plot;
plotAll¶
Displays a plot with all variables using OMPlot.
Works in the same way as plot(), but does not accept any variable names as input. Instead, all variables are part of the plot window.
Example command sequences:
simulate(A); plotAll();simulate(A); plotAll(externalWindow=true);simulate(A, fileNamePrefix="B"); simulate(C); plotAll(x, fileName="B.mat");
impure function plotAll
input Boolean externalWindow = false "Opens the plot in a new plot window";
input String fileName = "<default>" "The filename containing the variables. <default> will read the last simulation result";
input String title = "" "This text will be used as the diagram title.";
input String grid = "simple" "Sets the grid for the plot i.e., simple, detailed, none or xonly.";
input Boolean logX = false "Determines whether or not the horizontal axis is logarithmically scaled.";
input Boolean logY = false "Determines whether or not the vertical axis is logarithmically scaled.";
input String xLabel = "time" "This text will be used as the horizontal label in the diagram.";
input String yLabel = "" "This text will be used as the left vertical label in the diagram.";
input Real xRange[2] = {0.0, 0.0} "Determines the horizontal interval that is visible in the diagram. {0,0} will select a suitable range.";
input Real yRange[2] = {0.0, 0.0} "Determines the left vertical interval that is visible in the diagram. {0,0} will select a suitable range.";
input Real curveWidth = 1.0 "Sets the width of the curve.";
input Integer curveStyle = 1 "Sets the style of the curve. SolidLine=1, DashLine=2, DotLine=3, DashDotLine=4, DashDotDotLine=5, Sticks=6, Steps=7.";
input String legendPosition = "top" "Sets the POSITION of the legend i.e., left, right, top, bottom, none.";
input String footer = "" "This text will be used as the diagram footer.";
input Boolean autoScale = true "Use auto scale while plotting.";
input Boolean forceOMPlot = false "if true launches OMPlot and doesn't call callback function even if it is defined.";
input String yAxis = "L" "Sets the variable to be plotted on the left (L) or right (R) y-axis.";
input String yLabelRight = "" "This text will be used as the right vertical label in the diagram.";
input Real yRangeRight[2] = {0.0, 0.0} "Determines the right vertical interval that is visible in the diagram. {0,0} will select a suitable range.";
input Boolean stack = false "Draws each curve in a lane of its own, one below the other.";
output Boolean success "Returns true on success";
end plotAll;
plotParametric¶
Displays a parametric plot with two variables using OMPlot.
Returns true on success.
Example command sequences:
simulate(A); plotParametric(x,y);
simulate(A); plotParametric(x,y, externalWindow=true);
impure function plotParametric
input VariableName xVariable;
input VariableName yVariable;
input Boolean externalWindow = false "Opens the plot in a new plot window";
input String fileName = "<default>" "The filename containing the variables. <default> will read the last simulation result";
input String title = "" "This text will be used as the diagram title.";
input String grid = "simple" "Sets the grid for the plot i.e., simple, detailed, none or xonly.";
input Boolean logX = false "Determines whether or not the horizontal axis is logarithmically scaled.";
input Boolean logY = false "Determines whether or not the vertical axis is logarithmically scaled.";
input String xLabel = "" "This text will be used as the horizontal label in the diagram.";
input String yLabel = "" "This text will be used as the left vertical label in the diagram.";
input Real xRange[2] = {0.0, 0.0} "Determines the horizontal interval that is visible in the diagram. {0,0} will select a suitable range.";
input Real yRange[2] = {0.0, 0.0} "Determines the left vertical interval that is visible in the diagram. {0,0} will select a suitable range.";
input Real curveWidth = 1.0 "Sets the width of the curve.";
input Integer curveStyle = 1 "Sets the style of the curve. SolidLine=1, DashLine=2, DotLine=3, DashDotLine=4, DashDotDotLine=5, Sticks=6, Steps=7.";
input String legendPosition = "top" "Sets the POSITION of the legend i.e., left, right, top, bottom, none.";
input String footer = "" "This text will be used as the diagram footer.";
input Boolean autoScale = true "Use auto scale while plotting.";
input Boolean forceOMPlot = false "if true launches OMPlot and doesn't call callback function even if it is defined.";
input String yAxis = "L" "Sets the variable to be plotted on the left (L) or right (R) y-axis.";
input String yLabelRight = "" "This text will be used as the right vertical label in the diagram.";
input Real yRangeRight[2] = {0.0, 0.0} "Determines the right vertical interval that is visible in the diagram. {0,0} will select a suitable range.";
output Boolean success "Returns true on success";
end plotParametric;
previous_saveTotalModel¶
Saves a model and dependencies to a single file, the previous way.
The previous implementation of saveTotalModel(), which finds the classes className depends upon with the dependency analysis of the old frontend. It is kept for comparison for now and will be removed.
impure function previous_saveTotalModel
input String fileName;
input TypeName className;
input Boolean stripAnnotations = false;
input Boolean stripComments = false;
input Boolean obfuscate = false;
output Boolean success;
end previous_saveTotalModel;
qualifyPath¶
Returns the fully qualified path for the given path in a class.
impure function qualifyPath
input TypeName classPath;
input TypeName path;
output TypeName qualifiedPath;
end qualifyPath;
readFile¶
Returns the contents of a file.
Returns the contents of a file as a string or an empty string if the file couldn't be read. If the file couldn't be read an error message is emitted which can be viewed with getErrorString().
impure function readFile
input String fileName;
output String contents;
end readFile;
readSimulationResult¶
Reads a result file, returning a matrix corresponding to the variables and size given.
impure function readSimulationResult
input String filename;
input VariableNames variables "e.g. {a.b, a[1].b[3].c}, or a single VariableName";
input Integer size = 0 "0=read any size... If the size is not the same as the result-file, this function fails";
output Real result[:, :];
end readSimulationResult;
readSimulationResultSize¶
Returns the number of intervals that are present in the output file.
impure function readSimulationResultSize
input String fileName;
output Integer sz;
end readSimulationResultSize;
readSimulationResultVars¶
Returns the variables in a simulation results file.
Takes a simulation results file and returns the variables stored in it. These names can be used with e.g. val() or plot()
If readParameters is true, parameter names are also returned.
If openmodelicaStyle is true, the stored variable names are converted to the canonical form used by OpenModelica variables (a.der(b) becomes der(a.b), and so on).
impure function readSimulationResultVars
input String fileName;
input Boolean readParameters = true;
input Boolean openmodelicaStyle = false;
output String[:] vars;
end readSimulationResultVars;
realpath¶
Get full path name of file or directory name
Return the canonicalized absolute pathname. Similar to realpath(3), but with the safety of Modelica strings.
impure function realpath
input String name "Absolute or relative file or directory name";
output String fullName "Full path of 'name'";
end realpath;
reduceTerms¶
Calls buildModel with the --reduceTerms flag enabled.
impure function reduceTerms
input TypeName className "the class that should be built";
input Real startTime = 0.0 "the start time of the simulation. <default> = 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Integer numberOfIntervals = 500 "number of intervals in the result file. <default> = 500";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default> = 1e-6";
input String method = "dassl" "integration method used for simulation. <default> = dassl";
input String fileNamePrefix = "" "fileNamePrefix. <default> = \"\"";
input String options = "" "options. <default> = \"\"";
input String outputFormat = "mat" "Format for the result file. <default> = \"mat\"";
input String variableFilter = ".*" "Only variables fully matching the regexp are stored in the result file. <default> = \".*\"";
input String cflags = "" "cflags. <default> = \"\"";
input String simflags = "" "simflags. <default> = \"\"";
input String labelstoCancel = "";
output String[2] buildModelResults;
end reduceTerms;
refactorClass¶
Updates old graphical annotations to Modelica standard ones in a class.
impure function refactorClass
input TypeName className;
output String result;
end refactorClass;
refactorDiagramAnnotation¶
Updates an old Diagram annotation to a Modelica standard one in the given class.
impure function refactorDiagramAnnotation
input TypeName className;
output Expression result;
end refactorDiagramAnnotation;
refactorIconAnnotation¶
Updates an old Icon annotation to a Modelica standard one in the given class.
impure function refactorIconAnnotation
input TypeName className;
output Expression result;
end refactorIconAnnotation;
regex¶
Matches a string with a regular expression and returns the result.
Sets the error buffer and returns -1 if the regex does not compile.
The returned result is the same as POSIX regex():
The first value is the complete matched string.
The rest are the substrings that you wanted.
For example:
regex(lorem," \([A-Za-z]*\) \([A-Za-z]*\) ",maxMatches=3)
=> {" ipsum dolor ","ipsum","dolor"}
This means if you have n groups, you want maxMatches=n+1.
function regex
input String str;
input String re;
input Integer maxMatches = 1 "The maximum number of matches that will be returned";
input Boolean extended = true "Use POSIX extended or regular syntax";
input Boolean caseInsensitive = false;
output Integer numMatches "-1 is an error, 0 means no match, else returns a number 1..maxMatches";
output String matchedSubstrings[maxMatches] "unmatched strings are returned as empty";
end regex;
regexBool¶
Returns true if the string matches the regular expression.
function regexBool
input String str;
input String re;
input Boolean extended = true "Use POSIX extended or regular syntax";
input Boolean caseInsensitive = false;
output Boolean matches;
end regexBool;
regularFileExists¶
Returns whether the given file exists or not.
impure function regularFileExists
input String fileName;
output Boolean exists;
end regularFileExists;
releaseModelInstanceReference¶
Releases a handle returned by getModelInstanceReference or getModelInstanceAnnotationReference. Returns true on success.
impure function releaseModelInstanceReference
input Integer handle;
output Boolean success;
end releaseModelInstanceReference;
reloadClass¶
Reloads the file associated with the given loaded class.
Given an existing, loaded class in the compiler, compare the time stamp of the loaded class with the time stamp (mtime) of the file it was loaded from. If these differ, parse the file and merge it with the AST.
impure function reloadClass
input TypeName name;
input String encoding = "UTF-8";
output Boolean success;
end reloadClass;
remove¶
Removes a file or directory.
Removes the file or directory with the given filesystem path (which may be either relative or absolute). Returns true if the file was successfully removed, otherwise false.
impure function remove
input String path;
output Boolean success "Returns true on success.";
end remove;
removeComponentModifiers¶
Removes the component modifiers.
impure function removeComponentModifiers
input TypeName class_;
input String componentName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeComponentModifiers;
removeElementModifiers¶
Removes the element (component or short class) modifiers.
impure function removeElementModifiers
input TypeName className;
input String componentName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeElementModifiers;
removeExtendsModifiers¶
Removes the extends modifiers of a class.
impure function removeExtendsModifiers
input TypeName className;
input TypeName baseClassName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeExtendsModifiers;
renameClass¶
Renames a class and updates references to it.
Renames a class and updates references to it in the loaded classes. Returns a list of classes that were changed.
impure function renameClass
input TypeName oldName "The path of the class to rename.";
input TypeName newName "The new non-qualified name of the class.";
output TypeName[:] result;
end renameClass;
renameComponent¶
Renames a component and updates references to it.
Renames a component and updates references to it in the loaded classes. Returns a list of classes that were changed.
impure function renameComponent
input TypeName classPath;
input VariableName oldName;
input VariableName newName;
output TypeName[:] result;
end renameComponent;
renameComponentInClass¶
Renames a component in a class.
Renames a component only in the given class. Returns the name of the class if successful.
impure function renameComponentInClass
input TypeName classPath;
input VariableName oldName;
input VariableName newName;
output TypeName[:] result;
end renameComponentInClass;
reopenStandardStream¶
Changes which file is associated with a standard stream.
impure function reopenStandardStream
input StandardStream _stream;
input String filename;
output Boolean success;
end reopenStandardStream;
restoreAST¶
Restores an AST that was previously stored with storeAST.
impure function restoreAST
input Integer id;
output Boolean success;
end restoreAST;
reverseLookup¶
Searches for uses of the given name in either all loaded classes or a given class. Returns a JSON array containing the name and source location for each match.
If exactMatch is true then only names that reference the same element is considered a match, otherwise names that reference elements inside that element are also included. I.e. reverseLookup(A, exactMatch = false) will match both A and A.B, while reverseLookup(A, exactMatch = true) will match A but not A.B.
impure function reverseLookup
input TypeName name;
input TypeName scope = $Code(AllLoadedClasses);
input Boolean exactMatch = true;
input Boolean prettyPrint = false;
output String matches;
end reverseLookup;
rewriteBlockCall¶
Function for property modeling, transforms block calls into instantiations for a loaded model
An extension for modeling requirements in Modelica. Rewrites block calls as block instantiations.
impure function rewriteBlockCall
input TypeName className;
input TypeName inDefs;
output Boolean success;
end rewriteBlockCall;
runConversionScript¶
Runs a conversion script on a selected package.
impure function runConversionScript
input TypeName packageToConvert;
input String scriptFile;
output Boolean success;
end runConversionScript;
runScript¶
Runs the mos-script specified by the filename.
impure function runScript
input String fileName "*.mos";
output String result;
end runScript;
runScriptParallel¶
Runs multiple scripts in parallel.
As runScript, but runs the commands in parallel.
If useThreads=false (default), the script will be run in an empty environment (same as running a new omc process) with default config flags.
If useThreads=true (experimental), the scripts will run in parallel in the same address space and with the same environment (which will not be updated).
impure function runScriptParallel
input String scripts[:];
input Integer numThreads = numProcessors();
input Boolean useThreads = false;
output Boolean results[:];
end runScriptParallel;
save¶
Saves a class to the file(s) it's defined in.
impure function save
input TypeName className;
output Boolean success;
end save;
saveAll¶
Saves the entire loaded AST to file.
impure function saveAll
input String fileName;
output Boolean success;
end saveAll;
saveModel¶
Saves a loaded model to the given file.
impure function saveModel
input String fileName;
input TypeName className;
output Boolean success;
end saveModel;
saveTotalModel¶
Saves a model and dependencies to a single file.
Save the className model in a single file, together with all the other classes that it depends upon, directly and indirectly. This file can be later reloaded with the loadFile() API function, which loads className and all the other needed classes into memory.
This is useful to allow third parties to run a certain model (e.g. for debugging) without worrying about all the library dependencies.
The classes it depends upon are found by looking up the names used in className, in every class declared in it and in what they use, in the scopes of the new frontend, without instantiating them. className is saved whole, so for a package all its classes are saved, while of the other classes only the ones used and of their packages only the constants used are saved. A class that fails to instantiate is saved with what it refers to, so the saved model fails the same way. The className_total model extending className is not added for packages and functions.
Please note that the resulting file is not a valid Modelica .mo file according to the specification and cannot be loaded in OMEdit - it can only be loaded with loadFile() or passing the file to the compiler on the command line.
impure function saveTotalModel
input String fileName;
input TypeName className;
input Boolean stripAnnotations = false;
input Boolean stripComments = false;
input Boolean obfuscate = false;
output Boolean success;
end saveTotalModel;
saveTotalModelDebug¶
Saves a model and dependencies to a single file using a heuristic.
Saves the className model in a single file, together with all other classes that it depends on.
This function uses a naive heuristic based on which identifiers are used and might save things which are not actually used, and is meant to be used in cases where the normal saveTotalModel() fails.
impure function saveTotalModelDebug
input String filename;
input TypeName className;
input Boolean stripAnnotations = false;
input Boolean stripComments = false;
input Boolean obfuscate = false;
output Boolean success;
end saveTotalModelDebug;
saveTotalSCode¶
Alias for saveTotalModel
searchClassNames¶
Searches for a string in the loaded classes.
Returns a list of classes whose name contains searchText. If findInText = true then classes whose text contains searchText is also returned.
Example command:
searchClassNames("ground");
searchClassNames("ground", true);
impure function searchClassNames
input String searchText;
input Boolean findInText = false;
output TypeName classNames[:];
end searchClassNames;
setAnnotationVersion¶
Sets the annotation version.
impure function setAnnotationVersion
input String annotationVersion;
output Boolean success;
end setAnnotationVersion;
setCFlags¶
Sets the C compiler flags (CFLAGS) used for simulation code.
Sets the CFLAGS passed to the C compiler. Remember to add -fPIC if you are on a 64-bit platform. If you want to see the defaults before you modify this variable, check the output of getCFlags(). ${SIM_OR_DYNLOAD_OPT_LEVEL} can be used to get a default lower optimization level for dynamically loaded functions. And ${MODELICAUSERCFLAGS} is nice to add so you can easily modify the CFLAGS later by using an environment variable.
impure function setCFlags
input String inString;
output Boolean success;
end setCFlags;
setCXXCompiler¶
Sets the C++ compiler (CXX) used for simulation code.
impure function setCXXCompiler
input String compiler;
output Boolean success;
end setCXXCompiler;
setCheapMatchingAlgorithm¶
Sets the cheap matching algorithm.
Sets the cheap matching algorithm used by the backend. Same as calling the compiler with the --cheapmatchingAlgorithm flag.
Example input: 3
impure function setCheapMatchingAlgorithm
input Integer matchingAlgorithm;
output Boolean success;
end setCheapMatchingAlgorithm;
setClassComment¶
Sets a class comment.
impure function setClassComment
input TypeName class_;
input String filename;
output Boolean success;
end setClassComment;
setCommandLineOptions¶
Sets command line options for the compiler.
Takes a space separated list of command line options as input, with the same format as when calling the compiler on the command line. Call the compiler with --help for a list of available options.
Example input: --showErrorMessages -d=failtrace
impure function setCommandLineOptions
input String options;
output Boolean success;
end setCommandLineOptions;
setCompiler¶
Sets the C compiler (CC) used for simulation code.
impure function setCompiler
input String compiler;
output Boolean success;
end setCompiler;
setCompilerFlags¶
Same as setCFlags.
impure function setCompilerFlags
input String compilerFlags;
output Boolean success;
end setCompilerFlags;
setComponentComment¶
Sets the comment on a component.
impure function setComponentComment
input TypeName className;
input TypeName componentName;
input String comment;
output Boolean success;
end setComponentComment;
setComponentCondition¶
Sets the condition of a component in a class. An empty string removes the condition.
impure function setComponentCondition
input TypeName className;
input TypeName componentName;
input String condition;
output Boolean success;
end setComponentCondition;
setComponentDimensions¶
Sets the array dimensions of a component.
impure function setComponentDimensions
input TypeName className;
input TypeName componentName;
input Expression dimensions;
output Boolean success;
end setComponentDimensions;
setComponentModifierValue¶
Deprecated; alias for setElementModifierValue.
setComponentProperties¶
Sets the properties of a component in a class.
The prefixArray argument is an array of 4 or 5 values: final, flow, stream (optional), protected, replaceable.
impure function setComponentProperties
input TypeName className;
input TypeName componentName;
input Boolean[:] prefixArray;
input String[1] variability;
input Boolean[2] innerOuter;
input String[1] direction;
output Boolean success;
end setComponentProperties;
setConnectionComment¶
Sets the description string on a connect equation in the given class.
impure function setConnectionComment
input TypeName className;
input VariableName connector1;
input VariableName connector2;
input String comment;
output Boolean success;
end setConnectionComment;
setDebugFlags¶
Sets compiler debug flags.
Calling the compiler with --help=debug will list all debug flags and what they do. The flags are given as a comma separated string. Flags can be disabled by prefixing them with -.
Example input: failtrace,-noevalfunc
impure function setDebugFlags
input String debugFlags;
output Boolean success;
end setDebugFlags;
setDefaultOpenCLDevice¶
Sets the default OpenCL device to be used. 0 selects one automatically.
impure function setDefaultOpenCLDevice
input Integer defdevid;
output Boolean success;
end setDefaultOpenCLDevice;
setDocumentationAnnotation¶
Sets the Documentation annotation in a class.
The existing Documentation annotation of the class is overwritten, so an empty argument for e.g. revisions means that an existing revisions annotation is removed.
impure function setDocumentationAnnotation
input TypeName class_;
input String info = "";
input String revisions = "";
output Boolean bool;
end setDocumentationAnnotation;
setElementAnnotation¶
Sets the annotation on a component or class element.
impure function setElementAnnotation
input TypeName elementName;
input ExpressionOrModification annotationMod;
output Boolean success;
end setElementAnnotation;
setElementModifierValue¶
Sets a modifier on an element in a class definition.
impure function setElementModifierValue
input TypeName className;
input TypeName elementName;
input ExpressionOrModification modifier;
output Boolean success;
end setElementModifierValue;
setElementType¶
Changes the type of a component or short class element.
impure function setElementType
input TypeName elementName;
input VariableName typeName;
output Boolean success;
end setElementType;
setEnvironmentVar¶
Sets the value of the given environment variable.
impure function setEnvironmentVar
input String var;
input String value;
output Boolean success;
end setEnvironmentVar;
setExtendsModifier¶
Sets a modifier on an extends clause in a class definition.
impure function setExtendsModifier
input TypeName className;
input TypeName extendsName;
input ExpressionOrModification modifier;
output Boolean success;
end setExtendsModifier;
setExtendsModifierValue¶
Sets a modifier on an element in an extends clause in a class.
Example:
package P
model M
extends A.B(a = 1.0, x(z = 2.0));
end M;
end P;
setExtendsModifierValue(P.M, A.B, x.y, $Code((start = 3.0))) =>
package P
model M
extends A.B(a = 1.0, x(z = 2.0, y(start = 3.0)));
end M;
end P;
impure function setExtendsModifierValue
input TypeName className;
input TypeName extendsName;
input TypeName elementName;
input ExpressionOrModification modifier;
output Boolean success;
end setExtendsModifierValue;
setIndexReductionMethod¶
Sets the index reduction method.
Sets the index reduction method used by the backend after the pre optimization modules. Call the compiler with --help=optmodules for more information about what methods are available.
Example input: dynamicStateSelection
impure function setIndexReductionMethod
input String method;
output Boolean success;
end setIndexReductionMethod;
setInitXmlStartValue¶
Sets the start value for a variable in an initialization file.
Requires xsltproc from libxslt (included in the OpenModelica installer for Windows).
impure function setInitXmlStartValue
input String fileName;
input String variableName;
input String startValue;
input String outputFile;
output Boolean success = false;
end setInitXmlStartValue;
setInstallationDirectoryPath¶
Sets the OPENMODELICAHOME environment variable.
Use this method instead of setEnvironmentVar.
impure function setInstallationDirectoryPath
input String installationDirectoryPath;
output Boolean success;
end setInstallationDirectoryPath;
setLanguageStandard¶
Sets the Modelica Language Standard.
impure function setLanguageStandard
input String inVersion;
output Boolean success;
end setLanguageStandard;
setLinker¶
Sets the linker (LINK) used for simulation code.
impure function setLinker
input String linker;
output Boolean success;
end setLinker;
setLinkerFlags¶
Sets the linker flags (LDFLAGS) used for simulation code.
impure function setLinkerFlags
input String linkerFlags;
output Boolean success;
end setLinkerFlags;
setMatchingAlgorithm¶
Sets the matching algorithm.
Sets the matching algorithm used by the backend after the pre optimization modules. Call the compiler with --help=optmodules for more information about what algorithms are available.
Example input: PFPlus
impure function setMatchingAlgorithm
input String matchingAlgorithm;
output Boolean success;
end setMatchingAlgorithm;
setModelicaPath¶
Sets the Modelica library path.
Sets the OPENMODELICALIBRARY (MODELICAPATH in the language specification) in OpenModelica and the environment variable with the same name. See loadModel() for a description of what OPENMODELICALIBRARY is used for.
Set it to the empty string to reset it to the default: setModelicaPath(""); getModelicaPath() tells what the default is.
impure function setModelicaPath
input String modelicaPath;
output Boolean success;
end setModelicaPath;
setNoSimplify¶
Sets the noSimplify flag.
impure function setNoSimplify
input Boolean noSimplify;
output Boolean success;
end setNoSimplify;
setOrderConnections¶
Sets the orderConnection flag.
impure function setOrderConnections
input Boolean orderConnections;
output Boolean success;
end setOrderConnections;
setParameterValue¶
Sets the binding equation of a component.
impure function setParameterValue
input TypeName className;
input TypeName variableName;
input Expression value;
output Boolean success;
end setParameterValue;
setPostOptModules¶
Sets post optimization modules for the backend.
Sets the optimization modules which are used after the index reduction to optimize the system for simulation, given as a comma separated string. Call the compiler with --help=optmodules for more information about what methods are available.
Example input: lateInline,inlineArrayEqn,removeSimpleEquations
impure function setPostOptModules
input String modules;
output Boolean success;
end setPostOptModules;
setPreOptModules¶
Sets pre optimization modules for the backend.
Sets the optimization modules which are used before the matching and index reduction in the backend, given as a comma separated string. Call the compiler with --help=optmodules for more information about what modules are available.
Example input: removeFinalParameters,removeSimpleEquations,expandDerOperator
impure function setPreOptModules
input String modules;
output Boolean success;
end setPreOptModules;
setShowAnnotations¶
Sets the value of the --showAnnotations flag.
impure function setShowAnnotations
input Boolean show;
output Boolean success;
end setShowAnnotations;
setSourceFile¶
Sets the filename for a class.
impure function setSourceFile
input TypeName class_;
input String filename;
output Boolean success;
end setSourceFile;
setTearingMethod¶
Sets the tearing method used by the backend.
Same as calling the compiler with the --tearingMethod flag.
Example input: omcTearing
impure function setTearingMethod
input String tearingMethod;
output Boolean success;
end setTearingMethod;
setTempDirectoryPath¶
Sets the current user temporary directory location.
impure function setTempDirectoryPath
input String tempDirectoryPath;
output Boolean success;
end setTempDirectoryPath;
setVectorizationLimit¶
Sets the vectorization limit used by the old frontend.
impure function setVectorizationLimit
input Integer vectorizationLimit;
output Boolean success;
end setVectorizationLimit;
simulate¶
Simulates a model.
Simulates a Modelica model by generating C code, building it and running the simulation executable.
simulate(className, [startTime], [stopTime], [numberOfIntervals], [stepSize], [tolerance], [method], [fileNamePrefix], [options], [outputFormat], [variableFilter], [cflags], [simflags], [resimulateExecutable])
Example command:
simulate(A);
If resimulateExecutable is given, simulate() does not translate and build the model. It runs that executable, which an earlier buildModel() made in the current directory, with only the flags in simflags. To change the run, give simulation flags, for example simflags="-stopTime=2".
The arguments of simulate, buildModel and the other simulation calls.
Only className is necessary. An argument that is not given gets its value from the experiment annotation of the class, or of a class that it extends, or else from the default below. The declared values nan(), -1 and "<default>" only mark an argument that is not given.
Argument |
Value if not given |
|---|---|
|
|
|
|
|
( |
|
Not used. If it is given, numberOfIntervals is (stopTime - startTime) / stepSize, rounded down. |
|
|
|
"dassl". With |
|
The name of the class. The result file is |
|
Not used. |
|
"mat". The other formats are "csv", "plt", "arrow" and "empty", which writes no result file. |
|
".*". Only the variables whose full name matches this regular expression go into the result file. |
|
"". Extra flags for the C compiler. |
|
The |
The flags in simflags apply when the simulation executable runs, and they replace the values above: for example, -s=euler replaces method.
impure function simulate
input TypeName className "The model";
input Real startTime = nan() "Start time";
input Real stopTime = nan() "Stop time";
input Integer numberOfIntervals = -1 "Number of intervals";
input Real stepSize = nan() "Interval of the result file";
input Real tolerance = nan() "Integration tolerance";
input String method = "<default>" "Integration method";
input String fileNamePrefix = "<default>" "File name prefix";
input String options = "<default>" "Not used";
input String outputFormat = "<default>" "Result file format";
input String variableFilter = "<default>" "Variables to store";
input String cflags = "<default>" "Flags for the C compiler";
input String simflags = "<default>" "Flags for the simulation";
input String resimulateExecutable = "" "Executable to run";
output SimulationResult simulationResults;
record SimulationResult
String resultFile;
String simulationOptions;
String messages;
Real timeFrontend;
Real timeBackend;
Real timeSimCode;
Real timeTemplates;
Real timeCompile;
Real timeSimulation;
Real timeTotal;
end SimulationResult;
end simulate;
simulateAcausalDAE¶
Simulates a flowsheet model whose top-level components are acausal DAE blocks. Each top-level component is translated separately via translateResidualsDAE, the connections are extracted, the per-component code is stitched together by combine_components.py, and the resulting combined DAE system is built, run and returned just like simulate().
Simulates a flowsheet model whose top-level components are acausal DAE blocks, by separately compiling each top-level component (see translateResidualsDAE), stitching them together with the connection equations, and building/running the combined DAE system. Returns the same SimulationResult record as simulate.
simulateAcausalDAE(className, [startTime], [stopTime], [numberOfIntervals], [stepSize], [tolerance], [method], [fileNamePrefix], [options], [outputFormat], [variableFilter], [cflags], [simflags])
The arguments of simulate, buildModel and the other simulation calls.
Only className is necessary. An argument that is not given gets its value from the experiment annotation of the class, or of a class that it extends, or else from the default below. The declared values nan(), -1 and "<default>" only mark an argument that is not given.
Argument |
Value if not given |
|---|---|
|
|
|
|
|
( |
|
Not used. If it is given, numberOfIntervals is (stopTime - startTime) / stepSize, rounded down. |
|
|
|
"dassl". With |
|
The name of the class. The result file is |
|
Not used. |
|
"mat". The other formats are "csv", "plt", "arrow" and "empty", which writes no result file. |
|
".*". Only the variables whose full name matches this regular expression go into the result file. |
|
"". Extra flags for the C compiler. |
|
The |
The flags in simflags apply when the simulation executable runs, and they replace the values above: for example, -s=euler replaces method.
impure function simulateAcausalDAE
input TypeName className "The model";
input Real startTime = nan() "Start time";
input Real stopTime = nan() "Stop time";
input Integer numberOfIntervals = -1 "Number of intervals";
input Real stepSize = nan() "Interval of the result file";
input Real tolerance = nan() "Integration tolerance";
input String method = "<default>" "Integration method";
input String fileNamePrefix = "<default>" "File name prefix";
input String options = "<default>" "Not used";
input String outputFormat = "<default>" "Result file format";
input String variableFilter = "<default>" "Variables to store";
input String cflags = "<default>" "Flags for the C compiler";
input String simflags = "<default>" "Flags for the simulation";
output SimulationResult simulationResults;
record SimulationResult
String resultFile;
String simulationOptions;
String messages;
Real timeFrontend;
Real timeBackend;
Real timeSimCode;
Real timeTemplates;
Real timeCompile;
Real timeSimulation;
Real timeTotal;
end SimulationResult;
end simulateAcausalDAE;
solveLinearSystem¶
Solve A*X = B using dgesv.
Returns for solver dgesv:
info>0: Singular for element i.
info<0: Bad input.
function solveLinearSystem
input Real[size(B, 1), size(B, 1)] A;
input Real[:] B;
output Real[size(B, 1)] X;
output Integer info;
end solveLinearSystem;
sortStrings¶
Sorts a string array in ascending order.
function sortStrings
input String arr[:];
output String sorted[:];
end sortStrings;
stat¶
Returns status for a file.
Like stat(2), except the output is of type real because of limited precision of Integer.
impure function stat
input String fileName;
output Boolean success;
output Real fileSize;
output Real mtime;
end stat;
storeAST¶
Stores the AST and returns an id that can be used to restore it with restoreAST.
impure function storeAST
output Integer id;
end storeAST;
stringReplace¶
Replaces all occurrences of a token with another token in a string.
function stringReplace
input String str;
input String source;
input String target;
output String res;
end stringReplace;
stringSplit¶
Splits a string at the places given by the character
Splits the string at the places given by the character, for example:
stringSplit("abcbdef","b") => {"a","c","def"}
function stringSplit
input String string;
input String token "single character only";
output String[:] strings;
end stringSplit;
stringTypeName¶
Constructs a TypeName from a string.
stringTypeName is used to make it simpler to create some functionality when scripting. The basic use case is calling functions like simulate when you do not know the name of the class a priori: simulate(stringTypeName(readFile("someFile"))).
function stringTypeName
input String str;
output TypeName cl;
end stringTypeName;
stringVariableName¶
Constructs a VariableName from a string.
stringVariableName is used to make it simpler to create some functionality when scripting. The basic use case is calling functions like val when you do not know the name of the variable a priori: val(stringVariableName(readFile("someFile"))).
function stringVariableName
input String str;
output VariableName cl;
end stringVariableName;
strtok¶
Splits a string at the places given by the token.
Splits a string at the places given by the token, for example:
strtok("abcbdef","b") => {"a","c","def"}strtok("abcbdef","cd") => {"ab","ef"}
Note: strtok does not return empty tokens. To split a read file into lines, use stringSplit instead (splits only on character).
function strtok
input String string;
input String token;
output String[:] strings;
end strtok;
system¶
Similar to system(3). Executes the given command in the system shell.
impure function system
input String callStr "String to call: sh -c $callStr";
input String outputFile = "" "The output is redirected to this file (unless already done by callStr)";
output Integer retval "Return value of the system call; usually 0 on success";
end system;
system_parallel¶
Similar to system(3). Executes the given commands in the system shell, in parallel if omc was compiled using OpenMP.
impure function system_parallel
input String callStr[:] "String to call: sh -c $callStr";
input Integer numThreads = numProcessors();
output Integer retval[:] "Return value of the system call; usually 0 on success";
end system_parallel;
testsuiteFriendlyName¶
Converts a filename to a testsuite friendly one.
function testsuiteFriendlyName
input String path;
output String fixed;
end testsuiteFriendlyName;
threadWorkFailed¶
Exits the current thread with a failure.
(Experimental) Exits the current (worker thread) signalling a failure.
translateAcausalDAE¶
Generates the combined DAE C code for a flowsheet model whose top-level components are acausal DAE blocks, without building it. Each top-level component is translated separately via translateResidualsDAE, the connections are extracted, and the per-component code is stitched together by combine_components.py. This is the acausal-DAE counterpart of translateModel().
Generates the combined acausal-DAE C code (per-component residual code plus connection equations) without building it, the acausal-DAE counterpart of translateModel().
The arguments of simulate, buildModel and the other simulation calls.
Only className is necessary. An argument that is not given gets its value from the experiment annotation of the class, or of a class that it extends, or else from the default below. The declared values nan(), -1 and "<default>" only mark an argument that is not given.
Argument |
Value if not given |
|---|---|
|
|
|
|
|
( |
|
Not used. If it is given, numberOfIntervals is (stopTime - startTime) / stepSize, rounded down. |
|
|
|
"dassl". With |
|
The name of the class. The result file is |
|
Not used. |
|
"mat". The other formats are "csv", "plt", "arrow" and "empty", which writes no result file. |
|
".*". Only the variables whose full name matches this regular expression go into the result file. |
|
"". Extra flags for the C compiler. |
|
The |
The flags in simflags apply when the simulation executable runs, and they replace the values above: for example, -s=euler replaces method.
impure function translateAcausalDAE
input TypeName className "The model";
input Real startTime = nan() "Start time";
input Real stopTime = nan() "Stop time";
input Integer numberOfIntervals = -1 "Number of intervals";
input Real stepSize = nan() "Interval of the result file";
input Real tolerance = nan() "Integration tolerance";
input String method = "<default>" "Integration method";
input String fileNamePrefix = "<default>" "File name prefix";
input String options = "<default>" "Not used";
input String outputFormat = "<default>" "Result file format";
input String variableFilter = "<default>" "Variables to store";
input String cflags = "<default>" "Flags for the C compiler";
input String simflags = "<default>" "Flags for the simulation";
output Boolean success;
end translateAcausalDAE;
translateGraphics¶
Translates old graphical annotations to Modelica standard annotations.
impure function translateGraphics
input TypeName className;
output String result;
end translateGraphics;
translateModel¶
Translates a modelica model into C code without building it.
The arguments of simulate, buildModel and the other simulation calls.
Only className is necessary. An argument that is not given gets its value from the experiment annotation of the class, or of a class that it extends, or else from the default below. The declared values nan(), -1 and "<default>" only mark an argument that is not given.
Argument |
Value if not given |
|---|---|
|
|
|
|
|
( |
|
Not used. If it is given, numberOfIntervals is (stopTime - startTime) / stepSize, rounded down. |
|
|
|
"dassl". With |
|
The name of the class. The result file is |
|
Not used. |
|
"mat". The other formats are "csv", "plt", "arrow" and "empty", which writes no result file. |
|
".*". Only the variables whose full name matches this regular expression go into the result file. |
|
"". Extra flags for the C compiler. |
|
The |
The flags in simflags apply when the simulation executable runs, and they replace the values above: for example, -s=euler replaces method.
impure function translateModel
input TypeName className "The model";
input Real startTime = nan() "Start time";
input Real stopTime = nan() "Stop time";
input Integer numberOfIntervals = -1 "Number of intervals";
input Real stepSize = nan() "Interval of the result file";
input Real tolerance = nan() "Integration tolerance";
input String method = "<default>" "Integration method";
input String fileNamePrefix = "<default>" "File name prefix";
input String options = "<default>" "Not used";
input String outputFormat = "<default>" "Result file format";
input String variableFilter = "<default>" "Variables to store";
input String cflags = "<default>" "Flags for the C compiler";
input String simflags = "<default>" "Flags for the simulation";
output Boolean success;
end translateModel;
translateModelFMU¶
Translates a model into C code for a FMU without building it.
The only required argument is the className, while all others have some default values.
Example command:
translateModelFMU(className, version="2.0");
impure function translateModelFMU
input TypeName className "the class that should translated";
input String version = "2.0" "FMU version, 2.0 or 3.0 (1.0 is deprecated).";
input String fmuType = "me" "FMU type, me (model exchange), cs (co-simulation), me_cs (both model exchange and co-simulation)";
input String fileNamePrefix = "<default>" "fileNamePrefix. <default> = \"className\"";
input String platforms[:] = {"static"} "The list of platforms to generate code for.
\"dynamic\"=current platform, dynamically link the runtime.
\"static\"=current platform, statically link everything.
\"<cpu>-<vendor>-<os>\", host tripple, e.g. \"x86_64-linux-gnu\" or \"x86_64-w64-mingw32\".
\"<cpu>-<vendor>-<os> docker run ghcr.io/openmodelica/crossbuild:v1.28.0\" host triple with OpenModelica supplied Docker image, e.g. \"x86_64-linux-gnu docker run ghcr.io/openmodelica/crossbuild:v1.28.0\".
\"<cpu>-<vendor>-<os> docker run <image>\" host triple with Docker image, e.g. \"x86_64-linux-gnu docker run --pull=never multiarch/crossbuild\"";
input Boolean includeResources = false "include Modelica based resources via loadResource or not";
output Boolean success;
end translateModelFMU;
translateModelXML¶
Translates a model into an XML representation of its equation system.
Translates a model and writes its equation system to fileNamePrefix.xml, with dots in fileNamePrefix replaced by underscores.
Returns the name of the XML file, or an empty string on failure.
impure function translateModelXML
input TypeName className "the class that should be translated";
input String fileNamePrefix = "<default>" "fileNamePrefix. <default> = \"className\"";
output String xmlFile;
end translateModelXML;
translateResidualsDAE¶
Takes a model with top-level connectors as input and produces the DAE mode C code for the DAE residuals and Jacobian, guaranteed to be valid for any arbitrary causality once this component is coupled to other ones through the connector variables. Can be used for separate compilation of DAE-based components.
impure function translateResidualsDAE
input TypeName className;
input String fileNamePrefix = "<default>";
output Boolean success;
end translateResidualsDAE;
typeNameString¶
Converts a TypeName to a string.
function typeNameString
input TypeName cl;
output String out;
end typeNameString;
typeNameStrings¶
Converts a TypeName to a list of strings.
function typeNameStrings
input TypeName cl;
output String out[:];
end typeNameStrings;
typeOf¶
Returns the type of an interactive variable.
impure function typeOf
input VariableName variableName;
output String result;
end typeOf;
unloadOMSimulator¶
Frees the OMSimulator instances.
impure function unloadOMSimulator
output Integer status;
end unloadOMSimulator;
updateComponent¶
Updates an existing component.
impure function updateComponent
input TypeName componentName;
input TypeName typeName;
input TypeName classPath;
input Expression binding = $Code(());
input ExpressionOrModification modification = $Code();
input Expression comment = $Code(());
input Expression annotate = $Code(());
output Boolean success;
end updateComponent;
updateConnection¶
Updates the connection annotation in the class.
See also updateConnectionNames().
impure function updateConnection
input TypeName className;
input String from;
input String to;
input ExpressionOrModification annotate;
output Boolean result;
end updateConnection;
updateConnectionAnnotation¶
Updates the connection annotation in the class.
See also updateConnectionNames().
impure function updateConnectionAnnotation
input TypeName className;
input String from;
input String to;
input String annotate;
output Boolean result;
end updateConnectionAnnotation;
updateConnectionNames¶
Updates the connection connector names in the class.
See also updateConnection().
impure function updateConnectionNames
input TypeName className;
input String from;
input String to;
input String fromNew;
input String toNew;
output Boolean result;
end updateConnectionNames;
updateEquation¶
Replaces an equation with another equation in a class.
Syntax¶
updateEquation(MyModel, "x = 1", "x = 2")
Description¶
updateEquation takes two equations, given as strings that are parsed as Modelica equations, and replaces an equation in the given class that matches the first equation with the second. If
newEq
is an empty string, then the matching equation is removed instead of replaced.
Optional arguments¶
- matchAll
If
matchAllis true, then updateEquation replaces all equations that matches. Otherwise it only replaces the first matching equation.
- matchShallow
If
matchShallowis true, then equations are only matched shallowly, ignoring any nested equations. I.e.
updateEquation(M, "if b then end if", ...)
will replace any if-equation that matches
if b then
, regardless of what equations the if-equation contains. If
matchShallowis false, then the equations must match recursively.
- matchDescription
If
matchDescriptionis true, then the description strings and annotations of the equations must match. Otherwise these are ignored when matching equations.
- mergeDescription
If
mergeDescriptionis true, then the description string and/or annotations of the replaced equation are copied to the new equation if these are missing on the new equation. This requires that
matchDescriptionis false, otherwise there will be nothing to merge since the equations must have the same description to match. If
mergeDescriptionis false, then the new equation overwrites the old completely, including description strings and annotations.
impure function updateEquation
input TypeName className "The name of the class";
input String oldEq "The equation to replace";
input String newEq "The equation to replace with";
input Boolean matchAll = false "Update all matching equations if true, otherwise only the first matching";
input Boolean matchShallow = true "Ignore nested equations if true, otherwise match the equations recursively";
input Boolean matchDescription = false "Match description strings/annotations if true, otherwise ignore them";
input Boolean mergeDescription = false "Keep description string/annotations from the old equation if true";
output Boolean success "true if any equation was updated, otherwise false";
end updateEquation;
updateInitialState¶
Updates an initial state in a class.
impure function updateInitialState
input TypeName cl;
input String state;
input ExpressionOrModification annotate;
output Boolean bool;
end updateInitialState;
updatePackageIndex¶
Updates the package index.
Updates the package index from the internet. This adds new packages to be able to install or upgrade packages. To upgrade installed packages, call upgradeInstalledPackages().
impure function updatePackageIndex
output Boolean result;
end updatePackageIndex;
updateTransition¶
Updates a transition in a class.
impure function updateTransition
input TypeName cl;
input String from;
input String to;
input String oldCondition;
input Boolean oldImmediate;
input Boolean oldReset;
input Boolean oldSynchronize;
input Integer oldPriority;
input String newCondition;
input Boolean newImmediate;
input Boolean newReset;
input Boolean newSynchronize;
input Integer newPriority;
input ExpressionOrModification annotate;
output Boolean bool;
end updateTransition;
upgradeInstalledPackages¶
Upgrades installed packages.
Upgrades installed packages that have been registered by the package manager. To update the index, call updatePackageIndex().
impure function upgradeInstalledPackages
input Boolean installNewestVersions = true;
output Boolean result;
end upgradeInstalledPackages;
uriToFilename¶
Converts a URI to a filename.
Handles modelica:// and file:// URI's. The result is an absolute path on the local system. modelica:// URI's are only handled if the class is already loaded.
Returns the empty string on failure.
function uriToFilename
input String uri;
output String filename = "";
end uriToFilename;
val¶
Return the value of a variable at a given time in the simulation results
Return the value of a variable at a given time in the simulation results.
Works on the filename pointed to by the scripting variable currentSimulationResult or a given filename.
For parameters, any time may be given. For variables the startTime<=time<=stopTime needs to hold.
On error, nan (Not a Number) is returned and the error buffer contains the message.
impure function val
input VariableName var;
input Real timePoint = 0.0;
input String fileName = "<default>" "The contents of the currentSimulationResult variable";
output Real valAtTime;
end val;
writeFile¶
Writes data to a file.
Returns true on success. If append = true the data is appended to the file, otherwise the file is overwritten with the new content.
impure function writeFile
input String fileName;
input String data;
input Boolean append = false;
output Boolean success;
end writeFile;
Simulation Parameter Sweep¶
Following example shows how to update the parameters and re-run the simulation without compiling the model.
loadFile("BouncingBall.mo");
getErrorString();
// build the model once
buildModel(BouncingBall);
getErrorString();
for i in 1:3 loop
// We update the parameter e start value from 0.7 to "0.7 + i".
value := 0.7 + i;
// call the generated simulation code to produce a result file BouncingBall%i%_res.mat
system("./BouncingBall -override=e="+String(value)+" -r=BouncingBall" + String(i) + "_res.mat");
getErrorString();
end for;
We used the BouncingBall.mo in the example above. The above example produces three result files each containing different start value for e i.e., 1.7, 2.7, 3.7.
Examples¶
The following is an interactive session with the OpenModelica environment including some of the abovementioned commands and examples. Run the examples below using OMShell or OMNotebook.
We type in a very small model in the command window:
model Test "Testing OpenModelica Scripts"
Real x, y;
equation
x = 5.0+time; y = 6.0;
end Test;
We give the command to flatten a model:
>>> instantiateModel(Test)
class Test "Testing OpenModelica Scripts"
Real x;
Real y;
equation
x = 5.0 + time;
y = 6.0;
end Test;
A range expression is typed in:
>>> a:=1:10
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
It is multiplied by 2:
>>> a*2
{2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
The variables are cleared:
>>> clearVariables()
true
We print the loaded class test from its internal representation:
>>> list(Test)
model Test "Testing OpenModelica Scripts"
Real x, y;
equation
x = 5.0 + time;
y = 6.0;
end Test;
We get the name and other properties of a class:
>>> getClassNames()
{Test, EQ, ProfilingTest}
>>> getClassComment(Test)
"Testing OpenModelica Scripts"
>>> isPartial(Test)
false
>>> isPackage(Test)
false
>>> isModel(Test)
true
>>> checkModel(Test)
"Check of Test completed successfully.
Class Test has 2 equation(s) and 2 variable(s).
2 of these are trivial equation(s)."
The common combination of a simulation followed by getting a value and doing a plot:
>>> simulate(Test, stopTime=3.0)
record SimulationResult
resultFile = "«DOCHOME»/Test_res.mat",
simulationOptions = "startTime = 0.0, stopTime = 3.0, numberOfIntervals = 500, tolerance = 1e-6, method = 'dassl', fileNamePrefix = 'Test', options = '', outputFormat = 'mat', variableFilter = '.*', cflags = '', simflags = ''",
messages = "LOG_SUCCESS | info | The initialization finished successfully without homotopy method.
LOG_SUCCESS | info | The simulation finished successfully.
LOG_STDOUT | info | Time measurements are stored in Test_prof.html (human-readable) and Test_prof.xml (for XSL transforms or more details)
",
timeFrontend = 8.151500000000001e-4,
timeBackend = 0.001663041,
timeSimCode = 4.1177300000000004e-4,
timeTemplates = 0.001384789,
timeCompile = 0.166429043,
timeSimulation = 0.016129999000000003,
timeTotal = 0.18687703700000002
end SimulationResult;
>>> val(x , 2.0)
7.0
Figure 155 Plot generated by OpenModelica+gnuplot¶
>>> plotAll()
Figure 156 Plot generated by OpenModelica+gnuplot¶
Interactive Function Calls, Reading, and Writing¶
We enter an assignment of a vector expression, created by the range construction expression 1:12, to be stored in the variable x. The type and the value of the expression is returned.
>>> x := 1:12
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
The function bubblesort is called to sort this vector in descending order. The sorted result is returned together with its type. Note that the result vector is of type Real[:], instantiated as Real[12], since this is the declared type of the function result. The input Integer vector was automatically converted to a Real vector according to the Modelica type coercion rules.
>>> loadFile(getInstallationDirectoryPath() + "/share/doc/omc/testmodels/bubblesort.mo")
true
>>> bubblesort(x)
{12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0}
Now we want to try another small application, a simplex algorithm for optimization. First read in a small matrix containing coefficients that define a simplex problem to be solved:
>>> a := {
{-1,-1,-1, 0, 0, 0, 0, 0, 0},
{-1, 1, 0, 1, 0, 0, 0, 0, 5},
{ 1, 4, 0, 0, 1, 0, 0, 0, 45},
{ 2, 1, 0, 0, 0, 1, 0, 0, 27},
{ 3,-4, 0, 0, 0, 0, 1, 0, 24},
{ 0, 0, 1, 0, 0, 0, 0, 1, 4}
}
{{-1, -1, -1, 0, 0, 0, 0, 0, 0}, {-1, 1, 0, 1, 0, 0, 0, 0, 5}, {1, 4, 0, 0, 1, 0, 0, 0, 45}, {2, 1, 0, 0, 0, 1, 0, 0, 27}, {3, -4, 0, 0, 0, 0, 1, 0, 24}, {0, 0, 1, 0, 0, 0, 0, 1, 4}}
function pivot1
input Real b[:,:];
input Integer p;
input Integer q;
output Real a[size(b,1),size(b,2)];
protected
Integer M;
Integer N;
algorithm
a := b;
N := size(a,1)-1;
M := size(a,2)-1;
for j in 1:N loop
for k in 1:M loop
if j<>p and k<>q then
a[j,k] := a[j,k]-0.3*j;
end if;
end for;
end for;
a[p,q] := 0.05;
end pivot1;
function misc_simplex1
input Real matr[:,:];
output Real x[size(matr,2)-1];
output Real z;
output Integer q;
output Integer p;
protected
Real a[size(matr,1),size(matr,2)];
Integer M;
Integer N;
algorithm
N := size(a,1)-1;
M := size(a,2)-1;
a := matr;
p:=0;q:=0;
a := pivot1(a,p+1,q+1);
while not (q==(M) or p==(N)) loop
q := 0;
while not (q == (M) or a[0+1,q+1]>1) loop
q:=q+1;
end while;
p := 0;
while not (p == (N) or a[p+1,q+1]>0.1) loop
p:=p+1;
end while;
if (q < M) and (p < N) and(p>0) and (q>0) then
a := pivot1(a,p,q);
end if;
if(p<=0) and (q<=0) then
a := pivot1(a,p+1,q+1);
end if;
if(p<=0) and (q>0) then
a := pivot1(a,p+1,q);
end if;
if(p>0) and (q<=0) then
a := pivot1(a,p,q+1);
end if;
end while;
z := a[1,M];
x := {a[1,i] for i in 1:size(x,1)};
for i in 1:10 loop
for j in 1:M loop
x[j] := x[j]+x[j]*0.01;
end for;
end for;
end misc_simplex1;
Then call the simplex algorithm implemented as the Modelica function simplex1. This function returns four results, which are represented as a tuple of four return values:
>>> misc_simplex1(a)
({0.05523110627056022, -1.1046221254112043, -1.1046221254112043, 0.0, 0.0, 0.0, 0.0, 0.0}, 0.0, 8, 1)
