Setup and Import

f_load_settings

Code

  1function [stg,rst,sb] = f_user_input(mmf,analysis_options)
  2
  3persistent last_SBtab_date
  4persistent last_model_folder
  5persistent last_settings_file_text
  6persistent last_settings_file_date
  7persistent last_analysis_text
  8
  9Matlab_main_folder = mmf.main;
 10
 11rst = [];
 12sb = [];
 13functions_cleared = false;
 14
 15% Get the folder of the model
 16model_folder_general = Matlab_main_folder + "Model/";
 17last_choice = last_model_folder;
 18prompt = "What model folder should be used?\n";
 19[model_folder,last_model_folder] =...
 20    choose_options(model_folder_general,prompt,last_choice);
 21
 22model_name_specific = string(model_folder);
 23folder_model_specific = model_folder_general + "/" + model_name_specific;
 24
 25prompt = "\nWhat analysis should be performed?\n";
 26last_choice = last_analysis_text;
 27[analysis_text,last_analysis_text] =...
 28    parse_choices(prompt,analysis_options,last_choice);
 29
 30% analysis_n = find(contains(analysis_options,analysis_text));
 31    
 32% Check if an analysis was chosen
 33if any(contains(analysis_options([1:3,6]),...
 34        analysis_text))
 35    
 36    %Get the Setting file to be used
 37    settings_folder = folder_model_specific + "/Matlab/Settings";
 38    last_choice = last_settings_file_text;
 39    prompt = "\nWhat file should be used as settings?\n";
 40    [settings_file_text,last_settings_file_text] =...
 41        choose_options(settings_folder,prompt,last_choice);
 42    
 43    settings_file = strrep(settings_file_text,".m","");
 44    
 45    % Add the default settings to the struct
 46    stg_add_default = eval("default_settings()");
 47    
 48    f = fieldnames(stg_add_default);
 49    for i = 1:length(f)
 50        stg.(f{i}) = stg_add_default.(f{i});
 51    end
 52    
 53    % Add chosen settings to the struct overwriting defaults when
 54    % appropriate
 55    [stg_add] = eval(settings_file + "()");
 56    
 57    f = fieldnames(stg_add);
 58    for i = 1:length(f)
 59        stg.(f{i}) = stg_add.(f{i});
 60    end
 61    
 62    % Check if the date of the settings file changed, if so clear functions
 63    listing = dir(settings_folder);
 64    for n = 1:size(listing,1)
 65        if matches(settings_file_text,listing(n).name,"IgnoreCase",true)
 66            settings_file_date = listing(n).date;
 67        end
 68    end
 69    
 70    [last_settings_file_date,functions_cleared] =...
 71        compare_last(settings_file_date,last_settings_file_date,...
 72        functions_cleared);
 73    
 74    % Check if the name of the settings file changed, if so clear functions
 75    [last_settings_file_text,functions_cleared] =...
 76        compare_last(settings_file_text,last_settings_file_text,...
 77        functions_cleared);
 78    
 79    % Check if the date of the SBtab changed, if so clear functions
 80    listing = dir(folder_model_specific);
 81    
 82    for n = 1:size(listing,1)
 83        if matches(stg.sbtab_excel_name,listing(n).name,"IgnoreCase",true)
 84            sbtab_date = listing(n).date;
 85        end
 86    end
 87    [last_SBtab_date,~] =...
 88        compare_last(sbtab_date,last_SBtab_date,functions_cleared);
 89    
 90    % Store the name of the chosen analysis in the settings struct
 91    stg.analysis = analysis_text;
 92
 93    if contains(analysis_options(6),analysis_text)
 94        stg.import = true;
 95        stg.save_results = false;
 96        stg.plot = false;
 97    end
 98elseif any(contains(analysis_options(4:5),analysis_text))
 99    
