Is is possible to programmatically play a Simulink model and measure its states? - matlab

I am looking to set up a test set for an existing Simulink model. Ideally I could take full control of the model, explicitly stepping it and measuring the state of any signal on any bus in the model.
As might have been gleaned, this is the precursor of a unit testing system for the model. Being so, I can't really justify changing the model to suit the test, the test must accommodate the model as-is.
The furthest I've got so far is using load_model() to return a handle to the model. From there there seems to be a quite obscure set of functions for accessing the model. I can't see any that relate to accessing states and can't see any further commands that relate to accessing a loaded model.

The easiest way is to use the Data Import/Export function within the Simulink Preferences.
Set the checkbox States and it will store every state of your system for every time step in your workspace, also when you pause the simulation or execute it step by step.
Be aware not to set Save simulation output as single object, in this case the access would be more complicated and you need to follow the instructions here.

To add to the other answer, you probably want to check this page in the documentation: Control Simulation Using the set_param Command. Of interest are the following commands:
set_param(<model_name>, 'SimulationCommand', 'start')
set_param(<model_name>, 'SimulationCommand', 'pause')
set_param(<model_name>, 'SimulationCommand', 'WriteDataLogs')
set_param(<model_name>, 'SimulationCommand', 'continue')
Replace <model_name> by the path to your model file.

Related

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.

How can I pass Bus signal input to simulink model during runtime

I have a simulink model which takes Bus signal as input. I have passed the bus signal data using Configuration->Data import/export ->input
Now I want to vary this signal from workspace when model is running and see the output during runtime.
But model is taking new data from workspace only when you stop the model and run again. Is there any way to feed the input to model during runtime?
By default Simulink looks in the Workspace for data at initialization, not at every time step. Hence the behaviour you are seeing.
To make it look in the workspace during the simulation you need to force it to do so. This can be done by using set_param to change a dialog parameter.
Once you've made a change to the variable in the workspace, in your case, something like set_param(gcs,'ExternalInput',get_param(gcs,'ExternalInput')) should work.
This is just getting the string that is in the dialog box and poking the (same) string back into the dialog.
This tells Simulink that something has changed and it'll go and re-read the variables.

Set Filename of ToFile Block after Model has Finished

I have a series of ToFile blocks in my Simulink model that each have a unique filename (e.g. "Pulse.mat". I want to store the results of my simulation in timestamped folders based roughly on when I hit the run button / use the sim command.
My solution was to write two scripts, one called during the InitFcn callback and one for the StopFcn/CloseFcn callback (and PreSaveFcn callback).
The InitFcn callback would find all ToFile blocks and change the filename from "Pulse.mat" to something like "../runs//Pulse.mat", and the StopFcn/CloseFcn/PreSaveFcn to revert them to their original ".mat" names. This worked on my small test model, however when I attempted to integrate it into my actual model I receive the following error:
Error evaluating 'StopFcn' callback of block_diagram '<model_name>'.
Caused by:
Cannot change parameter 'Filename' of '<ToFile Block>' while simulation is running. The block was made virtual as it was optimized for simulation
From my research I discovered that the StopFcn actually executes before the simulation is "done" (for whatever reason), but why did it work in my initial test model? Do my ToFile blocks in my actual model have some property set that causes this error to occur?
The block has been virtualised in your larger model; which seems to be changing the execution point. One option might be to untick 'Block Reduction' in the 'Optimisation' pane of the model configuration parameters dialogue.
Alternatively, there might be another approach that you could try -
Setting the model properties 'StartFcn' to something like :
evalin('base','resultTimTag = datestr(clock, ''yyyymmdd_HHhMM'');')
and setting the model properties 'StopFcn' to :
targetDir = evalin('base','resultTimTag');
mkdir(targetDir);
outputs = dir('*.mat');
for i=1:length(outputs)
movefile(outputs(i).name,targetDir);
end
evalin('base','clear resultTimeTag');
It's possibly a little more brute-force than your approach, but seems to work quite nicely...

Omnet++: getting .ned file after simulations has ended

When my simulation, using Omnet++, starts, there is a .ned file describing the initial scenario (in my case it shows a certain type of a network configuration). During the simulation this scenario changes, come times it changes very much. Is there a way to get a .ned file describing the final scenario after the simulation has ended? So that I can analyze it with a script...
thnaks
Not the NED file, because that describes the initial network structure in an abstract way (i.e. it can contain vectors, loops, conditional statements etc.)
What you need is a simple dump of all or selected objects. You should use the 'snapshot feature' for this. It produces a nicely formatted XML output. You can read more about it in the manual:
http://www.omnetpp.org/doc/omnetpp/manual/usman.html#sec299

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.