Simulation and Scoring

f_sim_score

Code

 1function [score,rst,rst_not_simd] = f_sim_score(parameters, stg, model_folders)
 2% This function calculates the total score of a given model by simulating
 3% its performance and scoring the results.
 4%
 5% Inputs:
 6% - parameters: A double containing the model's parameters necessary for
 7% the simulation.
 8% - stg: A structure containing the settings and configurations for the
 9% simulation and scoring process.
10% - model_folders: A structure containing the paths to the folders where
11% the model and other relevant files are stored.
12%
13% Outputs:
14% - score: A scalar value representing the total score of the model's
15% performance.
16% - rst: A structure containing the results of the simulation and scoring
17% process.
18% - rst_not_simd: A structure containing the results of the simulation and
19% scoring process with the 'simd' field removed.
20%
21% Used Functions:
22% - f_prep_sim: Simulates the model using the provided parameters,
23% settings, and model folders.
24% - f_score: Calculates the score of the model based on the results of the
25% simulation.
26%
27% Variables:
28% Loaded:
29% - None.
30%
31% Initialized:
32% - None.
33%
34% Persistent:
35% - None.
36%
37
38%Turn off Dimension analysis warning from simbiology
39warning('off','SimBiology:DimAnalysisNotDone_MatlabFcn_Dimensionless')
40
41% Call the function that simulates the model
42rst = f_prep_sim(parameters, stg, model_folders);
43
44% Call the function that scores
45rst = f_score(rst, stg, model_folders);
46
47% Get the total score explicitly for optimization functions
48score = rst.st;
49
50rst_not_simd = rmfield( rst , 'simd');
51end

This function, f_sim_score, calculates the total score of a given model by simulating the model and scoring its performance. The function takes three input arguments: parameters, stg, and model_folders. The output of the function includes the total score (score), the result of the simulation and scoring (rst), and the result of the simulation and scoring without the ‘simd’ field (rst_not_simd).

  • Inputs

    • stg - Structure containing the settings and configurations for the simulation and scoring process.

    • parameters - Double containing the model’s parameters that are necessary for the simulation.

    • model_folders: Structure containing the paths to the folders where the model and other relevant files are stored.

  • Outputs

    • score - rst.st Scalar value representing the total score of the model’s performance.

    • rst - rst.simd, rst.xfinal, rst.sd, rst.se, and rst.st Structure containing the results of the simulation and scoring process.

    • rst_not_simd - rst.xfinal, rst.sd, rst.se, and rst.st Structure containing the results of the simulation and scoring process with the ‘simd’ field removed.

  • Calls

    • f_prep_sim This function simulates the model using the provided parameters, settings, and model folders.

    • f_score This function calculates the score of the model based on the results of the simulation.

f_prep_sim