100    % Get the folder of the Analysis that should be reproduced
101    folder_results = folder_model_specific + "/Matlab/Results";
102    
103    last_choice = [];
104    prompt = "\nWhat analysis should be reproduced?\n";
105
106    [r_analysis_text,~] =...
107        choose_options(folder_results,prompt,last_choice);
108    
109    folder_results_specific = folder_results + "/" + ...
110        r_analysis_text;
111    
112    last_choice = [];
113    prompt = "\nWhen was this analysis run originaly?\n";
114  
115    [r_analysis_date_text,~] =...
116        choose_options(folder_results_specific,prompt,last_choice);
117    
118    folder_results_specific_date = folder_results_specific + "/" + ...
119        r_analysis_date_text;
120    
121    % Load the settings file and the SBtab struct
122    load(folder_results_specific_date + "/Analysis.mat","stg","sb")
123    
124    % Set inport to false since we don't want to overwrite anything
125    stg.import = false;
126    
127    % If the reproduction of an analysis is chosen clear the functions
128    % because the settings most likely changed
129    if contains(analysis_options(4),analysis_text)
130        f_functions_to_clear()
131    end
132    
133    % I the reproduction of the plots of an analyis is chosen make sure
134    % we tell the code to produce plots and also load the results that were
135    % previously obtained
136    if contains(analysis_options(5),analysis_text)
137        stg.plot = true;
138        load(folder_results_specific_date + "/Analysis.mat","rst")
139    end
140end
141
142% Set the chosen model folder in the settings struct
143stg.folder_model = model_name_specific;
144end
145
146function [choice,last_choice] = choose_options(folder,prompt,last_choice)
147
148listing = dir(folder);
149
150for n = size(listing,1):-1:1
151    if any(matches(listing(n).name,[".","..","Place models here.txt"]))
152        listing(n)= [];
153    end
154end
155
156for n = 1:size(listing,1)
157    options(n) = string(listing(n).name);
158end
159
160[choice,last_choice] = parse_choices(prompt,options,last_choice);
161end
162
163function [choice,last_choice] = parse_choices(prompt,options,last_choice)
164
165for n = 1:size(options,2)
166    prompt = prompt + "\n" + n + ": " + options(n);
167end
168
169if ~isempty(last_choice)
170    if any(contains(options,last_choice))
171        prompt = prompt + "\n\nPress enter to use " + last_choice;
172    else
173        last_choice = [];
174    end
175end
176
177prompt = prompt + "\n";
178
179i = input(prompt);
180
181if isempty(i)
182    choice = [];
183elseif i > 0 && i < size(options,2)+1
184    choice = options(i);
185    disp("The option chosen was: " + choice)
186else
187    prompt = "Please choose from the provided options";
188    [choice,last_choice] = parse_choices(prompt,options,last_choice);
189end
190
191if isempty(choice)
192    if ~isempty(last_choice)
193        choice = last_choice;
194        disp("The option chosen was: " + last_choice)
195    else
196        prompt = "Please choose from the provided options";
197        [choice,last_choice] = parse_choices(prompt,options,last_choice);
198    end
199else
200    last_choice = choice;
201end
202end
203
204function [previous,f_cleared] = compare_last(current,previous,f_cleared)
205
206if ~isempty(previous)
207    if ~contains(current,previous)
208        if f_cleared == false
209            disp("Settings file changed, clearing functions")
210            f_functions_to_clear()
211            f_cleared = true;
212        end
213    end
214end
215previous = current;
216end

It prompts the user to choose the model to run, the settings file to use, and the Analysis to perform.

  • Outputs - stg, rst, sb, Analysis_n

f_import

Code

 1function [stg,sb] = f_import(stg,mmf)
 2
 3Model_folder = mmf.model.main;
 4
 5disp("Generating model files and folder from SBtab")
 6
 7% Create needed folders
 8[~,~] = mkdir(mmf.model.data.main);
 9[~,~] = mkdir(mmf.model.input_functions.main);
10[~,~] = mkdir(mmf.model.tsv.model_name);
11[~,~] = mkdir(mmf.model.data.model_exp.main);
12
13% Creates a .mat and a tsvs from the SBtab file
14f_excel_sbtab_importer(mmf);
15
16addpath(genpath(Model_folder));
17
18% Creates a struct based on the SBtab that is used elswhere in the code and
19% also adds the number of experiments and outputs to the settings struct
20[stg,sb] = f_generate_sbtab_struct(stg,mmf);
21
22%Create the model and input output structure from sbtab.mat
23
24% Saves the model in .mat, .sbproj and .xml format, while also creating a
25% file whith the data to run the model in all different experimental
26% settings defined in the SBtab
27f_sbtab_to_model(stg,sb,mmf)
28
29% Creates code that loads the inputs of each experiment into a .mat file,
30% and creates the code to read this inputs at runtime when the experiments
31% are being simulated, all this generated code is stored on the Input
32% functions folder
33f_setup_input(stg,mmf)
34
35%Creates three .mat files for each experiment, with all the added rules,
36%species and parameters needed depending on the inputs and outputs
37%specified on the SBtab, one for the equilibrium simulation run, one for
38%the deffault run, and one for a more detailed run.
39f_build_model_exp(stg,sb,mmf)
40disp("Model files and folders generated successfully")
41end

Creates the necessary folders inside the model folder. Calls subfunctions that convert the SBtab from an Excel into MATLAB® files useful for the workflow, TSVs and a SBML.

f_excel_sbtab_importer

Code

 1function f_excel_sbtab_importer(mmf)
 2
 3Source_sbtab = mmf.model.sbtab;
 4Matlab_sbtab = mmf.model.data.sbtab;
 5
 6% Get the total number of sheets in the SBTAB
 7sheets = sheetnames(Source_sbtab);
 8
 9% Try to run the import the sheets in multicore, depending on the version
