AnyLogic stop simulation: finish() - anylogic

I'm trying to stop my anylogic model during setup.
I tried to use getEngine().finish() or getEngine().pause() but is seems like these functions only work when the simulation is already running. In my case, I am trying to handle a situation where I need to finish the simulation at the begging (during model initiation) when getEngine().getState() is still at PLEASE_WAIT.
Any thoughts?
getEngine().finish() and finishSimulation()

Related

Anylogic: Running a model but stuck suddenly without any error

I'm new to Anylogic and created a simple traffic model. Only use 'carSource', 'CarMoveTo', 'Car Dispose' blocks to set the car routes. But After I ran the model, it worked for a while, then all the cars froze without any error occurring. ’Events‘ panel also stopped. How to solve it?
Most likely your model is running into an infinite loop somewhere in the logic. The first place to check would be all your loops that might become infinite,e.g Do loops, Do-while loops, iterator for loops where you perhaps change the counter variable manually...
If you have the professional version of AnyLogic the best option is to run the model in debug mode until you get this to the point where it freezes and then press pause. You will then see where in the code the model is getting stuck.
If this does not work you might need to start putting traceln in major functions and see ing you can spot the last traceln that gets printed and keep on adding more and more until you can find the point between two traceln where the model freezes
I had the same problem, that after a certain time, all cars froze and there wasn't a signle error.
The problem on my side was that the stop line was too close to the intersection, so I moved it a little bit farther.

Abort execution of parsim

For the use case of being able to abort parallel simulations with a MATLAB GUI, I would like to stop all scheduled simulations after the user pressed the Stop button.
All simulations are submitted at once using the parsim command, hence something like a callback to my GUI variables (App Designer) would be the most preferable solution.
Approaches I have considered but were not exactly providing a desirable solution:
The Simulation Manager provides the functionality to close simulations using its own interface. If I only had the code its Stop button executes...
parsim uses the Simulink.SimulationInput class as input to run simulations, allowing to modify the preSimFcn at the beginning of each simulation. I have not found a way to "skip" the simulation at its initialization phase apart from intentionally throwing an error so far.
Thank you for your help!
Update 1: Using the preSimFcn to set the the termination time equal to the start time drastically reduces simulation time. But since the first step still is computed there has to be a better solution.
simin = simin.setModelParameter('StopTime',get_param(mdl,'StartTime'))
Update 2: Intentionally throwing an error executing the preSimFcn, for example by setting it to
simin = simin.setModelParameter('SimulationCommand','stop')
provides the shortest termination times for me so far. Though, it requires catching and identifying the error in the ErrorMessageof the Simulink.SimulationOutput object. As this is exactly the "ugly" implementation I wanted to avoid, the issue is still active.
If you are using 17b or later, parsim provides an option to 'RunInBackground'. It returns an array of Future objects.
F = parsim(in, 'RunInBackground', 'on')
Please note that is only available for parallel simulations. The Simulink.Simulation.Future object F provides a cancel method which will terminate the simulation. You can use the fetchOutputs methods to fetch the output from the simulation.
F.cancel();

Update S-function Parameters in Fast Restart

I have read the Mathworks documentation carefully and tried to find a solution on forums as well. However, I have not been able to find a solution to my problem yet.
I am using Matlab/Simulink to simulate the dynamics of a vehicle, which picks up an object during operation. The way I am planning to do this is to:
Simulate the motions of the vehicle by itself at the start of the simulation;
Stop the simulation, save the final state, update the model parameters (so that they now represent the vehicle and the object)
Initialize the simulation again starting from the end time of the previous run and using the previous final state as input state to the new simulation.
To do this, I have been using the options FastRestart, SaveFinalState, SaveCompleteFinalSimState and update. Unluckily, the simulation runs seamlessly, but the model parameters are not updated.
The dynamics of the vehicle and vehicle+body are modelled by the same C-coded S-function. This function receives the parameters of the dynamic equations (e.g. inertia, damping, etc.) as parameters to the S-function block. I think this is the main problem with my approach: even though I run the update command, the S-function does not recognize the update of the parameters in the workspace. Do I need to recompile it? I guess that is not feasible under Fast Restart mode, is it?
Any advise is really appreciated! Thank you!
I have a similar issue to this in a different situation. Trying to update the initial state target of a revolute joint, the fast restart option does not change the property.
I have had some luck updating the model in fastrestart with other parameters, however, using:
set_param('Model_Name','TunableVars','Variable Name')
Not sure if this will help in your situation, perhaps saving the final state as a variable and having the respective variables as initial parameters.