Code

  1function result = f_prep_sim(parameters,stg,model_folders)
  2% This function prepares the parameters for a simulation by setting them
  3% to the default values defined in the SBTAB and then updating any
  4% parameters that are being tested. The parameters are also adjusted
  5% according to any thermodynamic constraints.
  6%
  7% Inputs:
  8% - parameters: Array of parameter values that need to be tested
  9% - stg: Settings structure containing various settings for the simulation
 10% - model_folders: Structure containing folder paths for the model data
 11%
 12% Outputs:
 13% - result: Structure containing simulation results and parameter values
 14%
 15% Used Functions:
 16% - update_simulation_parameters: Function to update simulation parameters
 17% - f_sim: Function to run the simulation
 18%
 19% Variables:
 20% Loaded:
 21% - Data: Array of structures containing experimental data
 22% - sbtab: SBTAB structure containing default parameters and species
 23% information
 24%
 25% Initialized:
 26% - sim_par: Array of simulation parameters
 27% - ssa: Array of species start amounts
 28%
 29% Persistent:
 30% - sbtab: SBTAB structure containing default parameters and species
 31% information
 32% - Data: Array of structures containing experimental data
 33
 34% Save variables that need to be mantained over multiple function calls
 35persistent sbtab
 36persistent Data
 37
 38data_model = model_folders.model.data.data_model;
 39
 40% Import the data on the first run
 41if isempty(sbtab)
 42    load(data_model,'Data','sbtab')
 43end
 44
 45% Set the parameters that are going to be used for the simulation to the
 46% default ones as definded in the SBTAB
 47sim_par(:,1) = [sbtab.defpar{:,2}];
 48
 49% Check if the parametrer needs to be set to the value relevant for Profile
 50% Likelihood
 51if isfield(stg,"PLind") && isfield(stg,"PLval")
 52    parameters = [parameters(1:stg.PLind-1) stg.PLval parameters(stg.PLind:end)];
 53end
 54
 55% Update simulation parameters
 56sim_par = update_simulation_parameters(sim_par, parameters, stg,sbtab);
 57
 58%  Set the start amount for the species in the model to 0
 59ssa = zeros(size(sbtab.species,1),max(stg.exprun));
 60
 61% Initialize the results variable
 62result = [];
 63result.parameters = sim_par;
 64result.simd{stg.exprun(1)} = [];
 65
 66% Run simulations for each experiment
 67for n = stg.exprun
 68    
 69    % Try catch used because iterations errors can happen unexectedly and
 70    % we want to be able to continue simulations
 71try
 72    % Display progress message if appropriate
 73    if stg.simcsl
 74        disp("Running dataset number " + n + " of " + stg.exprun(end))
 75    end
 76
 77    % Check if this is not the first experiment, the start values are
 78    % equal to the previous experiment, and the previous simulation
 79    % was valid
 80    is_not_first_experiment = n ~= stg.exprun(1);
 81    
 82    start_values_equal = min([sbtab.datasets(n).start_amount{:,2}] ==...
 83        [sbtab.datasets(stg.exprun(...
 84        max(find(stg.exprun==n)-1,1))).start_amount{:,2}]);
 85    previous_simulation_valid = ...
 86        result.simd{stg.exprun(max(find(stg.exprun==n)-1,1))} ~= 0;
 87    
 88    if is_not_first_experiment && start_values_equal && previous_simulation_valid
 89        % Set the start amounts based on the previous experiment
 90        ssa(:,n) = ssa(:,stg.exprun(find(stg.exprun==n)-1));
 91        if stg.simdetail
 92            ssa(:,n+2*stg.expn) = ssa(:,stg.exprun(find(stg.exprun==n)-1));
 93        end
 94    else
 95        % Set start amounts for species with non-zero values
 96        for j = 1:size(sbtab.datasets(n).start_amount,1)
 97
 98            % Set the start amount of the species to the number defined in
 99            % the sbtab for each experiment