10% of excel this migth not work
11try
12    parfor i = 1:size(sheets,1)
13        sbtab_excel{i} = impexp (i,mmf);
14    end
15catch
16    for i = 1:size(sheets,1)
17        sbtab_excel{i} = impexp (i,mmf);
18    end
19end
20
21% Save the SBTAB tables in .mat format
22save(Matlab_sbtab,'sbtab_excel');
23disp("SBtab with " + size(sheets,1) + " sheets parsed successfully")
24end
25
26function sbtab_excel = impexp (i,mmf)
27
28Source_sbtab = mmf.model.sbtab;
29tsv_name_folder = mmf.model.tsv.model_name;
30
31% Import the SBTAB to a cell with a sheet per cell
32sbtab_excel = readcell(Source_sbtab,'sheet',i);
33
34% Replace "ismissing" values with empty spaces
35mask = cellfun(@ismissing, sbtab_excel,'UniformOutput',false);
36mask = cellfun(@min, mask);
37mask = logical(mask);
38sbtab_excel(mask) = {[]};
39
40% Get name for tsv that is going to be exported
41field = regexp(sbtab_excel{1,2},"TableName='[^']*'",'match');
42field = string(replace(field,["TableName='","'"," "],["","","_"]));
43
44%Export the tsv
45cell_write_tsv(tsv_name_folder + field + ".tsv",sbtab_excel)
46end
47
48function cell_write_tsv(filename,origCell)
49
50% save a new version of the cell for reference
51modCell = origCell;
52% assume some cells are numeric, in which case set to char
53iNum = cellfun(@isnumeric,origCell);
54
55% Replace numeric sells with cell strings
56for n = 1:size(iNum,1)
57    for m = 1:size(iNum,2)
58        modCell(n,m) = cellstr(num2str(origCell{n,m}));
59    end
60end
61
62%Save the file that only as strings in each cell
63modCell = transpose(modCell);
64
65[rNum,cNum] = size(origCell);
66frmt = repmat([repmat('%s\t',1,cNum-1),'%s\n'],1,rNum);
67fid = fopen(filename,'wt');
68fprintf(fid,frmt,modCell{:});
69fclose(fid);
70end

Loads the information in the SBtab and creates a . mat file that contains the sbtab and TSVs corresponding to all the SBtab tabs.

f_generate_sbtab_struct

Code

 1function [stg,sb] = f_generate_sbtab_struct(stg,mmf)
 2
 3Matlab_sbtab = mmf.model.data.sbtab;
 4
 5if isfile(Matlab_sbtab)
 6    
 7    load(Matlab_sbtab,'sbtab_excel');
 8    
 9    sb = f_get_sbtab_fields(sbtab_excel);
10    
11    stg.expn = size(sb.Experiments.ID,1);
12    stg.outn = size(sb.Output.ID,1);
13end
14end
15
16function sb = f_get_sbtab_fields(sbtab_excel)
17for n = 1:size(sbtab_excel,2)
18    
19    if ~isempty(sbtab_excel{1,n}{1,2})
20        
21        field = regexp(sbtab_excel{1,n}{1,2},"TableName='[^']*'",'match');
22        field = string(replace(field,["TableName='","'"," "],["","","_"]));
23        
24        for k = 1:size(sbtab_excel{1,n},2)
25            
26            if ~isempty(sbtab_excel{1,n}{2,k})
27                subfield = sbtab_excel{1,n}{2,k};
28                subfield =...
29                    string(replace(subfield,["!",">",":"," "],["","","_","_"]));
30                
31                sb.(field).(subfield)(:,1) = sbtab_excel{1,n}(3:end,k)';
32                
33                sb.(field).(subfield) = sb.(field).(subfield)...
34                    (~cellfun('isempty', sb.(field).(subfield)));
35            end
36        end
37    end
38end
39end

Loads the SBtab saved in the .mat file and creates a MATLAB® struct that can be more easily parsed.

f_sbtab_to_model