Managing multiple anylogic simulations within an experiment

We are developing an ABM under AnyLogic 7 and are at the point where we want to make multiple simulations from a single experiment. Different parameters are to be set for each simulation run so as to generate results for a small suite of standard scenarios.
We have an experiment that auto-starts without the need to press the "Run". Subsequent pressing of the Run does increment the experiment counter and reruns the model.
What we'd like is a way to have the auto-run, or single press of Run, launch a loop of simulations. Within that loop would be the programmatic adjustment of the variables linked to passed parameters.
EDIT- One wrinkle is that some parameters are strings. The Optimization or Parameter Variation experiments don't lend themselves to enumerating a set of strings to be be used across a set of simulation runs. You can set a string per parameter for all the simulation runs within one experiment.
We've used the help sample for "Running a Model from Outside Without Presentation Window", to add the auto-run capability to the initial experiment setup block of code. A method to wait for Run 0 to complete, then dispatch Run 1, 2, etc, is needed.
Pointers to tutorial models with such features, or to a snip of code for the experiment's java blocks are much appreciated.
maybe I don't understand your need but this certainly sounds like you'd want to use a "Parameter Variation" experiment. You can specify which parameters should be varied in which steps and running the experiment automatically starts as many simulation runs as needed, all without animation.
hope that helps
As you, I was confronted to this problem. My aim was to use parameter variation with a model and variation were on non numeric data, and I knew the number of runs to start.
Then i succeed in this task with the help of Custom Variation.
Firstly I build an experiment typed as 'multiple run', create my GUI (user was able to select the string values used in each run.
Then, I create a new java class which inherit from the previous 'multiple run' experiment,
In this class (called MyMultipleRunClass) was present:
- overload of the getMaximumIterations method from default experiment to provide to default anylogic callback the correct number of iteration, and idnex was also used to retrieve my parameter value from array,
- implementation of the static method start,
public static void start() {
prepareBeforeExperimentStart_xjal( MyMultipleRunClass.class);
MyMultipleRunClass ex = new MyMultipleRunClass();
ex.setCommandLuneArguments_xjal(null);
ex.setup(null);
}
Then the experiment to run is the 'empty' customExperiment, which automatically start the other Multiple run experiment thru the presented subclass.
Maybe it exists shortest path, but from my point of view anylogic is correctly used (no trick with non exposed interface) and it works as expected.

How to export simulink data to workspace during simulation?

I want to retrieve the data from simulink during simulation, and use serial network function to send these data to another program. Because I need to use another program to do some tricks and send command back to simulink, so I have to get data from simulink during runtime so that another program can make the right command.
I've tried using To Workspace block to export the data.
However, I can only got value in the very beginning of the simulation.
And I've also tried using scope and change some properties: check Save Data To Workspace and Uncheck Limite data to Last.
First, I started simulation, and I found the ScopeData didn't appear in the Workspace. Only when I stop simulation, ScopeData would appear in workspace.
And after that, I can use ScopeData.signals.values to get values.
But what I want is: when I start simulation, ScopeData would appear in workspace so that I can send these data to other program.
Does anyone know how to achieve this?
I found this page might be helpful, but I still don't know how to continuously export data during simulation.
Use get_param to read data from just at the current time. Also to send the data back to Simulink with set_param of a gain or another block.
An example of get_param
First load and start the simulation:
load_system('myModel')
set_param('myModel','SimulationCommand','Start');
To read data on any line of your simulink model:
Get a simulink block object (let's try a Clock with the name Clock):
block = 'myModel/Clock';
rto = get_param(block, 'RuntimeObject');
Then get the data on its first (or any) output port (or input) of that block.
time = rto.OutputPort(1).Data;
You could do the reading, in a timer callback.
Also this might be helpful: Command Line Functionality for Simulink
During simulation Simulink stores logged data in an internal buffer and only writes the data to the Workspace when the simulation is paused or stopped.
It sounds as if you really need to write an S-function (which will get signal values on a timestep-by-timestep basis) and communicate with Proteus that way.
Of course Simulink is a non-realtime simulator, so if you are talking about doing anything resembling real-time control then you are most likely taking the wrong approach altogether.
At any time during simulation you can force Simulink to write the simulation output data to the workspace:
set_param(bdroot,'SimulationCommand','WriteDataLogs');
I've found that this command is quite unstable in my Matlab 2010a for Win64. In particular I have to avoid it when simulation is stopped (i.e. first check
get_param(bdroot,'SimulationStatus') ), otherwise Matlab shows an error and asks to be restarted.