100            ssa(sbtab.datasets(n).start_amount{j,3},n+stg.expn) =...
101                sbtab.datasets(n).start_amount{j,2};
102        end
103
104        % Equilibrate the model
105            result = f_sim(n+stg.expn,stg,sim_par,ssa,result,model_folders);
106
107            % Update the start amounts based on equilibrium results
108        for j = 1:size(sbtab.species,1)
109
110            final_amount = result.simd{n+stg.expn}.Data(end,j);
111
112            if final_amount < 1.0e-15
113                ssa(j,n) = 0;
114                if stg.simdetail
115                    ssa(j,n+2*stg.expn) = 0;
116                end
117            else
118                ssa(j,n) = final_amount;
119                if stg.simdetail
120                    ssa(j,n+2*stg.expn) = final_amount;
121                end
122            end
123        end
124    end
125    % Run the main simulation
126        result = f_sim(n,stg,sim_par,ssa,result,model_folders);
127    % Run detailed simulation if required
128        if stg.simdetail
129            result = f_sim(n+2*stg.expn,stg,sim_par,ssa,result,model_folders);
130        end
131
132    % Check if the simulation output times match the SBTAB data times, if
133    % they don't it means that the simulator didn't had enough time to run
134    % the model (happens in some unfavorable configurations of parameters,
135    % controlled by stg.maxt)
136    simulation_times_match = size(Data(n).Experiment.t,1) == size(result.simd{n}.Data(:,end),1);
137
138    % Handle cases where the simulation did not run properly
139    if ~simulation_times_match
140        result.simd{n} = 0;
141    end
142
143catch
144result.simd{n} = 0;
145end
146
147end
148end
149
150function sim_par = update_simulation_parameters(sim_par, parameters, settings,sbtab)
151% Iterate over all the parameters of the model
152for n = 1:size(sim_par,1)
153
154    % Update tested parameters
155    if settings.partest(n) > 0
156        sim_par(n) = 10.^(parameters(settings.partest(n,1)));
157    end
158
159    % Update thermodynamic constrained parameters
160    if isfield(settings,'tci') && ~isempty(settings.tci) && ismember(n,settings.tci) && settings.partest(n) > 0
161        sim_par = update_thermo_constrained_multiplications(sim_par, parameters,settings, n,sbtab);
162        sim_par = update_thermo_constrained_divisions(sim_par, parameters, settings, n,sbtab);
163    end
164end
165end
166
167function sim_par = update_thermo_constrained_multiplications(sim_par, parameters, settings, n,sbtab)
168% Iterate over the parameters that need to be mutiplied for calculating the
169% parameter that depends on the thermodynamic constraints
170for m = 1:size(settings.tcm, 2)
171    % Check that the parameter that is going to be used to calculate the
172    % parameter dependent on thermodynamic constraintsis is not the default
173    if settings.partest(settings.tcm(n, m), 1) > 0
174        % Check if the parametrer needs to be set to the value relevant for
175        % Profile Likelihood
176        if isfield(settings, "PLind") && settings.partest(settings.tcm(n, m), 1) == settings.PLind
177            parameters(settings.partest(settings.tcm(n, m), 1)) = settings.PLval;
178        end
179        % Make the appropriate multiplications to get the thermodinamicly
180        % constrained parameter
181        sim_par(n) = sim_par(n) * (10 ^ (parameters(settings.partest(settings.tcm(n, m), 1))));
182    else
183        % Make the appropriate multiplications to get the thermodinamicly
184        % constrained parameter
185        sim_par(n) = sim_par(n) * (sbtab.defpar{settings.tcm(n, m), 2});
186    end
187end
188end
189
190function sim_par = update_thermo_constrained_divisions(sim_par, parameters, settings, n,sbtab)
191% Iterate over the parameters that need to be divided for calculating the
192% parameter that depends on the thermodynamic constraints
193for m = 1:size(settings.tcd, 2)
194    % Check that the parameter that is going to be used to calculate the
195    % parameter dependent on thermodynamic constraintsis is not the default
196    if settings.partest(settings.tcd(n, m), 1) > 0
197        % Check if the parametrer needs to be set to the value relevant for
198        % Profile Likelihood
199        if isfield(settings, "PLind") && settings.partest(settings.tcd(n, m), 1) == settings.PLind
200            parameters(settings.partest(settings.tcd(n, m), 1)) = settings.PLval;
201        end
202        % Make the appropriate divisions to get the thermodinamicly
203        % constrained parameter
204        sim_par(n) = sim_par(n) / (10 ^ (parameters(settings.partest(settings.tcd(n, m), 1))));
205    else
206        % Make the appropriate divisions to get the thermodinamicly
207        % constrained parameter
208        sim_par(n) = sim_par(n) / (sbtab.defpar{settings.tcd(n, m), 2});
209    end
210end
211end

The code defines a main function f_prep_sim and three additional helper functions update_thermo_constrained_multiplications, update_thermo_constrained_divisions, and f_sim. The main function f_prep_sim prepares the parameters for a simulation, setting default values and updating any parameters being tested. It also adjusts the parameters according to thermodynamic constraints.

The main function f_prep_sim takes the following inputs:

  • parameters: parameters for the simulation

  • :ref:`stg<stg>`: settings for the simulation

  • model_folders: folder paths for the models

And it outputs :

  • rst: results of the simulation

The function initializes several persistent variables, imports data on the first run, and sets the default parameters for the simulation.

The function checks if the parameters need to be updated for Profile Likelihood.

It iterates through all model parameters, updating tested parameters and thermodynamic constrained parameters accordingly.

The function initializes the start amount for the species in the model to 0 and sets up a loop for each experiment being run.

Within the loop, the function tries to simulate the model, performing several checks and updates. If an error occurs during the simulation, the function catches the error and sets the simulation output to 0, indicating the simulation did not work properly.

The helper functions update_thermo_constrained_multiplications and update_thermo_constrained_divisions update the parameters according to the thermodynamic constraints. They iterate through parameters that need to be multiplied or divided, respectively, and make the appropriate adjustments.

The helper function f_sim runs simulations using SimBiology models for a set of experiments. It takes the following inputs:

  • experiment_idx: indices of experiments to run

  • settings: simulation settings

  • simulation_parameters: parameter values for simulations

  • species_start_amount: start amounts for species in simulations

  • results: output variable to save simulation results

  • main_model_folders: paths for model files