Code

  1function f_sbtab_to_model(stg,sb,mmf)
  2% Saves the model in .mat, .sbproj and .xml format, while also creating a
  3% file whith the data to run the model in all different experimental
  4% settings defined in the sbtab
  5
  6modelobj = sbiomodel(stg.name);
  7compObj = [];
  8
  9sbtab.species = cat(2,sb.Compound.Name,sb.Compound.InitialValue,...
 10    sb.Compound.IsConstant,sb.Compound.Unit,sb.Compound.Location);
 11
 12sbtab.defpar = cat(2,sb.Parameter.Comment,sb.Parameter.Value_linspace,...
 13    sb.Parameter.Unit);
 14
 15for n = 1:size(sb.Compartment.ID,2)
 16    compObj{n} = addcompartment(modelobj, sb.Compartment.Name{n});
 17    set(compObj{n}, 'CapacityUnits', sb.Compartment.Unit{n});
 18    set(compObj{n}, 'Value', sb.Compartment.Size{n});
 19end
 20
 21for n = 1:size(sbtab.species,1)
 22    
 23    for m = 1:size(compObj,2)
 24        if string(compObj{m}.Name) == string(sb.Compound.Location{n})
 25            compartment_number_match = m;
 26        end
 27    end
 28    
 29    addspecies (compObj{compartment_number_match}, sb.Compound.Name{n},sb.Compound.InitialValue{n}...
 30        ,'InitialAmountUnits',sb.Compound.Unit{n});
 31end
 32
 33for n = 1:size(sbtab.defpar,1)
 34    addparameter(modelobj,sb.Parameter.Name{n},...
 35        sb.Parameter.Value_linspace{n},'ValueUnits',sb.Parameter.Unit{n},'Notes',sb.Parameter.Comment{n});
 36end
 37
 38for n = 1:size(sb.Reaction.ID,1)
 39    
 40    if ischar(sb.Reaction.IsReversible{n})
 41        if contains(convertCharsToStrings(sb.Reaction.IsReversible{n}),"true")
 42            reaction_name = strrep(sb.Reaction.ReactionFormula{n},'<=>',' <-> ');
 43        else
 44            reaction_name = strrep(sb.Reaction.ReactionFormula{n},'<=>',' -> ');
 45        end
 46    else
 47        if sb.Reaction.IsReversible{n}
 48            reaction_name = strrep(sb.Reaction.ReactionFormula{n},'<=>',' <-> ');
 49        else
 50            reaction_name = strrep(sb.Reaction.ReactionFormula{n},'<=>',' -> ');
 51        end
 52    end
 53    
 54    reaction_name_compartment = reaction_name;
 55    
 56    for m = 1:size(sb.Compound.Name,1)
 57        reaction_name_compartment =...
 58            insertBefore(string(reaction_name_compartment)," " +...
 59            string(sb.Compound.Name{m})," " + string(sb.Reaction.Location{n}));
 60    end
 61    
 62    while contains(reaction_name_compartment,...
 63            string(sb.Reaction.Location{n})+" "+string(sb.Reaction.Location{n}))
 64        reaction_name_compartment =...
 65            strrep(reaction_name_compartment,string(sb.Reaction.Location{n})+...
 66            " "+string(sb.Reaction.Location{n})," "+sb.Reaction.Location{n});
 67    end
 68    
 69    while contains(reaction_name_compartment,"  ")
 70        reaction_name_compartment = strrep(reaction_name_compartment,"  "," ");
 71    end
 72    
 73    reaction_name_compartment = strrep(reaction_name_compartment,...
 74        sb.Reaction.Location{n} + " ",sb.Reaction.Location{n}+".");
 75    reaction_name_compartment = string(sb.Reaction.Location{n})+"."+reaction_name_compartment;
 76    
 77    reactionObj = addreaction(modelobj,reaction_name_compartment);
 78    set(reactionObj,'ReactionRate',sb.Reaction.KineticLaw{n});
 79end
 80
 81for n = 1:size(sb.Compound.ID,1)
 82    if ischar(sb.Compound.Assignment{n})
 83        if contains(convertCharsToStrings(sb.Compound.Assignment{n}),["true","True"])
 84            modelobj.species(n).BoundaryCondition = 1;
 85        end
 86    else
 87        if sb.Compound.Assignement{n} == 1
 88            modelobj.species(n).BoundaryCondition = 1;
 89        end
 90    end
 91    if ischar(sb.Compound.Interpolation{n})
 92        if contains(convertCharsToStrings(sb.Compound.Interpolation{n}),["true","True"])
 93            modelobj.species(n).BoundaryCondition = 1;
 94        end
 95    else
 96        if sb.Compound.Interpolation{n} == 1
 97            modelobj.species(n).BoundaryCondition = 1;
 98        end
 99    end
