Exit in Modelica

Here’s an idiomatic Modelica example demonstrating the concept of exiting a program:

model ExitExample
  import Modelica.Utilities.System;
  
  function exitProgram
    input Integer status;
  algorithm
    System.exit(status);
  end exitProgram;
  
equation
  when time > 5 then
    exitProgram(3);
  end when;
  
  annotation(
    experiment(StopTime=10)
  );
end ExitExample;

This Modelica code demonstrates how to exit a simulation prematurely with a specific exit status. Let’s break it down:

  1. We define a model called ExitExample.

  2. We import the System package from Modelica’s standard library, which provides system-related functions, including exit.

  3. We define a function exitProgram that takes an integer status as input. This function wraps the System.exit() call, which terminates the simulation with the given status code.

  4. In the equation section, we use a when clause to trigger the exit condition. In this case, when the simulation time exceeds 5 seconds, the exitProgram function is called with a status code of 3.

  5. We add an annotation to set the experiment’s stop time to 10 seconds. However, due to our exit condition, the simulation will terminate before reaching this time.

To run this simulation:

  1. Save the code in a file named ExitExample.mo.
  2. Open your Modelica simulation environment (e.g., OpenModelica, Dymola).
  3. Load the model and run the simulation.

You should observe that the simulation stops at approximately 5 seconds, instead of the full 10 seconds specified in the experiment annotation. The exact behavior might vary slightly depending on the Modelica tool you’re using.

It’s important to note that unlike some other programming languages, Modelica doesn’t typically use exit codes in the same way. The System.exit() function is primarily used for terminating simulations prematurely, rather than returning status codes to an operating system.

Also, be aware that the System.exit() function might not be supported in all Modelica simulation environments, as it depends on the specific implementation of the Modelica Standard Library and the simulation tool being used.

In practice, it’s often better to use Modelica’s built-in termination conditions or events to control simulation duration, rather than forcefully exiting the program. However, this example demonstrates how you could implement an exit-like behavior if needed.