Setup and Import

f_user_input

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:4,7]),...
 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(7),analysis_text)
 94        stg.import = true;
 95        stg.save_results = false;
 96        stg.plot = false;
 97    end
 98elseif any(contains(analysis_options(5:6),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(5),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(6),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.Assignment{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_value{nOutput} = ...
173                {convertStringsToChars(...
174                string(sb.Output.Location{m}) + "." +...
175                string(sb.Output.Name{m}) + " = " +...
176                string(sb.Output.Formula{m}))};
177            
178            sbtab.datasets(n).output_unit{nOutput} = sb.Output.Unit{m};
179
180            sbtab.datasets(n).output_name{nOutput} = ...
181                sb.Output.Name(m);
182            sbtab.datasets(n).output_ID{nOutput} = ...
183                sb.Output.ID(m);
184            sbtab.datasets(n).output_location{nOutput} = ...
185                sb.Output.Location(m);
186        end
187    end
188    sbtab.datasets(n).stg.outnumber = nOutput;
189    sbtab.datasets(n).start_amount = cat(2,startAmountName(:)...
190        ,transpose([startamount{:}]),species_INP_matcher);
191end
192
193if isfield(sb,"Expression")
194    for m = 1:size(sb.Expression.ID,1)
195        if isfield(sb.Expression,'Formula')
196            if isa(sb.Expression.Formula{m},'double')
197                addspecies (modelobj, char(sb.Expression.Name(m)),...
198                    str2double(string(sb.Expression.Formula{m})),...
199                    'InitialAmountUnits',sb.Expression.Unit{m});
200            else
201                try
202                    addspecies (modelobj, char(sb.Expression.Name(m)),0,...
203                        'InitialAmountUnits',sb.Expression.Unit{m});
204                catch
205                end
206                addrule(modelobj, char({convertStringsToChars(...
207                    string(sb.Expression.Location{m}) + "." +...
208                    string(sb.Expression.Name{m}) + " = " +...
209                    string(sb.Expression.Formula{m}))}),...
210                    'repeatedAssignment');
211            end
212        else
213            addparameter(modelobj,char(sb.Expression.Name(m)),...
214                str2double(string(sb.Expression.DefaultValue{m})),...
215                'ValueUnits',sb.Expression.Unit{m});
216        end
217    end
218end
219
220if isfield(sb,"Input")
221    for m = 1:size(sb.Input.ID,1)
222        if isfield(sb.Input,'Formula')
223            if isa(sb.Input.Formula{m},'double')
224                addspecies (modelobj, char(sb.Input.Name(m)),...
225                    str2double(string(sb.Input.DefaultValue{m})),...
226                    'InitialAmountUnits',sb.Input.Unit{m});
227            else
228                try
229                    addspecies (modelobj, char(sb.Input.Name(m)),0,...
230                        'InitialAmountUnits',sb.Input.Unit{m});
231                catch
232                end
233                addrule(modelobj, char({convertStringsToChars(...
234                    string(sb.Input.Location{m}) + "." +...
235                    string(sb.Input.Name{m}) + " = " +...
236                    string(sb.Input.DefaultValue{m}))}),...
237                    'repeatedAssignment');
238            end
239        else
240            addparameter(modelobj,char(sb.Input.Name(m)),...
241                str2double(string(sb.Input.DefaultValue{m})),...
242                'ValueUnits',sb.Input.Unit{m});
243        end
244    end
245end
246
247if isfield(sb,"Constant")
248    for m = 1:size(sb.Constant.ID,1)
249        addparameter(modelobj,char(sb.Constant.Name(m)),...
250            str2double(string(sb.Constant.Value{m})),...
251            'ValueUnits',sb.Constant.Unit{m});
252    end
253end
254
255sbproj_model = mmf.model.data.sbproj_model;
256matlab_model = mmf.model.data.mat_model;
257data_model = mmf.model.data.data_model; 
258xml_model = mmf.model.data.xml_model; 
259
260sbiosaveproject(sbproj_model,'modelobj')
261
262save(matlab_model,'modelobj')
263
264save(data_model,'Data','sbtab','sb')
265
266sbmlexport(modelobj,xml_model)
267
268end

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    output_unit = sbtab.datasets(number_exp).output_unit;
 25    input_time = sbtab.datasets(number_exp).input_time;
 26    input_value = sbtab.datasets(number_exp).input_value;
 27    input_species = sbtab.datasets(number_exp).input;
 28    
 29    
 30    model_run{number_exp} = copyobj(modelobj);
 31    configsetObj{number_exp} = getconfigset(model_run{number_exp});
 32    
 33    set(configsetObj{number_exp}, 'MaximumWallClock', stg.maxt);
 34    set(configsetObj{number_exp}, 'StopTime', stg.eqt);
 35    set(configsetObj{number_exp}.CompileOptions,...
 36        'DimensionalAnalysis', stg.dimenanal);
 37    set(configsetObj{number_exp}.CompileOptions,...
 38        'UnitConversion', stg.UnitConversion);
 39    set(configsetObj{number_exp}.SolverOptions,...
 40        'AbsoluteToleranceScaling', stg.abstolscale);
 41    set(configsetObj{number_exp}.SolverOptions,...
 42        'RelativeTolerance', stg.reltol);
 43    set(configsetObj{number_exp}.SolverOptions,...
 44        'AbsoluteTolerance', stg.abstol);
 45    set(configsetObj{number_exp}.SolverOptions, 'OutputTimes', stg.eqt);
 46    set(configsetObj{number_exp}, 'TimeUnits', stg.simtime);
 47    set(configsetObj{number_exp}.SolverOptions,...
 48        'MaxStep', stg.maxstepeq);
 49    
 50    set(configsetObj{number_exp}.SolverOptions,...
 51        'AbsoluteToleranceStepSize', stg.abstolstepsize_eq);
 52    
 53    
 54    model_exp = model_run{number_exp};
 55    config_exp = configsetObj{number_exp};
 56    
 57    save(model_exp_eq + number_exp + ".mat",'model_exp','config_exp')
 58    
 59    sbiosaveproject(model_exp_eq + number_exp + ".sbproj",'model_exp')
 60    
 61    set(configsetObj{number_exp}, 'StopTime', sbtab.sim_time(number_exp));
 62    
 63    set(configsetObj{number_exp}.SolverOptions, 'OutputTimes',...
 64        Data(number_exp).Experiment.t);
 65    
 66    set(configsetObj{number_exp}.SolverOptions, 'MaxStep', stg.maxstep);
 67    
 68    for n = 1:size(output,2)
 69        
 70        m = 0;
 71        for k = 1:size(model_run{number_exp}.species,1)
 72            if model_run{number_exp}.species(k).name == string(output{1,n})
 73                model_run{number_exp}.species(k).BoundaryCondition = 1;
 74                m = 1;
 75            end
 76        end
 77        
 78        if m == 0
 79            if strcmp( output_unit{1,n},'dimensionless' )
 80                warning('off','SimBiology:InvalidSpeciesInitAmtUnits')
 81            else
 82                warning('on','SimBiology:InvalidSpeciesInitAmtUnits')
 83            end
 84            addspecies (model_run{number_exp}.Compartments(1),...
 85                char(output{1,n}),0,...
 86                'InitialAmountUnits',output_unit{1,n});
 87        end
 88        
 89        addrule(model_run{number_exp}, char(output_value{1,n}),...
 90            'repeatedAssignment');
 91    end
 92    
 93    for j = 1:size(input_species,2)
 94        
 95        input_indexcode = str2double(strrep(input_species(j),'S',''));
 96        input_name = string(model_run{number_exp}.species(1 +...
 97                input_indexcode).name);
 98        
 99        if size(input_time{j},2) < 100
100            
101            model_run{number_exp}.species(...
102                1 + input_indexcode).BoundaryCondition = 1;
103            for n = 1:size(input_time{j},2)
104                if ~isnan(input_time{j}(n))
105                    
106                    addparameter(model_run{number_exp},char("time_event_t_" + j + "_" +  n),...
107                        str2double(string(input_time{j}(n))),...
108                        'ValueUnits',char(stg.simtime));
109                    
110                    addparameter(model_run{number_exp},char("time_event_r_" + j + "_" +  n),...
111                        str2double(string(input_value{j}(n))),...
112                        'ValueUnits',char(model_run{number_exp}.species(1 +...
113                        input_indexcode).InitialAmountUnits));
114                    
115                    addevent(model_run{number_exp}, ...
116                        char("time>=time_event_t_" + j + "_" +  n),...
117                        cellstr(sbtab.datasets(number_exp).output_location{1} +...
118                        "." + input_name + " = time_event_r_" + j + "_" +  n));
119
120                end
121            end
122        else
123            
124            addrule(model_run{number_exp}, char(sbtab.datasets(...
125                number_exp).output_location{1} + "." + input_name +...
126                "=" + string(model_run{number_exp}.name)+ "_input" + ...
127                number_exp + "_" + input_name + "(time)"), 'repeatedAssignment');
128        end
129    end
130    
131    model_exp = model_run{number_exp};
132    config_exp = configsetObj{number_exp};
133    
134    save(model_exp_default + number_exp + ".mat",'model_exp','config_exp')
135
136    sbiosaveproject(model_exp_default + number_exp + ".sbproj",'model_exp')
137    
138    set(configsetObj{number_exp}.SolverOptions,'OutputTimes', []);
139    set(configsetObj{number_exp}.SolverOptions,'MaxStep', stg.maxstepdetail);
140    
141    model_exp = model_run{number_exp};
142    config_exp = configsetObj{number_exp};
143    
144    save(model_exp_detail + number_exp + ".mat",'model_exp','config_exp')
145    
146end
147end

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.