It outputs:

  • results: simulation results

The function f_sim maintains the state of the loaded models between calls using persistent variables, loads the appropriate models, compiles the code for the simulation run, substitutes the start amounts of species and parameter values based on real-time results, and runs the simulation.

The simulation results are saved in the output variable, and the function can be called multiple times for different experiments. The function checks if the times of the simulation output and the simulation data from SBTAB match. If they do not match, it sets the simulation output to 0, indicating that the simulation did not work properly.

In summary, the main function f_prep_sim prepares the parameters for a simulation by setting them to the default values and then updating any parameters being tested. It adjusts the parameters according to any thermodynamic constraints and iterates through all the experiments to be run. The function then calls the helper function f_sim to run the simulation using SimBiology models for the set of experiments. The simulation results are saved in the output variable, and any errors encountered during the simulation are caught and handled appropriately.

f_sim

Code

  1function results = f_sim(experiment_idx,settings,simulation_parameters,...
  2    species_start_amount,results,main_model_folders)
  3% This function runs simulations using SimBiology models for a set of
  4% experiments. It loads the appropriate models and compiles the code for
  5% simulation run, then substitutes the start amounts of species and
  6% parameter values based on real-time results and runs the simulation. The
  7% results of the simulation are saved in the output variable. The function
  8% can be called multiple times for different experiments, and it maintains
  9% the state of the loaded models between calls using persistent variables.
 10%
 11% Inputs:
 12% - experiment_idx: Indices of experiments to run
 13% - settings: Simulation settings (e.g., sbioaccelerate, simdetail, expn,
 14% exprun)
 15% - simulation_parameters: Parameter values for simulations
 16% - species_start_amount: Start amounts for species in simulations
 17% - results: Output variable to save simulation results
 18% - main_model_folders: Paths for model files (e.g., model_exp_default,
 19% model_exp_eq, model_exp_detail)
 20%
 21% Outputs:
 22% - results: Simulation results (e.g., simd)
 23%
 24% Functions called:
 25% - sbioaccelerate: Compile model code for faster simulation run
 26% - sbiosimulate: Run simulation of SimBiology model with specified
 27% configuration
 28%
 29% Variables:
 30% Loaded:
 31% - model_exp: SimBiology model for each experiment
 32% - config_exp: SimBiology model configuration for each experiment
 33%
 34% Initialized:
 35% None
 36% 
 37% Persistent:
 38% - models: Cell array containing the SimBiology models for each experiment
 39% - configs: Cell array containing the configurations for each SimBiology
 40% model
 41
 42% Save variables that need to be mantained over multiple function calls
 43persistent models
 44persistent configs
 45
 46% If the function is called for the first time, load the appropriate model
 47% and compile the code for simulation run
 48if isempty(models)
 49
 50    % Turn off warning messages
 51    warning('off','all')
 52    warning('off', 'SimBiology:InvalidSpeciesInitAmtUnits')
 53    warning('off', 'SimBiology:SolodeSolverIntegrationError');
 54    warning('off', 'SimBiology:Solver:IntegrationTolNotMet');
 55    warning('off', 'SimBiology:Solver:InfOrNaN');
 56    warning('off', 'SimBiology:solver');
 57
 58    %Generate an empty array to be populated with the model suited for each
 59    %equilibration and experiment%
 60    models = cell(1,settings.expn*(2 + settings.simdetail));
 61    configs = cell(1,settings.expn*(2 + settings.simdetail));
 62
 63    % Set the file paths for the different models
 64    model_exp_default = main_model_folders.model.data.model_exp.default;
 65    model_exp_eq = main_model_folders.model.data.model_exp.equilibration;
 66    model_exp_detail = main_model_folders.model.data.model_exp.detail;
 67
 68    % Iterate over the experiments thar are being run
 69    for n = settings.exprun
 70
 71        % Load and compile SimBiology models for each experiment
 72
 73        % Load models for main simulation
 74        load(model_exp_default + n + ".mat",'model_exp','config_exp')
 75        models{n} = model_exp;
 76        configs{n} = config_exp;
 77
 78        % Load models for equilibrium
 79        load(model_exp_eq + n + ".mat",'model_exp','config_exp')
 80        models{n+settings.expn} = model_exp;
 81        configs{n+settings.expn} = config_exp;
 82
 83        % Load models for detailed simulation
 84        if settings.simdetail
 85            load(model_exp_detail + n + ".mat",'model_exp','config_exp')
 86            models{n+2*settings.expn} = model_exp;
 87            configs{n+2*settings.expn} = config_exp;
 88        end
 89
 90        % Compile the model code if the option is selected in settings
 91        if settings.sbioacc
 92            sbioaccelerate(models{n},configs{n});
 93            sbioaccelerate(models{n+settings.expn},configs{n+settings.expn});
 94            if settings.simdetail
 95                sbioaccelerate(models{n+2*settings.expn},configs{n+2*settings.expn});
 96            end
 97        end
 98    end
 99end