100    if ischar(sb.Compound.IsConstant{n})
101        if contains(convertCharsToStrings(sb.Compound.IsConstant{n}),["true","True"])
102            modelobj.species(n).BoundaryCondition = 1;
103        end
104    else
105        if sb.Compound.IsConstant{n} == 1
106            modelobj.species(n).BoundaryCondition = 1;
107        end
108    end
109end
110
111sbtab.sim_time = [sb.Experiments.Sim_Time{:}];
112
113species_INP_matcher ={};
114for n = 1:size(sb.Compound.ID,1)
115    if isfield(sb.Experiments,"S"+(n-1))
116        species_INP_matcher{size(species_INP_matcher,1)+1,1} = n;
117    end
118end
119
120for n = 1:size(sb.Experiments.ID,1)
121    startamount = cell(1,size(species_INP_matcher,1));
122    nstartamount = 0;
123    nInputTime = 0;
124    nInput = 0;
125    nOutput = 0;
126
127    for m = 1:size(sb.Compound.ID,1)
128        if isfield(sb.Experiments,"S"+(m-1))
129            nstartamount = nstartamount+1;
130            startamount{nstartamount} = eval("sb.Experiments.S"+(m-1)+"(n)");
131            startAmountName(nstartamount) = sb.Compound.Name(m);
132        end
133    end
134    
135    if isfield(sb.Experiments,"Normalize")
136        sbtab.datasets(n).Normalize = sb.Experiments.Normalize{n};
137    else
138        sbtab.datasets(n).Normalize = [];
139    end
140    
141    if isfield(eval(("sb.E")+(n-1)),"Time")
142        Data(n).Experiment.t = transpose(eval("[sb.E"+(n-1)+".Time{:}]"));
143    end
144    
145    for m = 1:size(sb.Compound.ID,1)
146        if isfield(eval(("sb.E")+(n-1)+"I"),"Input_Time_S"+(m-1))
147            nInputTime = nInputTime + 1;
148            sbtab.datasets(n).input_time{1,nInputTime} = ...
149                eval(("[sb.E") + (n-1) + "I.Input_Time_S" + (m-1) + "{:}]");
150        end
151        if isfield(eval(("sb.E")+(n-1)+"I"),"S"+(m-1))
152            nInput = nInput + 1;
153            sbtab.datasets(n).input_value{1,nInput} = ...
154                eval(("[sb.E") + (n-1) + "I.S" + (m-1) + "{:}]");
155            sbtab.datasets(n).input{nInput} = char("S" + (m-1));
156        end
157    end
158    
159    for m = 1:size(sb.Output.ID,1)
160        if isfield(eval(("sb.E")+(n-1)),"Y"+(m-1))
161            nOutput = nOutput+1;
162            Data(n).Experiment.x(:,nOutput) = eval(("[sb.E") +...
163                (n-1) + ".Y" + (m-1) + "{:}]");
164            Data(n).Experiment.x_SD(:,nOutput) = eval(("[sb.E") +...
165                (n-1) + ".SD_Y" + (m-1) + "{:}]");
166            sbtab.datasets(n).output{nOutput} = sb.Output.Name(m);
167            sbtab.datasets(n).output_value{nOutput} = ...
168                {convertStringsToChars(...
169                strrep(string(sb.Output.Location{m}) + "." +...
170                string(sb.Output.Name{m}) + " = " +...
171                string(sb.Output.Formula{m}),'eps','0.0001'))};
172            sbtab.datasets(n).output_name{nOutput} = ...
173                sb.Output.Name(m);
174            sbtab.datasets(n).output_ID{nOutput} = ...
175                sb.Output.ID(m);
176            sbtab.datasets(n).output_location{nOutput} = ...
177                sb.Output.Location(m);
178        end
179    end
180    sbtab.datasets(n).stg.outnumber = nOutput;
181    sbtab.datasets(n).start_amount = cat(2,startAmountName(:)...
182        ,transpose([startamount{:}]),species_INP_matcher);
183end
184
185if isfield(sb,"Expression")
186    for m = 1:size(sb.Expression.ID,1)
187        if isfield(sb.Expression,'Formula')
188            if isa(sb.Expression.Formula{m},'double')
189                addspecies (modelobj, char(sb.Expression.Name(m)),...
190                    str2double(string(sb.Expression.Formula{m})),...
191                    'InitialAmountUnits',sb.Expression.Unit{m});
192            else
193                try
194                    addspecies (modelobj, char(sb.Expression.Name(m)),0,...
195                        'InitialAmountUnits',sb.Expression.Unit{m});
196                catch
197                end
198                addrule(modelobj, char({convertStringsToChars(...
199                    string(sb.Expression.Location{m}) + "." +...
200                    string(sb.Expression.Name{m}) + " = " +...
201                    string(sb.Expression.Formula{m}))}),...
202                    'repeatedAssignment');
203            end
204        else
205            addparameter(modelobj,char(sb.Expression.Name(m)),...
206                str2double(string(sb.Expression.DefaultValue{m})),...
207                'ValueUnits',sb.Expression.Unit{m});
208        end
209    end
210end
211
212if isfield(sb,"Input")
213    for m = 1:size(sb.Input.ID,1)
214        if isfield(sb.Input,'Formula')
215            if isa(sb.Input.Formula{m},'double')
216                addspecies (modelobj, char(sb.Input.Name(m)),...
217                    str2double(string(sb.Input.DefaultValue{m})),...
218                    'InitialAmountUnits',sb.Input.Unit{m});
219            else
220                try
221                    addspecies (modelobj, char(sb.Input.Name(m)),0,...
222                        'InitialAmountUnits',sb.Input.Unit{m});
223                catch
224                end
225                addrule(modelobj, char({convertStringsToChars(...
226                    string(sb.Input.Location{m}) + "." +...
227                    string(sb.Input.Name{m}) + " = " +...
228                    string(sb.Input.DefaultValue{m}))}),...
229                    'repeatedAssignment');
230            end
231        else
232            addparameter(modelobj,char(sb.Input.Name(m)),...
233                str2double(string(sb.Input.DefaultValue{m})),...
234                'ValueUnits',sb.Input.Unit{m});
235        end
236    end
237end
238
239if isfield(sb,"Constant")
240    for m = 1:size(sb.Constant.ID,1)
241        addparameter(modelobj,char(sb.Constant.Name(m)),...
242            str2double(string(sb.Constant.Value{m})),...
243            'ValueUnits',sb.Constant.Unit{m});
244    end
245end
246
247sbproj_model = mmf.model.data.sbproj_model;
248matlab_model = mmf.model.data.mat_model;
249data_model = mmf.model.data.data_model; 
250xml_model = mmf.model.data.xml_model; 
251
252sbiosaveproject(sbproj_model,'modelobj')
253
254save(matlab_model,'modelobj')
255
256save(data_model,'Data','sbtab','sb')
257
258sbmlexport(modelobj,xml_model)
259
260end

