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. All commands are shown in alphabetical order:
relocateFunctions¶
Highly experimental, requires OMC be compiled with special flags to use.
Update symbols in the running program to ones defined in the given shared object.
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).
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.
function GC_expand_hp
input Integer size;
output Boolean success;
end GC_expand_hp;
GC_gcollect_and_unmap¶
Forces GC to collect and unmap memory (we use it before we start and wait for memory-intensive tasks in child processes).
addClassAnnotation¶
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>"))
function addClassAnnotation
input TypeName class_;
input ExpressionOrModification annotate;
output Boolean bool;
end addClassAnnotation;
addInitialState¶
Adds the initial state to the class.
function addInitialState
input TypeName cl;
input String state;
input ExpressionOrModification annotate;
output Boolean bool;
end addInitialState;
addTransition¶
Adds the transition to the class.
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¶
Like alarm(2).
Note that OpenModelica also sends SIGALRM to the process group when the alarm is triggered (in order to kill running simulations).
impure function alarm
input Integer seconds;
output Integer previousSeconds;
end alarm;
appendEnvironmentVar¶
Appends a variable to the environment variables list.
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;
buildModel¶
builds a modelica model by generating c code and build it. It does not run the code! The only required argument is the className, while all others have some default values. simulate(className, [startTime], [stopTime], [numberOfIntervals], [tolerance], [method], [fileNamePrefix], [options], [outputFormat], [variableFilter], [cflags], [simflags]) Example command: simulate(A);
function buildModel
input TypeName className "the class that should be built";
input Real startTime = "<default>" "the start time of the simulation. <default> = 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Real 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 = "<default>" "integration method used for simulation. <default> = dassl";
input String fileNamePrefix = "<default>" "fileNamePrefix. <default> = \"\"";
input String options = "<default>" "options. <default> = \"\"";
input String outputFormat = "mat" "Format for the result file. <default> = \"mat\"";
input String variableFilter = ".*" "Filter for variables that should store in result file. <default> = \".*\"";
input String cflags = "<default>" "cflags. <default> = \"\"";
input String simflags = "<default>" "simflags. <default> = \"\"";
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");
function buildModelFMU
input TypeName className "the class that should translated";
input String version = "2.0" "FMU version, 1.0 or 2.0.";
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[:] = {"dynamic"} "The list of platforms to generate code for. \"dynamic\"=current platform, dynamically link the runtime. \"static\"=current platform, statically link everything. Else, use a host triple, e.g. \"x86_64-linux-gnu\" or \"x86_64-w64-mingw32\"";
input Boolean includeResources = false "include Modelica based resources via loadResource or not";
output String generatedFileName "Returns the full path of the generated FMU.";
end buildModelFMU;
buildOpenTURNSInterface¶
generates wrapper code for OpenTURNS
function buildOpenTURNSInterface
input TypeName className;
input String pythonTemplateFile;
input Boolean showFlatModelica = false;
output String outPythonScript;
end buildOpenTURNSInterface;
cd¶
change directory to the given 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.
function cd
input String newWorkingDirectory = "";
output String workingDirectory;
end cd;
checkAllModelsRecursive¶
Checks all models recursively and returns number of variables and equations.
function checkAllModelsRecursive
input TypeName className;
input Boolean checkProtected = false "Checks also protected classes if true";
output String result;
end checkAllModelsRecursive;
checkCodeGraph¶
Checks if the given taskgraph has the same structure as the graph described in the codefile.
function checkCodeGraph
input String graphfile;
input String codefile;
output String[:] result;
end checkCodeGraph;
checkInterfaceOfPackages¶
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).
function checkInterfaceOfPackages
input TypeName cl;
input String dependencyMatrix[:, :];
output Boolean success;
end checkInterfaceOfPackages;
checkModel¶
Checks a model and returns number of variables and equations.
function checkModel
input TypeName className;
output String result;
end checkModel;
checkSettings¶
Display some diagnostics.
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.
function checkTaskGraph
input String filename;
input String reffilename;
output String[:] result;
end checkTaskGraph;
classAnnotationExists¶
Check if annotation exists
Returns true if className has a class annotation called annotationName.
function classAnnotationExists
input TypeName className;
input TypeName annotationName;
output Boolean exists;
end classAnnotationExists;
clear¶
Clears everything: symboltable and variables.
function clear
output Boolean success;
end clear;
clearCommandLineOptions¶
Resets all command-line flags to their default values.
function clearCommandLineOptions
output Boolean success;
end clearCommandLineOptions;
clearDebugFlags¶
Resets all debug flags to their default values.
function clearDebugFlags
output Boolean success;
end clearDebugFlags;
clearMessages¶
Clears the error buffer.
function clearMessages
output Boolean success;
end clearMessages;
clearVariables¶
Clear all user defined variables.
function clearVariables
output Boolean success;
end clearVariables;
closeSimulationResultFile¶
Closes the current simulation result 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. Even OMEdit only use this API for Windows.
function closeSimulationResultFile
output Boolean success;
end closeSimulationResultFile;
codeToString¶
function codeToString
input $Code className;
output String string;
end codeToString;
compareFiles¶
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¶
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;
compareSimulationResults¶
compares simulation results.
function compareSimulationResults
input String filename;
input String reffilename;
input String logfilename;
input Real relTol = 0.01;
input Real absTol = 0.0001;
input String[:] vars = fill("", 0);
output String[:] result;
end compareSimulationResults;
convertUnits¶
Returns the scale factor and offsets used when converting two units.
Returns false if the types are not compatible and should not be converted.
function convertUnits
input String s1;
input String s2;
output Boolean unitsCompatible;
output Real scaleFactor;
output Real offset;
end convertUnits;
copyClass¶
Copies a class within the same level
function copyClass
input TypeName className "the class that should be copied";
input String newClassName "the name for new class";
input TypeName withIn = $Code(TopLevel) "the with in path for new class";
output Boolean result;
end copyClass;
countMessages¶
Returns the total number of messages in the error buffer, as well as the number of errors and warnings.
function countMessages
output Integer numMessages;
output Integer numErrors;
output Integer numWarnings;
end countMessages;
deleteFile¶
Deletes a file with the given name.
function deleteFile
input String fileName;
output Boolean success;
end deleteFile;
deleteInitialState¶
Deletes the initial state from the class.
function deleteInitialState
input TypeName cl;
input String state;
output Boolean bool;
end deleteInitialState;
deleteTransition¶
Deletes the transition from the class.
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.
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).
function diffModelicaFileListings
input String before, after;
input DiffFormat diffFormat = DiffFormat.color;
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.
The output is the names of the variables for which files were generated.
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¶
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.
The output is the names of the variables for which files were generated.
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¶
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;
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.
function dumpXMLDAE
input TypeName className;
input String translationLevel = "flat" "flat, optimiser, backEnd, or stateSpace";
input Boolean addOriginalIncidenceMatrix = 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¶
echo(false) disables Interactive output, echo(true) enables it again.
function echo
input Boolean setEcho;
output Boolean newEcho;
end echo;
escapeXML¶
function escapeXML
input String inStr;
output String outStr;
end escapeXML;
exportToFigaro¶
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
function extendsFrom
input TypeName className;
input TypeName baseClassName;
output Boolean res;
end extendsFrom;
filterSimulationResults¶
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).
function filterSimulationResults
input String inFile;
input String outFile;
input String[:] vars;
input Integer numberOfIntervals = 0 "0=Do not resample";
output Boolean success;
end filterSimulationResults;
generateCode¶
The input is a function name for which C-code is generated and compiled into a dll/so
function generateCode
input TypeName className;
output Boolean success;
end generateCode;
generateEntryPoint¶
Generates a main() function that calls the given MetaModelica entrypoint (assumed to have input list and no outputs).
function generateEntryPoint
input String fileName;
input TypeName entryPoint;
input String url = "https://trac.openmodelica.org/OpenModelica/newticket";
end generateEntryPoint;
generateHeader¶
function generateHeader
input String fileName;
output Boolean success;
end generateHeader;
generateScriptingAPI¶
Work in progress
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.
function generateScriptingAPI
input TypeName cl;
input String name;
output Boolean success;
output String moFile;
output String qtFile;
output String qtHeader;
end generateScriptingAPI;
generateSeparateCode¶
Under construction.
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¶
Under construction.
function generateSeparateCodeDependencies
input String stampSuffix = ".c" "Suffix to add to dependencies (often .c.stamp)";
output String[:] dependencies;
end generateSeparateCodeDependencies;
generateSeparateCodeDependenciesMakefile¶
Under construction.
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¶
function generateVerificationScenarios
input TypeName path;
output Boolean success;
end generateVerificationScenarios;
getAlgorithmCount¶
Counts the number of Algorithm sections in a class.
function getAlgorithmCount
input TypeName class_;
output Integer count;
end getAlgorithmCount;
getAlgorithmItemsCount¶
Counts the number of Algorithm items in a class.
function getAlgorithmItemsCount
input TypeName class_;
output Integer count;
end getAlgorithmItemsCount;
getAnnotationCount¶
Counts the number of Annotation sections in a class.
function getAnnotationCount
input TypeName class_;
output Integer count;
end getAnnotationCount;
getAnnotationModifierValue¶
Returns the Modifiers value in the vendor annotation example annotation(__OpenModelica_simulationFlags(solver="dassl")) calling sequence should be getAnnotationNamedModifiersValue(className,"__OpenModelica_simulationFlags","modifiername") which returns "dassl".
function getAnnotationModifierValue
input TypeName name;
input String vendorannotation;
input String modifiername;
output String modifiernamevalue;
end getAnnotationModifierValue;
getAnnotationNamedModifiers¶
Returns the Modifiers name in the vendor annotation example annotation(__OpenModelica_simulationFlags(solver="dassl")) calling sequence should be getAnnotationNamedModifiers(className,"__OpenModelica_simulationFlags") which returns {solver}.
function getAnnotationNamedModifiers
input TypeName name;
input String vendorannotation;
output String[:] modifiernamelist;
end getAnnotationNamedModifiers;
getAnnotationVersion¶
Returns the current annotation version.
function getAnnotationVersion
output String annotationVersion;
end getAnnotationVersion;
getAstAsCorbaString¶
Print the whole AST on the CORBA format for records, e.g. record Absyn.PROGRAM classes = ..., within_ = ..., globalBuildTimes = ... end Absyn.PROGRAM;
function getAstAsCorbaString
input String fileName = "<interactive>";
output String result "returns the string if fileName is interactive; else it returns ok or error depending on if writing the file succeeded";
end getAstAsCorbaString;
getAvailableIndexReductionMethods¶
function getAvailableIndexReductionMethods
output String[:] allChoices;
output String[:] allComments;
end getAvailableIndexReductionMethods;
getAvailableLibraries¶
Looks for all libraries that are visible from the getModelicaPath().
function getAvailableLibraries
output String[:] libraries;
end getAvailableLibraries;
getAvailableMatchingAlgorithms¶
function getAvailableMatchingAlgorithms
output String[:] allChoices;
output String[:] allComments;
end getAvailableMatchingAlgorithms;
getAvailableTearingMethods¶
function getAvailableTearingMethods
output String[:] allChoices;
output String[:] allComments;
end getAvailableTearingMethods;
getBooleanClassAnnotation¶
Check if 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.
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.
function getBuiltinType
input TypeName cl;
output String name;
end getBuiltinType;
getCFlags¶
CFLAGS
See setCFlags() for details.
function getCFlags
output String outString;
end getCFlags;
getClassComment¶
Returns the class comment.
function getClassComment
input TypeName cl;
output String comment;
end getClassComment;
getClassInformation¶
Returns class information for the given 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).
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;
end getClassInformation;
getClassNames¶
Returns the list of class names defined in the class.
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.
function getClassRestriction
input TypeName cl;
output String restriction;
end getClassRestriction;
getClassesInModelicaPath¶
MathCore-specific or not? Who knows!
function getClassesInModelicaPath
output String classesInModelicaPath;
end getClassesInModelicaPath;
getCommandLineOptions¶
Returns all command line options who have non-default values as a list of strings. The format of the strings is '--flag=value --flag2=value2'.
function getCommandLineOptions
output String[:] flags;
end getCommandLineOptions;
getCompileCommand¶
function getCompileCommand
output String compileCommand;
end getCompileCommand;
getComponentModifierNames¶
Returns the list of class component modifiers.
function getComponentModifierNames
input TypeName class_;
input String componentName;
output String[:] modifiers;
end getComponentModifierNames;
getComponentModifierValue¶
Returns the modifier value (only the binding exculding submodifiers) of component. For instance, 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().
function getComponentModifierValue
input TypeName class_;
input TypeName modifier;
output String value;
end getComponentModifierValue;
getComponentModifierValues¶
Returns the modifier value (including the submodfiers) of component. For instance, model A B b1(a1(p1=5,p2=4)); end A; getComponentModifierValues(A,b1.a1) => (p1 = 5, p2 = 4) See also getComponentModifierValue().
function getComponentModifierValues
input TypeName class_;
input TypeName modifier;
output String value;
end getComponentModifierValues;
getComponentsTest¶
Returns the components found in the given class.
function getComponentsTest
input TypeName name;
output Component[:] components;
record Component
String className;
// when building record the constructor. Records are allowed to contain only components of basic types, arrays of basic types or other records.
String name;
String comment;
Boolean isProtected;
Boolean isFinal;
Boolean isFlow;
Boolean isStream;
Boolean isReplaceable;
String variability "'constant', 'parameter', 'discrete', ''";
String innerOuter "'inner', 'outer', ''";
String inputOutput "'input', 'output', ''";
String dimensions[:];
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.
function getConnectionCount
input TypeName className;
output Integer count;
end getConnectionCount;
getDefaultOpenCLDevice¶
Returns the id for the default OpenCL device to be used.
function getDefaultOpenCLDevice
output Integer defdevid;
end getDefaultOpenCLDevice;
getDerivedClassModifierNames¶
Returns the derived class modifier names. Example command: type Resistance = Real(final quantity="Resistance",final unit="Ohm"); getDerivedClassModifierNames(Resistance) => {"quantity","unit"}
Finds the modifiers of the derived class.
function getDerivedClassModifierNames
input TypeName className;
output String[:] modifierNames;
end getDerivedClassModifierNames;
getDerivedClassModifierValue¶
Returns the derived class modifier value. Example command: type Resistance = Real(final quantity="Resistance",final unit="Ohm"); getDerivedClassModifierValue(Resistance, unit); => " = "Ohm"" getDerivedClassModifierValue(Resistance, quantity); => " = "Resistance""
Finds the modifier value of the derived class.
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.
function getDerivedUnits
input String baseUnit;
output String[:] derivedUnits;
end getDerivedUnits;
getDocumentationAnnotation¶
Returns the documentaiton annotation defined in the class.
function getDocumentationAnnotation
input TypeName cl;
output String out[3] "{info,revision,infoHeader} TODO: Should be changed to have 2 outputs instead of an array of 2 Strings...";
end getDocumentationAnnotation;
getEnvironmentVar¶
Returns the value of the environment variable.
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.
function getEquationCount
input TypeName class_;
output Integer count;
end getEquationCount;
getEquationItemsCount¶
Counts the number of Equation items in a class.
function getEquationItemsCount
input TypeName class_;
output Integer count;
end getEquationItemsCount;
getErrorString¶
Returns the current error message. [file.mo:n:n-n:n:b] Error: message
Returns a user-friendly string containing the errors stored in the buffer. With warningsAsErrors=true, it reports warnings as if they were errors.
function getErrorString
input Boolean warningsAsErrors = false;
output String errorString;
end getErrorString;
getImportCount¶
Counts the number of Import sections in a class.
function getImportCount
input TypeName class_;
output Integer count;
end getImportCount;
getIndexReductionMethod¶
function getIndexReductionMethod
output String selected;
end getIndexReductionMethod;
getInheritedClasses¶
Returns the list of inherited classes.
function getInheritedClasses
input TypeName name;
output TypeName inheritedClasses[:];
end getInheritedClasses;
getInitialAlgorithmCount¶
Counts the number of Initial Algorithm sections in a class.
function getInitialAlgorithmCount
input TypeName class_;
output Integer count;
end getInitialAlgorithmCount;
getInitialAlgorithmItemsCount¶
Counts the number of Initial Algorithm items in a class.
function getInitialAlgorithmItemsCount
input TypeName class_;
output Integer count;
end getInitialAlgorithmItemsCount;
getInitialEquationCount¶
Counts the number of Initial Equation sections in a class.
function getInitialEquationCount
input TypeName class_;
output Integer count;
end getInitialEquationCount;
getInitialEquationItemsCount¶
Counts the number of Initial Equation items in a class.
function getInitialEquationItemsCount
input TypeName class_;
output Integer count;
end getInitialEquationItemsCount;
getInitialStates¶
Returns list of initial states for the given class.
Each initial state item contains 2 values i.e, state name and annotation.
function getInitialStates
input TypeName cl;
output String[:, :] initialStates;
end getInitialStates;
getInstallationDirectoryPath¶
This returns OPENMODELICAHOME if it is set; on some platforms the default path is returned if it is not set.
function getInstallationDirectoryPath
output String installationDirectoryPath;
end getInstallationDirectoryPath;
getLanguageStandard¶
Returns the current Modelica Language Standard in use.
function getLanguageStandard
output String outVersion;
end getLanguageStandard;
getLinker¶
function getLinker
output String linker;
end getLinker;
getLinkerFlags¶
function getLinkerFlags
output String linkerFlags;
end getLinkerFlags;
getLoadedLibraries¶
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"}}
function getLoadedLibraries
output String[:, 2] libraries;
end getLoadedLibraries;
getMatchingAlgorithm¶
function getMatchingAlgorithm
output String selected;
end getMatchingAlgorithm;
getMemorySize¶
Retrieves the physical memory size available on the system in megabytes.
function getMemorySize
output Real memory(unit = "MiB");
end getMemorySize;
getMessagesString¶
see getErrorString()
function getMessagesString
output String messagesString;
end getMessagesString;
getModelicaPath¶
Get the Modelica Library Path.
The MODELICAPATH is 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 (;).
To override the default path (OPENMODELICAHOME/lib/omlibrary/:~/.openmodelica/libraries/), set the environment variable OPENMODELICALIBRARY=...
function getModelicaPath
output String modelicaPath;
end getModelicaPath;
getNoSimplify¶
Returns true if noSimplify flag is set.
function getNoSimplify
output Boolean noSimplify;
end getNoSimplify;
getNthAlgorithm¶
Returns the Nth Algorithm section.
function getNthAlgorithm
input TypeName class_;
input Integer index;
output String result;
end getNthAlgorithm;
getNthAlgorithmItem¶
Returns the Nth Algorithm Item.
function getNthAlgorithmItem
input TypeName class_;
input Integer index;
output String result;
end getNthAlgorithmItem;
getNthAnnotationString¶
Returns the Nth Annotation section as string.
function getNthAnnotationString
input TypeName class_;
input Integer index;
output String result;
end getNthAnnotationString;
getNthConnection¶
Returns the Nth connection. Example command: getNthConnection(A) => {"from", "to", "comment"}
function getNthConnection
input TypeName className;
input Integer index;
output String[:] result;
end getNthConnection;
getNthEquation¶
Returns the Nth Equation section.
function getNthEquation
input TypeName class_;
input Integer index;
output String result;
end getNthEquation;
getNthEquationItem¶
Returns the Nth Equation Item.
function getNthEquationItem
input TypeName class_;
input Integer index;
output String result;
end getNthEquationItem;
getNthImport¶
Returns the Nth Import as string.
function getNthImport
input TypeName class_;
input Integer index;
output String out[3] "{\"Path\",\"Id\",\"Kind\"}";
end getNthImport;
getNthInitialAlgorithm¶
Returns the Nth Initial Algorithm section.
function getNthInitialAlgorithm
input TypeName class_;
input Integer index;
output String result;
end getNthInitialAlgorithm;
getNthInitialAlgorithmItem¶
Returns the Nth Initial Algorithm Item.
function getNthInitialAlgorithmItem
input TypeName class_;
input Integer index;
output String result;
end getNthInitialAlgorithmItem;
getNthInitialEquation¶
Returns the Nth Initial Equation section.
function getNthInitialEquation
input TypeName class_;
input Integer index;
output String result;
end getNthInitialEquation;
getNthInitialEquationItem¶
Returns the Nth Initial Equation Item.
function getNthInitialEquationItem
input TypeName class_;
input Integer index;
output String result;
end getNthInitialEquationItem;
getOrderConnections¶
Returns true if orderConnections flag is set.
function getOrderConnections
output Boolean orderConnections;
end getOrderConnections;
getPackages¶
Returns the list of packages defined in the class.
function getPackages
input TypeName class_ = $Code(AllLoadedClasses);
output TypeName classNames[:];
end getPackages;
getParameterNames¶
Returns the list of parameters of the class.
function getParameterNames
input TypeName class_;
output String[:] parameters;
end getParameterNames;
getParameterValue¶
Returns the value of the parameter of the class.
function getParameterValue
input TypeName class_;
input String parameterName;
output String parameterValue;
end getParameterValue;
getSettings¶
function getSettings
output String settings;
end getSettings;
getShowAnnotations¶
function getShowAnnotations
output Boolean show;
end getShowAnnotations;
getSimulationOptions¶
Returns the startTime, stopTime, tolerance, and interval based on the experiment annotation.
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.
function getSourceFile
input TypeName class_;
output String filename "empty on failure";
end getSourceFile;
getTearingMethod¶
function getTearingMethod
output String selected;
end getTearingMethod;
getTempDirectoryPath¶
Returns the current user temporary directory location.
function getTempDirectoryPath
output String tempDirectoryPath;
end getTempDirectoryPath;
getTimeStamp¶
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.
function getTimeStamp
input TypeName cl;
output Real timeStamp;
output String timeStampAsString;
end getTimeStamp;
getTransitions¶
Returns list of transitions for the given class.
Each transition item contains 8 values i.e, from, to, condition, immediate, reset, synchronize, priority.
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.
function getUsedClassNames
input TypeName className;
output TypeName classNames[:];
end getUsedClassNames;
getUses¶
Returns the libraries used by the package {{"Library1","Version"},{"Library2","Version"}}.
function getUses
input TypeName pack;
output String[:, :] uses;
end getUses;
getVectorizationLimit¶
function getVectorizationLimit
output Integer vectorizationLimit;
end getVectorizationLimit;
getVersion¶
Returns the version of the Modelica compiler.
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¶
The iconv() function converts one multibyte characters from one character set 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 the Functional Mockup Unit Example command: importFMU("A.fmu");
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.";
output String generatedFileName "Returns the full path of the generated file.";
end importFMU;
importFMUModelDescription¶
Imports modelDescription.xml Example command: importFMUModelDescription("A.xml");
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¶
function inferBindings
input TypeName path;
output Boolean success;
end inferBindings;
instantiateModel¶
Instantiates the class and returns the flat Modelica code.
function instantiateModel
input TypeName className;
output String result;
end instantiateModel;
isBlock¶
Returns true if the given class has restriction block.
function isBlock
input TypeName cl;
output Boolean b;
end isBlock;
isClass¶
Returns true if the given class has restriction class.
function isClass
input TypeName cl;
output Boolean b;
end isClass;
isConnector¶
Returns true if the given class has restriction connector or expandable connector.
function isConnector
input TypeName cl;
output Boolean b;
end isConnector;
isEnumeration¶
Returns true if the given class has restriction enumeration.
function isEnumeration
input TypeName cl;
output Boolean b;
end isEnumeration;
isExperiment¶
An experiment is defined as having annotation experiment(StopTime=...)
function isExperiment
input TypeName name;
output Boolean res;
end isExperiment;
isFunction¶
Returns true if the given class has restriction function.
function isFunction
input TypeName cl;
output Boolean b;
end isFunction;
isModel¶
Returns true if the given class has restriction model.
function isModel
input TypeName cl;
output Boolean b;
end isModel;
isOperator¶
Returns true if the given class has restriction operator.
function isOperator
input TypeName cl;
output Boolean b;
end isOperator;
isOperatorFunction¶
Returns true if the given class has restriction "operator function".
function isOperatorFunction
input TypeName cl;
output Boolean b;
end isOperatorFunction;
isOperatorRecord¶
Returns true if the given class has restriction "operator record".
function isOperatorRecord
input TypeName cl;
output Boolean b;
end isOperatorRecord;
isOptimization¶
Returns true if the given class has restriction optimization.
function isOptimization
input TypeName cl;
output Boolean b;
end isOptimization;
isPackage¶
Returns true if the given class is a package.
function isPackage
input TypeName cl;
output Boolean b;
end isPackage;
isPartial¶
Returns true if the given class is partial.
function isPartial
input TypeName cl;
output Boolean b;
end isPartial;
isProtectedClass¶
Returns true if the given class c1 has class c2 as one of its protected class.
function isProtectedClass
input TypeName cl;
input String c2;
output Boolean b;
end isProtectedClass;
isRecord¶
Returns true if the given class has restriction record.
function isRecord
input TypeName cl;
output Boolean b;
end isRecord;
isShortDefinition¶
returns true if the definition is a short class definition
function isShortDefinition
input TypeName class_;
output Boolean isShortCls;
end isShortDefinition;
isType¶
Returns true if the given class has restriction type.
function isType
input TypeName cl;
output Boolean b;
end isType;
linearize¶
creates a model with symbolic linearization matrixes
Creates a model with symbolic linearization matrixes.
At stopTime the linearization matrixes are evaluated and a modelica model is created.
The only required argument is the className, while all others have some default values.
Usage:¶
linearize(A, stopTime=0.0);
Creates the file "linear_A.mo" that contains the linearized matrixes at stopTime.
function linearize
input TypeName className "the class that should simulated";
input Real startTime = "<default>" "the start time of the simulation. <default> = 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Real numberOfIntervals = 500 "number of intervals in the result file. <default> = 500";
input Real stepSize = 0.002 "step size that is used for the result file. <default> = 0.002";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default> = 1e-6";
input String method = "<default>" "integration method used for simulation. <default> = dassl";
input String fileNamePrefix = "<default>" "fileNamePrefix. <default> = \"\"";
input Boolean storeInTemp = false "storeInTemp. <default> = false";
input Boolean noClean = false "noClean. <default> = false";
input String options = "<default>" "options. <default> = \"\"";
input String outputFormat = "mat" "Format for the result file. <default> = \"mat\"";
input String variableFilter = ".*" "Filter for variables that should store in result file. <default> = \".*\"";
input String cflags = "<default>" "cflags. <default> = \"\"";
input String simflags = "<default>" "simflags. <default> = \"\"";
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), the empty string is returned.
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().
function listFile
input TypeName class_;
output String contents;
end listFile;
listVariables¶
Lists the names of the active variables in the scripting environment.
function listVariables
output TypeName variables[:];
end listVariables;
loadFile¶
load file (*.mo) and merge it with the loaded AST.
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, 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 the MODELICAPATH (for this call only).
function loadFile
input String fileName;
input String encoding = "UTF-8";
input Boolean uses = true;
output Boolean success;
end loadFile;
loadFileInteractive¶
function loadFileInteractive
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end loadFileInteractive;
loadFileInteractiveQualified¶
function loadFileInteractiveQualified
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end loadFileInteractiveQualified;
loadFiles¶
load files (*.mo) and merges them with the loaded AST.
function loadFiles
input String[:] fileNames;
input String encoding = "UTF-8";
input Integer numThreads = OpenModelica.Scripting.numProcessors();
output Boolean success;
end loadFiles;
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.
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¶
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.
function loadModelica3D
input String version = "3.2.1";
output Boolean status;
end loadModelica3D;
loadString¶
Parses the data and merges the resulting AST with ithe loaded AST. If a filename is given, it is used to provide error-messages as if the string was read in binary format from a file with the same name. The file is converted to UTF-8 from the given character set. When merge is true the classes cNew in the file will be merged with the already loaded classes cOld in the following way: 1. get all the inner class definitions from cOld that were loaded from a different file than itself 2. append all elements from step 1 to class cNew public list NOTE: Encoding is deprecated as ALL strings are now UTF-8 encoded.
function loadString
input String data;
input String filename = "<interactive>";
input String encoding = "UTF-8";
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";
output Boolean success;
end loadString;
mkdir¶
create directory of given path (which may be either relative or absolute) returns true if directory was created or already exists.
function mkdir
input String newDirectory;
output Boolean success;
end mkdir;
moveClass¶
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.
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.
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.
function moveClassToTop
input TypeName className;
output Boolean result;
end moveClassToTop;
ngspicetoModelica¶
Converts ngspice netlist to Modelica code. Modelica file is created in the same directory as netlist file.
function ngspicetoModelica
input String netlistfileName;
output Boolean success = false;
end ngspicetoModelica;
numProcessors¶
Returns the number of processors (if compiled against hwloc) or hardware threads (if using sysconf) available to OpenModelica.
function numProcessors
output Integer result;
end numProcessors;
optimize¶
optimize a modelica/optimica model by generating c code, build it and run the optimization executable. The only required argument is the className, while all others have some default values. simulate(className, [startTime], [stopTime], [numberOfIntervals], [stepSize], [tolerance], [fileNamePrefix], [options], [outputFormat], [variableFilter], [cflags], [simflags]) Example command: simulate(A);
function optimize
input TypeName className "the class that should simulated";
input Real startTime = "<default>" "the start time of the simulation. <default> = 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Real numberOfIntervals = 500 "number of intervals in the result file. <default> = 500";
input Real stepSize = 0.002 "step size that is used for the result file. <default> = 0.002";
input Real tolerance = 1e-6 "tolerance used by the integration method. <default> = 1e-6";
input String method = DAE.SCONST("optimization") "optimize a modelica/optimica model.";
input String fileNamePrefix = "<default>" "fileNamePrefix. <default> = \"\"";
input Boolean storeInTemp = false "storeInTemp. <default> = false";
input Boolean noClean = false "noClean. <default> = false";
input String options = "<default>" "options. <default> = \"\"";
input String outputFormat = "mat" "Format for the result file. <default> = \"mat\"";
input String variableFilter = ".*" "Filter for variables that should store in result file. <default> = \".*\"";
input String cflags = "<default>" "cflags. <default> = \"\"";
input String simflags = "<default>" "simflags. <default> = \"\"";
output String optimizationResults;
end optimize;
parseFile¶
function parseFile
input String filename;
input String encoding = "UTF-8";
output TypeName names[:];
end parseFile;
parseString¶
function parseString
input String data;
input String filename = "<interactive>";
output TypeName names[:];
end parseString;
plot¶
Launches a plot window using OMPlot.
Launches a plot window 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",legend=false);
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 = "detailed" "Sets the grid for the plot i.e simple, detailed, none.";
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 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 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.";
output Boolean success "Returns true on success";
end plot;
plotAll¶
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");
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 = "detailed" "Sets the grid for the plot i.e simple, detailed, none.";
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 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 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.";
output Boolean success "Returns true on success";
end plotAll;
plotParametric¶
Launches a plotParametric window using OMPlot. Returns true on success. Example command sequences: simulate(A);plotParametric(x,y); simulate(A);plotParametric(x,y, externalWindow=true);
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 = "detailed" "Sets the grid for the plot i.e simple, detailed, none.";
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 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 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.";
output Boolean success "Returns true on success";
end plotParametric;
readFile¶
The contents of the given file are returned. Note that if the function fails, the error message is returned as a string instead of multiple output or similar.
impure function readFile
input String fileName;
output String contents;
end readFile;
readFileNoNumeric¶
Returns the contents of the file, with anything resembling a (real) number stripped out, and at the end adding: Filter count from number domain: n. This should probably be changed to multiple outputs; the filtered string and an integer. Does anyone use this API call?
function readFileNoNumeric
input String fileName;
output String contents;
end readFileNoNumeric;
readSimulationResult¶
Reads a result file, returning a matrix corresponding to the variables and size given.
function readSimulationResult
input String filename;
input VariableNames variables;
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¶
The number of intervals that are present in the output file.
function readSimulationResultSize
input String fileName;
output Integer sz;
end readSimulationResultSize;
readSimulationResultVars¶
Returns the variables in the simulation file; you can use val() and plot() commands using these names.
Takes one simulation results file and returns the variables stored in it.
If readParameters is true, parameter names are 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).
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.
function realpath
input String name "Absolute or relative file or directory name";
output String fullName "Full path of 'name'";
end realpath;
regex¶
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¶
function regularFileExists
input String fileName;
output Boolean exists;
end regularFileExists;
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.
function reloadClass
input TypeName name;
input String encoding = "UTF-8";
output Boolean success;
end reloadClass;
remove¶
removes a file or directory of given path (which may be either relative or absolute).
function remove
input String path;
output Boolean success "Returns true on success.";
end remove;
removeComponentModifiers¶
Removes the component modifiers.
function removeComponentModifiers
input TypeName class_;
input String componentName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeComponentModifiers;
removeExtendsModifiers¶
Removes the extends modifiers of a class.
function removeExtendsModifiers
input TypeName className;
input TypeName baseClassName;
input Boolean keepRedeclares = false;
output Boolean success;
end removeExtendsModifiers;
reopenStandardStream¶
function reopenStandardStream
input StandardStream _stream;
input String filename;
output Boolean success;
end reopenStandardStream;
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.
function rewriteBlockCall
input TypeName className;
input TypeName inDefs;
output Boolean success;
end rewriteBlockCall;
runOpenTURNSPythonScript¶
runs OpenTURNS with the given python script returning the log file
function runOpenTURNSPythonScript
input String pythonScriptFile;
output String logOutputFile;
end runOpenTURNSPythonScript;
runScript¶
Runs the mos-script specified by the filename.
function runScript
input String fileName "*.mos";
output String result;
end runScript;
runScriptParallel¶
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).
function runScriptParallel
input String scripts[:];
input Integer numThreads = numProcessors();
input Boolean useThreads = false;
output Boolean results[:];
end runScriptParallel;
save¶
function save
input TypeName className;
output Boolean success;
end save;
saveAll¶
save the entire loaded AST to file.
function saveAll
input String fileName;
output Boolean success;
end saveAll;
saveModel¶
function saveModel
input String fileName;
input TypeName className;
output Boolean success;
end saveModel;
saveTotalModel¶
function saveTotalModel
input String fileName;
input TypeName className;
output Boolean success;
end saveTotalModel;
saveTotalSCode¶
searchClassNames¶
Searches for the class name in the all the loaded classes. Example command: searchClassNames("ground"); searchClassNames("ground", true);
Look for searchText in All Loaded Classes and their code. Returns the list of searched classes.
function searchClassNames
input String searchText;
input Boolean findInText = false;
output TypeName classNames[:];
end searchClassNames;
setAnnotationVersion¶
Sets the annotation version.
function setAnnotationVersion
input String annotationVersion;
output Boolean success;
end setAnnotationVersion;
setCFlags¶
CFLAGS
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.
function setCFlags
input String inString;
output Boolean success;
end setCFlags;
setCXXCompiler¶
CXX
function setCXXCompiler
input String compiler;
output Boolean success;
end setCXXCompiler;
setCheapMatchingAlgorithm¶
example input: 3
function setCheapMatchingAlgorithm
input Integer matchingAlgorithm;
output Boolean success;
end setCheapMatchingAlgorithm;
setClassComment¶
Sets the class comment.
function setClassComment
input TypeName class_;
input String filename;
output Boolean success;
end setClassComment;
setCommandLineOptions¶
The input is a regular command-line flag given to OMC, e.g. -d=failtrace or -g=MetaModelica
function setCommandLineOptions
input String option;
output Boolean success;
end setCommandLineOptions;
setCompileCommand¶
function setCompileCommand
input String compileCommand;
output Boolean success;
end setCompileCommand;
setCompiler¶
CC
function setCompiler
input String compiler;
output Boolean success;
end setCompiler;
setCompilerFlags¶
function setCompilerFlags
input String compilerFlags;
output Boolean success;
end setCompilerFlags;
setCompilerPath¶
function setCompilerPath
input String compilerPath;
output Boolean success;
end setCompilerPath;
setDebugFlags¶
example input: failtrace,-noevalfunc
function setDebugFlags
input String debugFlags;
output Boolean success;
end setDebugFlags;
setDefaultOpenCLDevice¶
Sets the default OpenCL device to be used.
function setDefaultOpenCLDevice
input Integer defdevid;
output Boolean success;
end setDefaultOpenCLDevice;
setDocumentationAnnotation¶
Used to set the Documentation annotation of a class. An empty argument (e.g. for revisions) means no annotation is added.
function setDocumentationAnnotation
input TypeName class_;
input String info = "";
input String revisions = "";
output Boolean bool;
end setDocumentationAnnotation;
setEnvironmentVar¶
function setEnvironmentVar
input String var;
input String value;
output Boolean success;
end setEnvironmentVar;
setIndexReductionMethod¶
example input: dynamicStateSelection
function setIndexReductionMethod
input String method;
output Boolean success;
end setIndexReductionMethod;
setInitXmlStartValue¶
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.
function setInstallationDirectoryPath
input String installationDirectoryPath;
output Boolean success;
end setInstallationDirectoryPath;
setLanguageStandard¶
Sets the Modelica Language Standard.
function setLanguageStandard
input String inVersion;
output Boolean success;
end setLanguageStandard;
setLinker¶
function setLinker
input String linker;
output Boolean success;
end setLinker;
setLinkerFlags¶
function setLinkerFlags
input String linkerFlags;
output Boolean success;
end setLinkerFlags;
setMatchingAlgorithm¶
example input: omc
function setMatchingAlgorithm
input String matchingAlgorithm;
output Boolean success;
end setMatchingAlgorithm;
setModelicaPath¶
The Modelica Library Path - MODELICAPATH in the language specification; OPENMODELICALIBRARY in OpenModelica.
See loadModel() for a description of what the MODELICAPATH is used for.
function setModelicaPath
input String modelicaPath;
output Boolean success;
end setModelicaPath;
setNoSimplify¶
Sets the noSimplify flag.
function setNoSimplify
input Boolean noSimplify;
output Boolean success;
end setNoSimplify;
setOrderConnections¶
Sets the orderConnection flag.
function setOrderConnections
input Boolean orderConnections;
output Boolean success;
end setOrderConnections;
setPlotCommand¶
function setPlotCommand
input String plotCommand;
output Boolean success;
end setPlotCommand;
setPostOptModules¶
example input: lateInline,inlineArrayEqn,removeSimpleEquations.
function setPostOptModules
input String modules;
output Boolean success;
end setPostOptModules;
setPreOptModules¶
example input: removeFinalParameters,removeSimpleEquations,expandDerOperator
function setPreOptModules
input String modules;
output Boolean success;
end setPreOptModules;
setShowAnnotations¶
function setShowAnnotations
input Boolean show;
output Boolean success;
end setShowAnnotations;
setSourceFile¶
function setSourceFile
input TypeName class_;
input String filename;
output Boolean success;
end setSourceFile;
setTearingMethod¶
example input: omcTearing
function setTearingMethod
input String tearingMethod;
output Boolean success;
end setTearingMethod;
setTempDirectoryPath¶
function setTempDirectoryPath
input String tempDirectoryPath;
output Boolean success;
end setTempDirectoryPath;
setVectorizationLimit¶
function setVectorizationLimit
input Integer vectorizationLimit;
output Boolean success;
end setVectorizationLimit;
simulate¶
simulates a modelica model by generating c code, build it and run the simulation executable. The only required argument is the className, while all others have some default values. simulate(className, [startTime], [stopTime], [numberOfIntervals], [tolerance], [method], [fileNamePrefix], [options], [outputFormat], [variableFilter], [cflags], [simflags]) Example command: simulate(A);
function simulate
input TypeName className "the class that should simulated";
input Real startTime = "<default>" "the start time of the simulation. <default> = 0.0";
input Real stopTime = 1.0 "the stop time of the simulation. <default> = 1.0";
input Real 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 = "<default>" "integration method used for simulation. <default> = dassl";
input String fileNamePrefix = "<default>" "fileNamePrefix. <default> = \"\"";
input String options = "<default>" "options. <default> = \"\"";
input String outputFormat = "mat" "Format for the result file. <default> = \"mat\"";
input String variableFilter = ".*" "Filter for variables that should store in result file. <default> = \".*\"";
input String cflags = "<default>" "cflags. <default> = \"\"";
input String simflags = "<default>" "simflags. <default> = \"\"";
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;
solveLinearSystem¶
Solve A*X = B, using dgesv or lp_solve (if any variable in X is integer) Returns for solver dgesv: info>0: Singular for element i. info<0: Bad input. For solver lp_solve: ???
function solveLinearSystem
input Real[size(B, 1), size(B, 1)] A;
input Real[:] B;
input LinearSystemSolver solver = LinearSystemSolver.dgesv;
input Integer[:] isInt = {-1} "list of indices that are integers";
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;
stringReplace¶
Replaces all occurances of the string source with target.
function stringReplace
input String str;
input String source;
input String target;
output String res;
end stringReplace;
stringSplit¶
Splits the string at the places given by the character
function stringSplit
input String string;
input String token "single character only";
output String[:] strings;
end stringSplit;
stringTypeName¶
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¶
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 the strings at the places given by the token, for example: strtok("abcbdef","b") => {"a","c","def"} strtok("abcbdef","cd") => {"ab","ef"}
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¶
function testsuiteFriendlyName
input String path;
output String fixed;
end testsuiteFriendlyName;
threadWorkFailed¶
(Experimental) Exits the current (worker thread) signalling a failure.
translateGraphics¶
function translateGraphics
input TypeName className;
output String result;
end translateGraphics;
translateModelFMU¶
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: translateModelFMU(className, version="2.0");
function translateModelFMU
input TypeName className "the class that should translated";
input String version = "2.0" "FMU version, 1.0 or 2.0.";
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 Boolean includeResources = false "include Modelica based resources via loadResource or not";
output String generatedFileName "Returns the full path of the generated FMU.";
end translateModelFMU;
typeNameString¶
function typeNameString
input TypeName cl;
output String out;
end typeNameString;
typeNameStrings¶
function typeNameStrings
input TypeName cl;
output String out[:];
end typeNameStrings;
typeOf¶
function typeOf
input VariableName variableName;
output String result;
end typeOf;
updateInitialState¶
Updates the initial state in the class.
function updateInitialState
input TypeName cl;
input String state;
input ExpressionOrModification annotate;
output Boolean bool;
end updateInitialState;
updateTransition¶
Updates the transition in the class.
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;
uriToFilename¶
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 = "";
output String message = "";
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.
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;
verifyCompiler¶
function verifyCompiler
output Boolean compilerWorks;
end verifyCompiler;
writeFile¶
Write the data to file. Returns true on success.
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. First we start the system, and use the command line interface from OMShell, OMNotebook, or command window of some of the other tools.
We type in a very small model:
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,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-06, method = 'dassl', fileNamePrefix = 'Test', options = '', outputFormat = 'mat', variableFilter = '.*', cflags = '', simflags = ''",
messages = "stdout | info | The initialization finished successfully without homotopy method.
stdout | info | The simulation finished successfully.
stdout | info | Time measurements are stored in Test_prof.html (human-readable) and Test_prof.xml (for XSL transforms or more details)
",
timeFrontend = 0.005379554,
timeBackend = 0.004176158,
timeSimCode = 0.069358613,
timeTemplates = 0.03736329400000001,
timeCompile = 0.323386828,
timeSimulation = 0.034438472,
timeTotal = 0.474201102
end SimulationResult;
>>> val(x , 2.0)
7.0
>>> plotall()
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.104622125411205,-1.104622125411205,0.0,0.0,0.0,0.0,0.0},0.0,8,1)