100
101% substitute the start amount of the species in the model with the correct
102% ones for  simulations
103set(models{experiment_idx}.species(1:size(species_start_amount(:,experiment_idx),1)),...
104    {'InitialAmount'},num2cell(species_start_amount(:,experiment_idx)));
105
106% Substitute the values of the parameters in the model for the correct one
107% for simultaions
108set(models{experiment_idx}.parameters(1:size(simulation_parameters,1)),...
109    {'Value'},num2cell(simulation_parameters));
110
111try
112    %simulate the model using matlab built in function
113    results.simd{experiment_idx} = sbiosimulate(models{experiment_idx},...
114        configs{experiment_idx});
115catch ME
116    % disp(ME.identifier)
117
118    % Set the simulation output to be 0, this is a non function
119    % value that the score function expects in simulations that did
120    % not worked properly
121    results.simd{experiment_idx} = 0;
122end
123
124end

Description

Simulates the model with the provided configurations. The first time it is run it loads a representation of the model and the simulation, and compiles this information to C code.

Input Arguments

  • exp_n - (double) Unique number to identify the model for each experiment or equilibrium reaction (it needs a new model object for each one)

  • stg - stg.expn, stg.name, stg.sbioacc

  • rt

    • rt.ssa - (double) steady state amounts

    • rt.par - (double) All parameters of the model, takes the default ones from SBtab and then replaces the ones being worked on.

  • rst - rst.simd

Output Arguments

Functions called - Sbioaccelerate, Sbiosimulate Loaded variables - Ready to run model, Ready to run model equilibration

f_score

Code

  1function rst = f_score(rst, stg, mmf)
  2% This function calculates the score for a set of simulated results by
  3% comparing them to experimental data. It computes the score for each
  4% dataset and experiment and then calculates the total score based on the
  5% selected scoring strategy. The score serves as a metric for comparing the
  6% accuracy of different simulations or models.
  7%
  8% Inputs:
  9% - rst: Structure containing the simulation results and scores.
 10% - stg: Structure containing the settings for the scoring strategy, such
 11% as the option to use log10 scaling, error score, and other options.
 12% - mmf: Structure containing the model directory information.
 13%
 14% Outputs:
 15% - rst: Updated structure containing the calculated scores for each
 16% dataset, experiment, and the total score.
 17%
 18% Used Functions:
 19% - calculate_score_per_experiment: Calculates the score for each
 20% experiment.
 21% - calculate_score_per_dataset: Calculates the score for each dataset in
 22% an experiment.
 23% - f_normalize: Normalizes the simulation results for a dataset.
 24%
 25% Variables:
 26% Loaded:
 27% - Data: Experimental data.
 28% - sbtab: sbtab structure containing dataset information.
 29%
 30% Persistent:
 31% - sbtab: sbtab structure containing dataset information (persistent).
 32% - Data: Experimental data (persistent).
 33
 34persistent sbtab
 35persistent Data
 36
 37data_model = mmf.model.data.data_model;
 38
 39% Import the data on the first run
 40if isempty(Data)
 41    load(data_model,'Data','sbtab')
 42end
 43
 44% Iterate over the number of experiments
 45for n = stg.exprun
 46    rst = calculate_score_per_experiment(rst, stg, n, mmf,sbtab, Data);
 47end
 48
 49% Calculate the total score
 50rst.st = sum(rst.se);
 51
 52% Calculate the log10 of total score if option selected
 53if stg.useLog == 3
 54    rst.st = log10(rst.st);
 55end
 56end
 57
 58function rst = calculate_score_per_experiment(rst, stg, n, mmf,sbtab, Data)
 59
 60% Iterate over the number of datasets per experiment
 61for j = 1:size(sbtab.datasets(n).output, 2)
 62    rst = calculate_score_per_dataset(rst, stg, n, j, mmf, Data);
 63end
 64
 65% Calculate score per experiment
 66rst.se(n, 1) = sum(rst.sd(:, n));
 67
 68% Calculate the log10 of experiment score if option selected
 69if stg.useLog == 2
 70    rst.se(n, 1) = log10(rst.se(n, 1));
 71end
 72end
 73
 74function rst = calculate_score_per_dataset(rst, stg, n, j, mmf, Data)
 75
 76% Calculate score per dataset if there are no errors
 77if rst.simd{n} ~= 0
 78    data = Data(n).Experiment.x(:, j);
 79    data_sd = Data(n).Experiment.x_SD(:, j);
 80
 81
 82    % data = data /(max(data)-min(data));
 83
 84
 85    number_points = size(Data(n).Experiment.x(:, j), 1);
 86    sim_results = f_normalize(rst, stg, n, j, mmf);
 87    rst.xfinal{n, 1}(j) = sim_results(end);
 88
 89    % Calculate score using formula that accounts for normalization
 90    % with the starting point of the result
 91    switch stg.useLog
 92        case {0, 2, 3}
 93            rst.sd(j, n) = sum(((data - sim_results) ./ (data_sd)).^2) / number_points;
 94        case 1
 95            rst.sd(j, n) = max(0, log10(sum(((data - sim_results) ./ (data_sd)).^2) / number_points));
 96        case 4
 97            rst.sd(j, n) = sum(((data - sim_results) ./ (data_sd * sqrt(number_points))).^2);
 98        otherwise
 99            error('Invalid value for stage.useLog: %d', stg.useLog);