Reads information from the SBtab and saves the model in MATLAB (.mat, .sbproj) and SBML(.xml) format, while also creating a file whith the data to run the model in all different experimental settings defined in the SBtab.

f_setup_input

Code

  1function f_setup_input(stg,mmf)
  2% Creates code that loads the inputs of each experiment into a .mat file,
  3% and creates the code to read this inputs at runtime when the experiments
  4% are being simulated, all this generated code is stored on the
  5% Input_functions folder
  6
  7matlab_model = mmf.model.data.mat_model;
  8data_model = mmf.model.data.data_model;
  9inp_model_data = mmf.model.data.input_model_data;
 10Model_folder = mmf.model.main;
 11model_input = mmf.model.input_functions.input;
 12
 13%Find correct path for loading depending on the platform
 14load(data_model,'sbtab')
 15
 16load(matlab_model,'modelobj');
 17
 18for Exp_n = 1:size(sbtab.datasets,2)
 19    
 20    for index = 1:size(sbtab.datasets(Exp_n).input,2)
 21        if size(sbtab.datasets(Exp_n).input_value{index},2) > 100
 22            
 23            input_name = strrep(modelobj.species(1+str2double(strrep(...
 24                sbtab.datasets(Exp_n).input(index),'S',''))).name,".","");
 25            inpX = input_name + "X";
 26            inpT = input_name + "T";
 27            inph1 = input_name + "h1";
 28            inph2 = input_name + "h2";
 29            
 30            fullFileName = sprintf('%s.m',...
 31                model_input + Exp_n + "_" + input_name  );
 32            
 33            fileID = fopen(fullFileName, 'wt');
 34
 35            inp_str = template1();
 36            inp_str = replace(inp_str,...
 37                ["SBtab_name","Exp_n","input_name",...
 38                "inpX", "inpT", "inph1", "inph2", "inp_model_data",...
 39                "sbtab.sim_time(Exp_n)"],[stg.name,Exp_n,...
 40                input_name, inpX, inpT, inph1,...
 41                inph2, inp_model_data,...
 42                sbtab.sim_time(Exp_n)]);
 43
 44            fprintf(fileID,inp_str);
 45            fclose(fileID);
 46        end
 47    end
 48end
 49
 50fullFileName = sprintf('%s.m',model_input + "_creator"  );
 51
 52fileID = fopen(fullFileName, 'wt');
 53fprintf(fileID, "function " + stg.name + "_input_creator(~)\n");
 54helper = 0;
 55for Exp_n = 1:size(sbtab.datasets,2)
 56    for index =1:size(sbtab.datasets(Exp_n).input,2)
 57        if size(sbtab.datasets(Exp_n).input_value{index},2) > 100
 58            input_name = strrep(modelobj.species(1+str2double(strrep(...
 59                sbtab.datasets(Exp_n).input(index),'S',''))).name,".","");
 60            if helper == 0
 61                helper = 1;
 62                helper2 = Exp_n;
 63            end
 64            if index == 1 && Exp_n == helper2
 65                fprintf(fileID,"load('" + data_model + "','sbtab');\n");
 66                inp_creator_str = template2();
 67                inp_creator_str = replace(inp_creator_str,...
 68                    ["Exp_n", "input_name", "index", "inp_model_data"],...
 69                    [Exp_n, input_name, index, inp_model_data]);
 70                %                 fprintf(fileID,inp_creator_str);
 71            else
 72                inp_creator_str = template3();
 73                inp_creator_str = replace(inp_creator_str,...
 74                    ["Exp_n", "input_name", "index", "inp_model_data"],...
 75                    [Exp_n, input_name, index, inp_model_data]);
 76            end
 77            fprintf(fileID,inp_creator_str);
 78        end
 79    end
 80end
 81fprintf(fileID, "end\n");
 82fclose(fileID);
 83
 84addpath(genpath(Model_folder));
 85eval(stg.name + "_input_creator()");
 86end
 87
 88function inp_str = template1()
 89inp_str =...
 90    "function thisAmp = SBtab_name_inputExp_n_input_name(times)\n"+...
 91    "persistent inpX\n"+...
 92    "persistent inpT\n"+...
 93    "persistent inph1\n"+...
 94    "persistent inph2\n"+...
 95    "if isempty(inpX)\n"+...
 96        "Data = coder.load('inp_model_data','expExp_n_input_name');\n"+...
 97        "inpX = Data.expExp_n_input_name(:,2);\n"+...
 98        "inpT = Data.expExp_n_input_name(:,1);\n"+...
 99        "inph1 = 1;\n"+...
