Search code examples
modelica

How to check constraint on absolute time to terminate process without affecting simulation performance?


I want to read the current date and if the date is outside a constraint then the system should be terminated. The code below works.

    import Modelica.Utilities.System.getTime; 
    model M
       Integer[7] today;
       constant Integer[7] limit={0,0,0,0,0,0,2021};
       Real x;
    equation
       today = getTime();
       if today[7] > limit[7] then
          terminate();
       end if;
       // Process
       x = 1;
    end M;

But it would be much better to just read the date at startup and avoid check the date all the time which should be a burden although not obvious from running the code above.

Most logical would be an initial algorithmic (or equation) section to get the date with getTime() and also terminate() if appropriate.

But just change the current section to "initial equation" gives compilation error with the error text: "...The following variables(s) could not be matched to any equation: today[1], .... today[7]."


Solution

  • You don't need today in the model so you could just move this to a function:

    import Modelica.Utilities.System.getTime; 
    
    function afterLimit
      input Integer limit[7];
      output Boolean after;
    protected
      Integer[7] today;
    algorithm
      (,,,,,,today[7]) := getTime();
      after := today[7]>limit[7];
    end afterLimit;
    
    model M
      constant Integer[7] limit={0,0,0,0,0,0,2021};
      Real x;
    initial equation
      if afterLimit(limit) then
        terminate("Time is up!");
      end if;
    equation
      // Process
      x = 1;
    end M;
    

    Alternatively you could make it a parameter with fixed=false as suggested by @ReneJustNielsen