100    end
101
102    % If there are errors output a very high score value (10^10)
103elseif rst.simd{n} == 0 || rst.sd(n, j) == inf
104    rst.sd(j, n) = stg.errorscore;
105rst.xfinal{n, 1}(j) = 0;
106end
107end

Description

The f_score function computes the score for a given set of simulated results by comparing them with the experimental data. The function calculates the score for each dataset and experiment, and then computes the total score based on the selected scoring strategy. The score serves as a metric for comparing the accuracy of different simulations or models.

Input Arguments

  • rst: Structure containing the simulation results and scores.

  • stg: Structure containing the settings for the scoring strategy, such as the option to use log10 scaling, error score, and other options.

  • mmf: Structure containing the model information, including the data model.

Output Arguments

  • rst.st: Updated structure containing the calculated scores for each dataset, experiment, and the total score.

Example

% Define the input structures and settings
stg.useLog = 1;
stg.errorscore = 1e10;
stg.exprun = 1:3;
mmf.model.data.data_model = matlab model file
rst.simd = matlab output from f_prep_sim

% Call the f_score function
rst = f_score(rst, stg, mmf);

This example demonstrates how to call the f_score function with the input structures and settings. The function calculates the scores for the given simulation results based on the scoring strategy defined in the stg structure.

f_normalize