100    "end\n"+...
101    "thisAmp = inpX(end);\n"+...
102    "if times ~= sbtab.sim_time(Exp_n)\n"+...
103        "if times == 0\n"+...
104            "inph1 = 1;\n"+...
105            "thisAmp = inpX(1);\n"+...
106            "else\n"+...
107            "while times > inpT(inph1)\n"+...
108            "inph1 = inph1 + 1;\n"+...
109        "end\n"+...
110        "while times < inpT(inph1-1)\n"+...
111            "inph1  = inph1-1;\n"+...
112            "end\n"+...
113            "inph2 = (inpT(inph1)-times)*1/(inpT(inph1)-inpT(inph1-1));\n"+...
114            "thisAmp = (inpX(inph1-1)*inph2 + inpX(inph1)*(1-inph2));\n"+...
115        "end\n"+...
116    "end\n"+...
117    "end";
118end
119
120
121function inp_creator_str = template2()
122inp_creator_str = ...
123    "expExp_n_input_name(:,1) = sbtab.datasets(Exp_n).input_time{index};\n"+...
124    "expExp_n_input_name(:,2) = sbtab.datasets(Exp_n).input_value{index};\n"+...
125    "save('inp_model_data','expExp_n_input_name');\n";
126end
127function inp_creator_str = template3()
128inp_creator_str = ...
129    "expExp_n_input_name(:,1) = sbtab.datasets(Exp_n).input_time{index};\n"+...
130    "expExp_n_input_name(:,2) = sbtab.datasets(Exp_n).input_value{index};\n"+...
131    "save('inp_model_data','expExp_n_input_name','-append');\n";
132end

Creates code that loads the inputs of each experiment into a .mat file and the code to read these inputs at runtime when the experiments are being simulated. All this generated code is stored on the “Model/«model folder name»/Formulas” folder.

f_build_model_exp

