Main Content

Run Rapid Simulations over a Range of Parameter Values

You can use the RSim system target file to run simulations over a range of parameter values.

Prepare Model

  1. Open the model. For example:

    mdlName = 'RapidSim';
    open_system(mdlName);
  2. Open the Simulink Coder app.

  3. Set model configuration parameter System target file to rsim.tlc. For example:

    cs = getActiveConfigSet(mdlName);
    cs.switchTarget('rsim.tlc',[]);
  4. Define tunable variables (for example, initial conditions for states and gain values). Convert the variables to Simulink.Parameter objects. Then, configure the objects to use a storage class other than Auto. For example:

    INIT_X1 = Simulink.Parameter(INIT_X1);
    INIT_X1.StorageClass = 'Model default';
    
    INIT_X2 = Simulink.Parameter(INIT_X2);
    INIT_X2.StorageClass = 'Model default';
    
    MU = Simulink.Parameter(MU);
    MU.StorageClass = 'Model default';
  5. Define the names of files that will be created. For example:

    prmFileName = [mdlName, '_prm_sets.mat'];
    logFileName = [mdlName, '_run_scr.log'];
    batFileName = [mdlName, '_run_scr'];
    exeFileName = mdlName;
    if ispc
        exeFileName = [exeFileName, '.exe'];
        batFileName = [batFileName, '.bat'];
    end
    aggDataFile = [mdlName, '_results'];
    startTime = cputime;

Build Model

Build the RSim executable program for the model. During the build process, a structural checksum is calculated for the model and embedded into the generated executable program. This checksum is used to check that a parameter set passed to the executable program is compatible with the program.

For example:

slbuild(mdlName);

Get Default Parameter Set for Model

Get the default rtP structure (parameter set) for the model by using the rsimgetrtp function. The modelChecksum field in the rtP structure is the structural checksum of the model. This must match the checksum embedded in the RSim executable program. If the two checksums do not match, the executable program produces an error. The rsimgetrtp function generates an rtP structure with entries for named tunable variables.

For example:

rtp = rsimgetrtp(mdlName)

Create Parameter Sets

Using the rtp structure, build a structure array with different values for the tunable variables in the model. For example you might want see how state trajectories evolve for different initial values for states in the model. To do this, generate different parameter sets with different values for each parameter.

For example:

INIT_X1_vals = -5:1:5;
INIT_X2_vals = -5:1:5;
nPrmSets = length(INIT_X1_vals)*length(INIT_X2_vals)

Save the rtp structure array with the parameter sets to a MAT-file.

save(prmFileName,'rtp');

Create Batch File

Create a batch script file to run the RSim executable program over the parameter sets. For this batch script, each run reads the specified parameter set from the parameter MAT-file and writes the results to the specified output MAT-file. The time out option provides a way to abort the run after the specified time limit and proceed to the next run if a run stops executing (for example, because the model has a singularity for that parameter set).

fid = fopen(batFileName, 'w');
idx = 1;
for iX1 = INIT_X1_vals
    for iX2 = INIT_X2_vals
        for iMU = MU_vals
            outMatFile = [mdlName, '_run',num2str(idx),'.mat'];
            cmd = [exeFileName, ...
                   ' -p ', prmFileName, '@', int2str(idx), ...
                   ' -o ', outMatFile, ...
                   ' -L 3600'];
            if ispc
                cmd  = [cmd, ' 2>&1>> ', logFileName];
            else % (unix)
                cmd  = ['.' filesep cmd, ' 1> ', logFileName, ' 2>&1'];
            end
            fprintf(fid, ['echo "', cmd, '"\n']);
            fprintf(fid, [cmd, '\n']);
            idx = idx + 1;
        end
    end
end
if isunix
    system(['touch ', logFileName]);
    system(['chmod +x ', batFileName]);
end
fclose(fid);

For example, this command (on Windows®) specifies using the third parameter set from the rtP structure in prm.mat, writes the results to run3.mat, and aborts execution if a run takes longer than 3600 seconds of CPU time. While running, the script pipes messages from model.exe to run.log, which you can use to debug issues.

model.exe -p prm.mat@3 -o run3.mat -L 3600 2>&1>> run.log 

Creating a batch/script file to run simulations enables you to call the system command once to run the simulations (or even run the batch script outside of MATLAB®) instead of calling the system command in a loop for each simulation. This improves performance because the system command has significant overhead.

Execute Batch File to Run simulations

Run the batch/script file, which runs the RSim executable program once for each parameter set and saves the results to a different MAT-file each time. You can run the batch file from outside MATLAB.

For example:

[stat, res] = system(['.' filesep batFileName]);
if stat ~= 0
    error(['Error running batch file ''', batFileName, ''' :', res]);
end

Your script can generate multiple batch files and run them in parallel by distributing them across multiple computers. Also, you can run the batch files without launching MATLAB.

Load Output MAT-Files and Collate Results

Collect the simulation results from the output MAT-files into a structure. If the output MAT-file corresponding to a particular run is not found, set the results corresponding to that run to NaN (not a number). This situation occurs if a simulation run with a particular set of parameters encounters singularities in the model.

For example:

idx = 1;
for iX1 = INIT_X1_vals
    for iX2 = INIT_X2_vals
        for iMU = MU_vals
            outMatFile = [mdlName, '_run',num2str(idx),'.mat'];
            if exist(outMatFile,'file')
                load(outMatFile);
                aggData(idx).tout = rt_tout;
                aggData(idx).yout = rt_yout;
            else
                aggData(idx).tout = nan;
                aggData(idx).yout = nan;
            end
            idx = idx + 1;
        end
    end
end

Save the structure to the results MAT-file. At this point, you can delete other MAT-files, as the saved data structure contains the aggregation of input (parameters sets) and output data (simulation results).

For example:

save(aggDataFile,'aggData');
disp(['Took ', num2str(cputime-startTime), ...
      ' seconds to generate results from ', ...
      num2str(nPrmSets), ' simulation runs.']);

Analyze Simulation Results

Plot and analyze the simulation results.

For example:

colors = {'b','g','r','c','m','y','k'}; nColors = length(colors);
for idx = 1:nPrmSets
    col = colors{idx - nColors*floor(idx/nColors) + 1};
    plot(aggData(idx).prms.INIT_X1, aggData(idx).prms.INIT_X2, [col,'x'], ...
         aggData(idx).yout(:,1), aggData(idx).yout(:,2),col);
    hold on
end
grid on
xlabel('X1'); 
ylabel('X2'); 
axis('square');