Code

  1function [sim_results_norm,sim_results_detailed,sim_results] = ...
  2f_normalize(results, settings, exp_number, output_number, model_folders)
  3% This function processes and normalizes simulation results based on a
  4% specified normalization method. It accepts a set of inputs, including the
  5% simulation results, settings, experiment and output numbers, and a model
  6% metafile structure. The function returns normalized simulation results,
  7% along with detailed normalized simulation results if the 'simdetail'
  8% setting is enabled.
  9%
 10% Inputs:
 11% - rst: Structure containing the simulation results and scores
 12% - stg: Structure containing the settings for the simulation
 13% - exp_number: An integer representing the experiment number
 14% - output_number: An integer representing the output number
 15% - mmf: Structure containing the model directory information
 16%
 17% Outputs:
 18% - sim_results: A matrix containing the normalized simulation results
 19% - sim_results_detailed: A matrix containing the detailed normalized
 20% simulation results (if stg.simdetail is true)
 21%
 22% Used Functions:
 23% - extract_data: Helper function to extract data from the simulation
 24% results
 25%
 26% Variables
 27% Persistent:
 28% - sbtab: SBtab structure
 29% - Data: Loaded data from the model
 30% - sb: Structure containing experiment IDs
 31
 32persistent sbtab
 33persistent Data
 34persistent sb
 35
 36% Load Data and sbtab if empty
 37if isempty(Data)
 38    load(model_folders.model.data.data_model, 'Data', 'sbtab','sb')
 39end
 40
 41% Extract the data from the simulation results
 42sim_results = extract_data(results, exp_number, output_number, sbtab);
 43sim_results_detailed = [];
 44
 45% Check if detailed simulation results are requested
 46if settings.simdetail
 47    sim_results_detailed =...
 48        extract_data(results, exp_number + 2 * settings.expn, ...
 49        output_number, sbtab);
 50end
 51
 52% Get the normalization method
 53normalize = sbtab.datasets(exp_number).Normalize;
 54% exp_number
 55% normalize
 56
 57% Perform normalization if a method is specified
 58if ~isempty(normalize)
 59    output_ID = sbtab.datasets(exp_number).output_ID{output_number}{:};
 60    norm_factor = extract_data(results, exp_number, output_number, sbtab);
 61%     output_ID
 62% contains(normalize, 'Max')
 63% contains(normalize, output_ID)
 64
 65sim_results_norm = sim_results;
 66
 67    % Normalize by the maximum value
 68    if contains(normalize, 'Max') && contains(normalize, output_ID)
 69        max_norm = max(norm_factor);
 70        sim_results_norm = sim_results / max_norm;
 71        if settings.simdetail
 72            sim_results_detailed = sim_results_detailed / max_norm;
 73        end
 74    end
 75
 76    % normalize
 77    % contains(normalize, 'Norm')
 78    % output_ID
 79    % contains(normalize, output_ID)
 80    % Normalize to a value between 0 and 1
 81    if contains(normalize, 'Norm') && contains(normalize, output_ID)
 82        max_norm = max(norm_factor);
 83        min_norm = min(norm_factor);
 84        sim_results_norm = (sim_results-min_norm) / (max_norm-min_norm);
 85        if settings.simdetail
 86            sim_results_detailed = (sim_results_detailed-min_norm) / (max_norm-min_norm);
 87        end
 88    end
 89
 90
 91    % Normalize by the minimum value
 92    % if contains(normalize, 'Min') && contains(normalize, output_ID)
 93    % 
 94    %     min_norm = min(norm_factor);
 95    %     sim_results = sim_results / min_norm;
 96    %     min_norm
 97    %     if settings.simdetail
 98    %         sim_results_detailed = sim_results_detailed / min_norm;
 99    %     end
100    % end
101
102    % Normalize by time-dependent factors
103    if contains(normalize, 'Time') && contains(normalize, output_ID)
104        t_size = size(Data(exp_number).Experiment.t, 1);
105        for n = 1:t_size
106            exp_ID = getfield(sb, ['E' num2str(exp_number - 1) '.ID'], n);
107            if contains(normalize, exp_ID)
108                sim_results_norm = sim_results / norm_factor(n);
109                if settings.simdetail
110                    sim_results_detailed = ...
111                    sim_results_detailed / norm_factor(n);
112                end
113            end
114        end
115    end
116end
117end
118
119% Helper function to extract data
120function data = extract_data(results, exp_number, output_number, sbtab)
121% Helper function to extract data from the simulation results
122% Input arguments:
123% rst  - Structure containing the simulation results and scores.
124% stg  - Structure containing the settings for the simulation.
125% output_number - An integer representing the output number.
126% sbtab - SBtab structure
127% Output argument:
128% data - extracted data from the simulation results
129    data = results.simd{1, exp_number}.Data(:, end - ...
130        size(sbtab.datasets(exp_number).output, 2) + output_number);
131end

Description

The f_normalize function processes and normalizes simulation results based on a specified normalization method. It accepts a set of inputs, including the simulation results, settings, experiment and output numbers, and a model metafile structure. The function returns normalized simulation results, along with detailed normalized simulation results if the ‘simdetail’ setting is enabled.

Input Arguments

  • rst: A structure containing the simulation results.

  • stg: A structure containing the settings for the simulation.

  • exp_number: An integer representing the experiment number.

  • output_number: An integer representing the output number.

  • mmf: A structure containing the model metafile information.

Output Arguments

  • sim_results: A matrix containing the normalized simulation results.

  • sim_results_detailed: A matrix containing the detailed normalized simulation results (if stg.simdetail is true).