Code

  1function f_build_model_exp(stg,sb,mmf)
  2%Creates two .mat files for each experiment, with all the added rules,
  3%species and parameters needed depending on the inputs and outputs
  4%specified on the sbtab, one for the equilibrium simulation run and one for
  5%the proper run
  6
  7data_model = mmf.model.data.data_model;
  8mat_model = mmf.model.data.mat_model;
  9model_exp_eq = mmf.model.data.model_exp.equilibration;
 10model_exp_default = mmf.model.data.model_exp.default;
 11model_exp_detail = mmf.model.data.model_exp.detail;
 12
 13%Find correct path for loading depending on the platform
 14load(data_model,'Data','sbtab')
 15load(mat_model,'modelobj');
 16
 17model_run = cell(size(sb.Experiments.ID,1),1);
 18configsetObj = cell(size(sb.Experiments.ID,1),1);
 19
 20for number_exp = 1:size(sb.Experiments.ID,1)
 21    
 22    output_value = sbtab.datasets(number_exp).output_value;
 23    output = sbtab.datasets(number_exp).output;
 24    input_time = sbtab.datasets(number_exp).input_time;
 25    input_value = sbtab.datasets(number_exp).input_value;
 26    input_species = sbtab.datasets(number_exp).input;
 27    
 28    model_run{number_exp} = copyobj(modelobj);
 29    configsetObj{number_exp} = getconfigset(model_run{number_exp});
 30    
 31    set(configsetObj{number_exp}, 'MaximumWallClock', stg.maxt);
 32    set(configsetObj{number_exp}, 'StopTime', stg.eqt);
 33    set(configsetObj{number_exp}.CompileOptions,...
 34        'DimensionalAnalysis', stg.dimenanal);
 35    set(configsetObj{number_exp}.CompileOptions,...
 36        'UnitConversion', stg.UnitConversion);
 37    set(configsetObj{number_exp}.SolverOptions,...
 38        'AbsoluteToleranceScaling', stg.abstolscale);
 39    set(configsetObj{number_exp}.SolverOptions,...
 40        'RelativeTolerance', stg.reltol);
 41    set(configsetObj{number_exp}.SolverOptions,...
 42        'AbsoluteTolerance', stg.abstol);
 43    set(configsetObj{number_exp}.SolverOptions, 'OutputTimes', stg.eqt);
 44    set(configsetObj{number_exp}, 'TimeUnits', stg.simtime);
 45    set(configsetObj{number_exp}.SolverOptions,...
 46        'MaxStep', stg.maxstepeq);
 47    
 48    set(configsetObj{number_exp}.SolverOptions,...
 49        'AbsoluteToleranceStepSize', stg.abstolstepsize_eq);
 50    
 51    
 52    model_exp = model_run{number_exp};
 53    config_exp = configsetObj{number_exp};
 54    
 55    save(model_exp_eq + number_exp + ".mat",'model_exp','config_exp')
 56    
 57    sbiosaveproject(model_exp_eq + number_exp + ".sbproj",'model_exp')
 58    
 59    set(configsetObj{number_exp}, 'StopTime', sbtab.sim_time(number_exp));
 60    
 61    set(configsetObj{number_exp}.SolverOptions, 'OutputTimes',...
 62        Data(number_exp).Experiment.t);
 63    
 64    set(configsetObj{number_exp}.SolverOptions, 'MaxStep', stg.maxstep);
 65    
 66    for n = 1:size(output,2)
 67        
 68        m = 0;
 69        for k = 1:size(model_run{number_exp}.species,1)
 70            if model_run{number_exp}.species(k).name == string(output{1,n})
 71                model_run{number_exp}.species(k).BoundaryCondition = 1;
 72                m = 1;
 73            end
 74        end
 75        
 76        if m == 0
 77            addspecies (model_run{number_exp}.Compartments(1),...
 78                char(output{1,n}),0,...
 79                'InitialAmountUnits',sb.Output.Unit{n});
 80        end
 81        
 82        addrule(model_run{number_exp}, char(output_value{1,n}),...
 83            'repeatedAssignment');
 84    end
 85    
 86    for j = 1:size(input_species,2)
 87        
 88        input_indexcode = str2double(strrep(input_species(j),'S',''));
 89        input_name = string(model_run{number_exp}.species(1 +...
 90                input_indexcode).name);
 91        
 92        if size(input_time{j},2) < 100
 93            
 94            model_run{number_exp}.species(...
 95                1 + input_indexcode).BoundaryCondition = 1;
 96            for n = 1:size(input_time{j},2)
 97                if ~isnan(input_time{j}(n))
 98                    
 99                    addparameter(model_run{number_exp},char("time_event_t_" + j + "_" +  n),...
100                        str2double(string(input_time{j}(n))),...
101                        'ValueUnits',char(stg.simtime));
102                    
103                    addparameter(model_run{number_exp},char("time_event_r_" + j + "_" +  n),...
104                        str2double(string(input_value{j}(n))),...
105                        'ValueUnits',char(model_run{number_exp}.species(1 +...
106                        input_indexcode).InitialAmountUnits));
107                    
108                    addevent(model_run{number_exp}, ...
109                        char("time>=time_event_t_" + j + "_" +  n),...
110                        cellstr(sbtab.datasets(number_exp).output_location{1} +...
111                        "." + input_name + " = time_event_r_" + j + "_" +  n));
112
113                end
114            end
115        else
116            
117            addrule(model_run{number_exp}, char(sbtab.datasets(...
118                number_exp).output_location{1} + "." + input_name +...
119                "=" + string(model_run{number_exp}.name)+ "_input" + ...
120                number_exp + "_" + input_name + "(time)"), 'repeatedAssignment');
121        end
122    end
123    
124    model_exp = model_run{number_exp};
125    config_exp = configsetObj{number_exp};
126    
127    save(model_exp_default + number_exp + ".mat",'model_exp','config_exp')
128
129    sbiosaveproject(model_exp_default + number_exp + ".sbproj",'model_exp')
130    
131    set(configsetObj{number_exp}.SolverOptions,'OutputTimes', []);
132    set(configsetObj{number_exp}.SolverOptions,'MaxStep', stg.maxstepdetail);
133    
134    model_exp = model_run{number_exp};
135    config_exp = configsetObj{number_exp};
136    
137    save(model_exp_detail + number_exp + ".mat",'model_exp','config_exp')
138    
139end
140end

Creates two .mat files for each experiment, one for the equilibrium simulation run and one for the proper simulation. These files have all the added rules, species and parameters needed depending on the inputs and outputs specified on the SBtab.