Search code examples
openmodelica

Syntax Error, Parser error: Unexpected token, optimization class


I got this Syntax error while trying an optimization example from openmodelica users guide.

model BatchReactor
  Real x1(start =1, fixed=true, min=0, max=1);
  Real x2(start =0, fixed=true, min=0, max=1);
  input Real u(min=0, max=5);
equation
  der(x1) = -(u+u^2/2)*x1;
  der(x2) = u*x1;
end BatchReactor;
optimization nmpcBatchReactor(objective=-x2)
  extends BatchReactor;
end nmpcBatchReactor;

OMEdit reports following error.

[1] 12:34:26 Syntax Error
[xx: 9:1-9:13]: Parser error: Unexpected token near: optimization (IDENT)

what is the syntax for the class optimization?


Solution

  • This is an extension to Modelica called Optimica and you need to activate a special flag in OMEdit to be able to use it.

    Go to OMEdit->Tools->Options->Simulation and add: -g=Optimica to the additional translation flags. Or just run the examples via OMNotebook or omc from command line with omc -g=Optimica script.mos

    enter image description here

    The integration with optimization is not that good in OMEdit so you need to do quite some manual steps.

    To use it in OMEdit you also need to wrap the classes in a package as Modelica supports just one entity per file:

    package BatchReactor
    
    model BatchReactor
      Real x1(start =1, fixed=true, min=0, max=1);
      Real x2(start =0, fixed=true, min=0, max=1);
      input Real u(min=0, max=5);
    equation
      der(x1) = -(u+u^2/2)*x1;
      der(x2) = u*x1;
    end BatchReactor;
    
    optimization nmpcBatchReactor(objective=-x2)
      extends BatchReactor;
    end nmpcBatchReactor;
    
    end BatchReactor;
    

    Looks like this in OMEdit:

    OMEdit

    To run the optimization in OMEdit you need to go via: OMEdit->Tools->OpenModelica Compiler CLI

    OMEdit OMC CLI

    Then you enter the command to optimize:

    optimize(BatchReactor.nmpcBatchReactor, numberOfIntervals=16, stopTime=1, tolerance=1e-8)
    

    enter image description here

    Then you need to manually open the result file, the path you will see in the output from the optimize command, for me is:

    resultFile = "C:/temp/BatchReactor.nmpcBatchReactor_res.mat"
    

    Go to OMEdit->File->Open Result File (s), navigate to the path and open the .mat file. Then you get to the plotting view and you can select what variables you want to plot.

    enter image description here

    As I said, the integration of optimizaton with OMEdit is quite bad so you might as well use OMNotebook or directly the omc command line.